我从 YouTube 视频中获取此代码。通过此代码,我正确加密了图像,但无法解密该图像。 谁能帮我吗???
加密代码
FileInputStream file = new FileInputStream("src/image/A.jpg");
FileOutputStream output = new FileOutputStream("src/image/AA.jpg");
byte j[]="12345678".getBytes();
SecretKeySpec kye = new SecretKeySpec(j,"DES");
System.out.println(kye);
Cipher enc = Cipher.getInstance("DES");
enc.init(Cipher.ENCRYPT_MODE,kye);
CipherOutputStream cos = new CipherOutputStream(output, enc);
byte[] buf = new byte[1024];
int read;
while((read=file.read(buf))!=-1){
cos.write(buf,0,read);
}
file.close();
output.flush();
cos.close();
解密代码
FileInputStream file = new FileInputStream("src/image/AA.jpg");
FileOutputStream output = new FileOutputStream("src/image/AAA.jpg");
byte j[]="12345678".getBytes();
SecretKeySpec kye = new SecretKeySpec(j,"DES");
System.out.println(kye);
Cipher enc = Cipher.getInstance("DES");
enc.init(Cipher.DECRYPT_MODE,kye);
CipherOutputStream cos = new CipherOutputStream(output, enc);
byte[] buf = new byte[1024];
int read;
while((read=file.read(buf))!=-1){
cos.write(buf,0,read);
}
file.close();
output.flush();
cos.close();
谢谢
最佳答案
这是一篇相对较旧的帖子,但我想我可以提供帮助。
首先,您应该将图像编码为 ASCII 表示形式。我会推荐 Base64。 Base64 加密更容易且错误更少。 (也许没那么强,但这取决于您的需求)
Base64 的好处是它使用的字母表。完全没有奇怪的符号。
1) 通过将图像与 ImageIO 类一起写入,将图像转换为 ByteArrayOutputStream。
2)将字节数组编码为Base64字符串
3)像上面那样加密(不要忘记刷新)。
4) 将字节保存到新文件中。删除旧的。
相应解密......
请注意,编码为 Base64 会耗尽您的内存,并且由于 Base64 和加密开销,文件会变得更大。
希望有帮助!
关于java - 使用java解密图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20737376/