2012-02-28 29 views
1

我試圖開發一個簡單的加密/解密程序。我遇到的問題是,當我嘗試解密加密的消息時,出現一條錯誤消息,指出使用密碼解密時,輸入長度必須是16的倍數。我在某處讀取加密的消息在將其轉換爲字符串之前可能需要進行編碼。我不知道如何做到這一點?或者如果有另一種方式可以幫助我一個人嗎?JAVA解密錯誤:需要輸入爲16的倍數

import java.security.InvalidAlgorithmParameterException; 
import java.security.InvalidKeyException; 
import java.security.Key; 
import java.security.NoSuchAlgorithmException; 

import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.KeyGenerator; 
import javax.crypto.NoSuchPaddingException; 


public class Cryption { 
    public static void cryption(String[] args, String message) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { 
     byte[] encodedKey = "ADBSJHJS12547896".getBytes(); 
     KeyGenerator keyGen = KeyGenerator.getInstance("AES"); 
     Key aesKey = keyGen.generateKey(); 

     System.out.println("CheckType: "+ Global.checkType); 
     Cipher cipher = Cipher.getInstance("AES"); 
     cipher.init(Cipher.ENCRYPT_MODE, aesKey); 
     byte[] input = Global.message.getBytes(); 

     // Check if clicked Encrypted 
     if(Global.checkType==true) { 
      // Encrypt 
      byte[] messageEncrypted = cipher.doFinal(input); 
      System.out.println("Encrypted Text: " + messageEncrypted); 
      Global.encValue = messageEncrypted.toString(); 
     } 

     // Check if clicked Decrypted 
     if(Global.checkType==false) { 
      //String mes = message; 
      System.out.println(Global.message); 
      System.out.println("Char lenght " + Global.message.length()); 
      byte[] mesByte = Global.message.getBytes(); 


      // Decrypt 
      cipher.init(Cipher.DECRYPT_MODE, aesKey); 
      byte[] messageDecrypted = cipher.doFinal(mesByte); 
      System.out.println("Text Decrypted: " + new String(messageDecrypted)); 
     } 
    } 

} 

回答

1
Global.encValue = messageEncrypted.toString(); 

這是完全錯誤,因爲它只是調用byte []。toString(),它不會給你內容,只是一個帶有類名和哈希碼的東西。它在語義上也是錯誤的,因爲String首先不是二進制數據的容器。不要將加密文本轉換爲字符串。使用API​​給你的byte []數組。

+0

的答案我需要將數據轉換爲字符串,因爲此程序的GUI具有文本字段,用戶可以在其中輸入一些文本(說一個加密的消息)。因此,如果您最初對數據進行加密,則會將加密的消息吐出到字段中。然後我希望能夠解密來自同一領域的數據並讓它解出解密的消息。對於混淆和抱歉,如果我的邏輯沒有意義,因爲我是編程新手。 – scriptdiddy 2012-02-28 04:18:57

+1

@scriptdiddy將加密數據輸入到文本字段對我來說沒有任何意義,但如果這是一個真正的用例,您將不得不對其進行64位編碼。 – EJP 2012-02-28 05:04:28

相關問題