2011-10-15 100 views
2

如何使用AES加密整個字符串。我有下面的代碼只加密了公認:(第一空間。我怎樣才能解決這個問題?謝謝Java AES加密整個字符串

SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES"); 
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE"); 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
    String result = new String(cipher.doFinal(message.getBytes())); 
    System.out.println("Encrypted:" + result); 

編輯 OMG,我不能相信這一點,我怎麼能錯過這個:(其因我的掃描儀正在接下來,而不是nextLine ...這是多麼令人尷尬,這一直困擾着我整天,只有現在我真的想考慮檢查問題解決:)謝謝大家

+0

例如加密的「hello world」和「hello」都是「sÀÊç$û?dgÞÏ┌q°(Ã」當鹽是「1111111111111111」 – Cody

+3

時不要將加密的字符串數據視爲字符串 - **它是不是。**如果你想得到一個人類可讀的表示,把字符串轉換爲base64或者一個十六進制字符串,然後打印出來。 –

+0

是這個原因爲什麼我錯過了剩餘的消息嗎?它不會影響我太多if這是人類readeble與否,實際上id可能更喜歡它,如果它不是:) – Cody

回答

6

我沒有看到任何錯誤的代碼除外試圖使用new String(byte[])打印任意byte[]。請嘗試此尺寸:

public static byte[] encrypt(String message) throws Exception 
{ 
    String salt = "1111111111111111"; 
    SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES"); 
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE"); 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
    return cipher.doFinal(message.getBytes()); 
} 

public static void main (String[] args) throws Exception 
{ 
    String hello = Arrays.toString(encrypt("hello")); 
    System.out.println("hello:" + hello); 
    String helloWorld = Arrays.toString(encrypt("hello world")); 
    System.out.println("hello world:" + helloWorld); 
} 

它打印:

hello:[115, -73, -46, -121, 36, -106, -99, 100, 103, -24, -40, -38, 113, -8, 40, -57] 
hello world:[5, 88, -31, 115, 4, 48, -75, 44, 83, 21, 105, -67, 78, -53, -13, -28] 

我想我們都同意,這是兩個不同的字節數組。