我有一个应用程序可以加密图像的像素,然后解密它们。
加密代码为:
File file = new File(fullPath, "uoc" +format +".png");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteBuffer bb = ByteBuffer.allocate(image.getByteCount());
image.copyPixelsToBuffer(bb);
byte[] b = bb.array();
image.copyPixelsFromBuffer(ByteBuffer.wrap(encrypt_image(b, password)));
image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b2 = baos.toByteArray();
bos.write(b2);
bos.flush();
bos.close();
现在我可以打开文件并看到噪音,这正是我想要的。
一旦成功,我需要解密图像的内容,但没有成功:(
我的代码与要加密的代码类似:
ByteBuffer bb = ByteBuffer.allocate(image_file.getByteCount());
image_file.copyPixelsToBuffer(bb);
byte[] b = bb.array();
// Decrypt
decryptedData = Security.decrypt(key,b);
image_file.copyPixelsFromBuffer(ByteBuffer.wrap(decryptedData));
问题出在 Security.decrypt(key,b)
中,因为它抛出 pad bloc 损坏异常。
我的加密算法是:
public static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
和解密:
public static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
我已经检查过这两种情况下的 key 是相同的。
有人知道如何解决这个问题吗?
编辑:
我尝试了下一个代码,但它也抛出异常:
ByteBuffer bb = ByteBuffer.allocate(image.getByteCount());
image.copyPixelsToBuffer(bb);
byte[] b = bb.array();
image.copyPixelsFromBuffer(ByteBuffer.wrap(Security.encrypt(Security.getRaw(password),b)));
//****
ByteBuffer bb2 = ByteBuffer.allocate(image.getByteCount());
image.copyPixelsToBuffer(bb2);
byte[] b_aux = bb.array();
// Decrypt
image.copyPixelsFromBuffer(ByteBuffer.wrap(Security.decrypt(Security.getRaw(password),b_aux)));
//*****
image.compress(Bitmap.CompressFormat.PNG, 100, baos);
现在我完全迷失了,我的最终项目取决于这个算法。
谁能帮帮我?
最佳答案
问题是加密的字节不再适合图像字节,数组大小将丢失,等等。不能立即将字节写入文件吗?
关于java - 解密位图的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20871030/