编辑:::问题中的代码工作,但一旦图像在相机中拍摄后,需要大约10秒才能恢复活动。我放弃了这种方法,并使用Facebook的隐藏库来加密和解密图像。链接到Facebook的解决方案:Facebook Conceal - Image Encryption and Decryption使用AES加密和解密图像的正确方法
我已经看过很多例子,但还是没能想出一个办法来获得加密和解密的权利。当我在互联网上使用一些随机代码时,我以为我知道它是正确的,但在解码时,我得到了BadPadding异常。
所以,我正在努力解决它。正如大多数人所建议的那样,我遵循以下问题(但是此代码显示如何加密字符串)。有人能帮我加密和解密图像吗?问题中的代码是否适用于图像?
链接到一个问题:Java 256-bit AES Password-Based Encryption
这里是我做了什么至今:
//全球ArrayList中存储IV和密码
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;
}
//编码文件
//字节[] FILEDATA,包含位图(图像)转换成字节[]
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;
}
为何我添加IV和加密的字节[] s到ivandcipher。因为,正如链接中的答案所暗示的,我应该在解密时使用相同的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()?
让我知道你是否需要任何其他代码。
downvote的任何理由?我明白这已被问了很多次,但我无法对我的图像进行适当的加密和解密。 – 2014-09-26 11:51:17
原因基本上是你复制了“在互联网上的一些随机代码”,没有得到它的工作,现在我们应该修复它。 – ntoskrnl 2014-09-26 11:57:55
@ntoskrnl,我不是要求任何人修复它。我在请求你的帮助,理解它并使之发挥作用。顺便说一下,我在问题中发布的代码不是随机的,而是来自我在问题中发布的链接。 – 2014-09-26 11:58:48