【发布时间】:2014-11-21 10:06:45
【问题描述】:
编辑 ::: 问题中的代码有效,但是一旦在相机中拍摄图像,返回活动大约需要 10 秒。我放弃了这种方法,使用 Facebook 的 Conceal Library 来加密和解密图像。链接到 Facebook 的解决方案:Facebook Conceal - Image Encryption and Decryption
我查看了很多示例,但仍然无法找到正确加密和解密的方法。当我在互联网上使用一些随机代码时,我认为我得到了正确的结果,但是在解码时,我得到了一个 BadPadding 异常。
所以,我正在努力解决它。正如大多数人在 SO 上所建议的那样,我正在关注以下问题(但此代码显示了如何加密字符串)。有人可以帮我加密和解密图像吗?问题中的代码是否适用于图片?
问题链接:Java 256-bit AES Password-Based Encryption
这是我到目前为止所做的:
//全局arraylist存储iv和cipher
static ArrayList<byte[]> ivandcipher = new ArrayList<byte[]>();
//生成密钥
public static SecretKey generateKey() throws NoSuchAlgorithmException {
char[] password = { 'a', 'b', 'c', 'd', 'e' };
byte[] salt = { 1, 2, 3, 4, 5 };
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = null;
try {
tmp = factory.generateSecret(spec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
yourKey = new SecretKeySpec(tmp.getEncoded(), "AES");
return yourKey;
}
//编码文件
//byte[] fileData,包含转换为byte[]的位图(图像)
public static ArrayList<byte[]> encodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] encrypted = null;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, yourKey);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
encrypted = cipher.doFinal(fileData);
ivandcipher.clear();
ivandcipher.add(iv);
ivandcipher.add(encrypted);
return ivandcipher;
}
为什么我要在 ivandcipher 中添加 iv 和加密的字节 []。因为,正如链接中的答案所暗示的那样,我在解密时应该使用相同的 iv。
//解码文件
//我在这个方法里面调用了一个重载的decodeFile方法..请注意
private Bitmap decodeFile(String filename) {
try {
yourKey = generateKey();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
try {
byte[] decodedData = decodeFile(yourKey, readFile(filename));
Bitmap bitmap = bytesToBitmap(decodedData);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//重载的decodeFile方法
public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] decrypted = null;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(ivandcipher.get(0)));
decrypted = cipher.doFinal(fileData);
return decrypted;
}
我猜问题出在 fileData[] 上,我无法正确加密和解密。对于上面链接的答案中所示的字符串,即
byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));
cipher.doFinal() 的参数应该是什么?
如果您需要任何其他代码,请告诉我。
【问题讨论】:
-
原因基本上是你复制了“互联网上的一些随机代码”,没有让它工作,现在我们应该修复它。
-
@ntoskrnl,我没有要求任何人修复它。我要求您帮助理解它并使其发挥作用。顺便说一句,我在问题中发布的代码不是随机的,它来自我在问题中发布的链接。
-
您的代码应该可以工作。可能是 readFile(filename) 中的问题。它会返回任何东西吗?你如何保存到文件/从文件中读取?
标签: java android encryption cryptography