使用AES加密和解密图像的正确方法

编辑:::问题中的代码有效,但是一旦在相机中拍摄了图像,返回活动大约需要10秒钟。我放弃了这种方法,而是使用Facebook的隐秘库对图像进行加密和解密。


我看了很多示例,但是仍然找不到解决正确加密和解​​密的方法。我以为我在互联网上使用一些随机代码时是正确的,但是在解码时会收到BadPadding异常。

所以,我正在努力解决。正如大多数人在SO上所建议的那样,我正在关注以下问题(但是此代码显示了如何加密字符串)。有人可以帮我加密和解密图像吗?问题中的代码适用于图像吗?

这是我到目前为止所做的:

//用于存储iv和密码的全局arraylist

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和加密的byte [] s。因为,正如链接中的答案所示,我在解密时应该使用相同的iv。

//解码文件

//我在此方法内调用了一个重载的encodeFile方法。

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()提供什么参数?

让我知道您是否需要其他代码。

回答:

问题中的代码有效,但是一旦在相机中拍摄了图像,返回活动大约需要10秒钟。我放弃了这种方法,而是使用Facebook的隐秘库对图像进行加密和解密。

以上是 使用AES加密和解密图像的正确方法 的全部内容, 来源链接: utcz.com/qa/407704.html

回到顶部