我正在关注确认凭证 http://developer.android.com/samples/ConfirmCredential/index.htmlGoogle 提供的 Android 示例,但仅展示了如何加密数据。当我尝试解密它时,出现异常:
java.security.InvalidKeyException: IV required when decrypting. Use IvParameterSpec or AlgorithmParameters to provide it.
我使用以下代码:
String transforation = KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7;
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null);
// encrypt
Cipher cipher = Cipher.getInstance(transforation);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
String encriptedPassword = cipher.doFinal("Some Password".getBytes("UTF-8"));
// decrypt
cipher = Cipher.getInstance(transforation);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
String password = new String(cipher.doFinal(encriptedPassword), "UTF-8"));
异常在以下行抛出:
cipher.init(Cipher.DECRYPT_MODE, secretKey);
知道在这种情况下进行解密的正确方法是什么吗?
基本上,您必须传递解密模式的 IvParameterSpec,而您不应手动将其设置为加密模式。
所以这就是我所做的并且效果很好:
private initCipher(int mode) {
try {
byte[] iv;
mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7);
IvParameterSpec ivParams;
if(mode == Cipher.ENCRYPT_MODE) {
mCipher.init(mode, generateKey());
ivParams = mCipher.getParameters().getParameterSpec(IvParameterSpec.class);
iv = ivParams.getIV();
fos = getContext().openFileOutput(IV_FILE, Context.MODE_PRIVATE);
fos.write(iv);
fos.close();
}
else {
key = (SecretKey)keyStore.getKey(KEY_NAME, null);
File file = new File(getContext().getFilesDir()+"/"+IV_FILE);
int fileSize = (int)file.length();
iv = new byte[fileSize];
FileInputStream fis = getContext().openFileInput(IV_FILE);
fis.read(iv, 0, fileSize);
fis.close();
ivParams = new IvParameterSpec(iv);
mCipher.init(mode, key, ivParams);
}
mCryptoObject = new FingerprintManager.CryptoObject(mCipher);
} catch(....)
}
您还可以使用 Base64 对 IV 数据进行编码,并将其保存在共享首选项下,而不是将其保存在文件下。
无论哪种情况,如果您使用了 Android M 的新完整备份功能,请记住此数据应该NOT允许备份/恢复,因为当用户重新安装应用程序或在其他设备上安装应用程序时,它会无效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)