我尝试使用不同的文件名加密并将文件保存到外部存储器中的相同位置。但我使用的方式似乎是错误的。请帮助别人。
public static void encrypt(SecretKey secretKey, String filePath, IvParameterSpec iv){
try {
String file = "";
// Here you read the cleartext.
FileInputStream fis = new FileInputStream(filePath);
// This stream write the encrypted text. This stream will be wrapped by another stream.
//String filePath2 = filePath+"enc";
file = filePath.substring(0,filePath.length()-5)+"enc.jpeg";
FileOutputStream fos = new FileOutputStream(file);
Log.i(TAG, "Uri = "+file);
// Create cipher
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
byte[] d = new byte[8];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}catch(IOException e){
e.printStackTrace();
}catch (NoSuchAlgorithmException e){
e.printStackTrace();
}catch(NoSuchPaddingException e){
e.printStackTrace();
}catch(InvalidKeyException e){
e.printStackTrace();
}/*catch (InvalidAlgorithmParameterException e){
e.printStackTrace();
}*/
}
包含读取和写入权限的清单文件。
答案 0 :(得分:1)
您指定“AES / ECB / NoPadding”。
对于ECB,没有iv,因此无需在调用encrypt
方法时提供一个。 ECB模式不安全,请参阅ECB mode,向下滚动到Penguin。
AES是块密码,因此它一次加密块大小的部分,因此输入需要是块大小的倍数。 Padding透明地完成了这一操作,但你指定了“NoPadding”,因此输入文件大小只是块大小的精确倍数,对于16字节的AES。而是使用PKCS#7(有些被称为PKCS#5)填充。
最简单的解决方案是使用一个库,将安全加密的所有元素放在一起,包括密码派生,随机iv,填充,加密验证。考虑RNCryptor,它提供了所有这些加上版本控制。有关详细信息,请参阅RNCryptor README和RNCryptor-Spec。