【发布时间】:2020-08-02 15:46:01
【问题描述】:
在我的应用程序中,我想用 AES、CBC 下载加密文件,然后将此文件解密到我的应用程序中!
我在我的应用程序中编写了以下代码,但在应用程序之后在logcat 中显示了这个错误:
E/newDecryptLog: 0 : Key length not 128/192/256 bits.
我的密码是: 7BOF%aZQMpfJ#2wUS*S6!@K+ZB$Sz+J0
我的代码是:
public class EncryptDecryptUtils {
public static EncryptDecryptUtils instance = null;
private static PrefUtils prefUtils;
public static EncryptDecryptUtils getInstance(Context context) {
if (null == instance)
instance = new EncryptDecryptUtils();
if (null == prefUtils)
prefUtils = PrefUtils.getInstance(context);
return instance;
}
public static byte[] encode(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] data = yourKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length, KEY_SPEC_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
return cipher.doFinal(fileData);
}
public static byte[] decode(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] decrypted;
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, PROVIDER);
cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
decrypted = cipher.doFinal(fileData);
return decrypted;
}
public void saveSecretKey(SecretKey secretKey) {
String encodedKey = Base64.encodeToString(secretKey.getEncoded(), Base64.NO_WRAP);
prefUtils.saveSecretKey(encodedKey);
}
public SecretKey getSecretKey() {
String encodedKey = "7BOF%aZQMpfJ#2wUS*S6!@K+ZB$Sz+J0";
if (null == encodedKey || encodedKey.isEmpty()) {
SecureRandom secureRandom = new SecureRandom();
KeyGenerator keyGenerator = null;
try {
keyGenerator = KeyGenerator.getInstance(KEY_SPEC_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keyGenerator.init(OUTPUT_KEY_LENGTH, secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
saveSecretKey(secretKey);
return secretKey;
}
byte[] decodedKey = Base64.decode(encodedKey, Base64.NO_WRAP);
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, KEY_SPEC_ALGORITHM);
return originalKey;
}
}
我在上面的课程中使用了这个代码:
@Nullable
public static byte[] decryptFile(Context context, String fileName) {
try {
byte[] fileData = FileUtils.readFile(FileUtils.getFilePath(context, fileName));
byte[] decryptedBytes = EncryptDecryptUtils.decode(EncryptDecryptUtils.getInstance(context).getSecretKey(), fileData);
return decryptedBytes;
} catch (Exception e) {
Log.e("newDecryptLog", "0 : " + e.getMessage());
}
return null;
}
但是当使用这个 run catch 方法并显示上面的错误!
我该如何解决?
【问题讨论】:
标签: java android file encryption