我的app中有下载文件的加密/解密机制。
此机制适用于Android 5.0-lollipop之前的所有Android设备和版本。
这是解密过程:
cipher.init(Cipher.DECRYPT_MODE, key);
fileInputStream = new FileInputStream(file);
cipherInputStream = new CipherInputStream(fileInputStream, cipher);
byte[] fileByte = new byte[(int) file.length()];
int j = cipherInputStream.read(fileByte);
return fileByte;
之前生成了密码和密钥,并在整个应用程序中使用:
key = new SecretKeySpec(keyValue, "AES");
try {
cipher = Cipher.getInstance("AES");
} catch (Exception e) {
e.printStackTrace();
}
当我在android 5.0中解密一个大约200,000字节的文件时,j(返回前的变量)大约是8000,远远低于200000,而在较旧的Android版本中,它完全等于解密的文件长度。
我发现问题在于解密。因为我可以加密android 5.0中的文件并在较旧的Android版本中解密它,但反之亦然。但是我发布了加密过程:
cipher.init(Cipher.ENCRYPT_MODE, AESutil.key);
cipherOutputStream = new CipherOutputStream(output, cipher);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
cipherOutputStream.write(data, 0, count);
}
提前致谢
答案 0 :(得分:2)
我的密码示例(L):
APPPATH是sd卡上我的应用程序目录的字符串
static void encrypt(File file, String pass) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(APPPATH+"/E_"+file.getName());
SecretKeySpec sks = new SecretKeySpec(pass.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
int b;
byte[] d = new byte[8];
while((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
cos.flush();
cos.close();
fis.close();
}
static void decrypt(File file, String pass) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(APPPATH+"/D_"+file.getName());
SecretKeySpec sks = new SecretKeySpec(pass.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
}