2013-12-23 61 views
1

我從YouTube視頻中獲取此代碼。從此代碼我正確加密圖像,但無法解密該圖像。 任何人都可以幫助我?使用java解密圖像

加密代碼

 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(); 

謝謝

+0

如果你無法解密它,爲什麼你確定你正確地加密了它? – Bandrami

+0

你應該在'close()'之前'flush()'(如果你要'flush()')。 –

+0

,因爲我有一個圖像無效的圖像。 有什麼問題嗎? – NoughT

回答

1

這是一個relativly老的文章,但我想我可以提供幫助。

首先,您應該將圖像編碼爲ASCII表示形式。我會推薦Base64。加密Base64時,它更容易,錯誤更少。 (也許不那麼強,但取決於你的需求)

Base64的好處是它使用的字母表。沒有怪異的符號。

1)將圖像轉換爲ByteArrayOutputStream,並將其與ImageIO類一起寫入。

2)編碼的字節數組爲Base64字符串

3)加密等你沒有上述(不要忘記沖洗)。

4)將字節保存到新文件。刪除舊的。

解密相應.....

注意,編碼爲Base64編碼將炸燬你的內存和文件會更大,因爲Base64編碼和加密開銷。

希望有幫助!