Zla*_*tko 15 encryption android
我正在关注Google提供的ConfirmCredential Android示例,但它只显示了如何加密数据.当我尝试解密它时,我得到例外:
java.security.InvalidKeyException: IV required when decrypting. Use IvParameterSpec or AlgorithmParameters to provide it.
Run Code Online (Sandbox Code Playgroud)
我使用以下代码:
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"));
Run Code Online (Sandbox Code Playgroud)
在行中抛出异常:
cipher.init(Cipher.DECRYPT_MODE, secretKey);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,任何关于解密的正确方法的想法?
Qia*_*ian 15
基本上,您必须为解密模式传递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(....)
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用Base64对IV数据进行编码,并将其保存在共享首选项下,而不是将其保存在文件下.
在这两种情况下,如果你采用版本的Android M的新的全备份功能,请记住,这个数据应该不被允许备份/恢复,因为当用户重新安装应用程序或其他设备上安装应用程序是无效的.