2013-08-26 108 views
4

我使用以下代碼進行AES-128加密,以編碼16字節的單個塊,但編碼的長度值給出2個32字節的塊。我錯過了什麼嗎?1塊(16字節)的Java AES-128加密返回2塊(32字節)作爲輸出

 

    plainEnc = AES.encrypt("thisisapassword!"); 

 

    import java.security.*; 
    import java.security.spec.InvalidKeySpecException; 
    import javax.crypto.*; 
    import sun.misc.*; 

    public class AES { 

     private static final String ALGO = "AES"; 
     private static final byte[] keyValue = 
      new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't', 
    'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' }; 

    public static String encrypt(String Data) throws Exception { 
      System.out.println("string length: " + (Data.getBytes()).length); //length = 16 
      Key key = generateKey(); 
      Cipher chiper = Cipher.getInstance(ALGO); 
      chiper.init(Cipher.ENCRYPT_MODE, key); 
      byte[] encVal = chiper.doFinal(Data.getBytes()); 
      System.out.println("output length: " + encVal.length); //length = 32 
      String encryptedValue = new BASE64Encoder().encode(encVal); 
      return encryptedValue; 
     } 

     public static String decrypt(String encryptedData) throws Exception { 
      Key key = generateKey(); 
      Cipher chiper = Cipher.getInstance(ALGO); 
      chiper.init(Cipher.DECRYPT_MODE, key); 
      byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData); 
      byte[] decValue = chiper.doFinal(decordedValue); 
      String decryptedValue = new String(decValue); 
      return decryptedValue; 
     } 
     private static Key generateKey() throws Exception { 
      Key key = new SecretKeySpec(keyValue, ALGO); 
      return key; 
    } 

} 
+0

考慮使用[Guava]的BaseEncoding(http://code.google.com/p/guava-libraries/),[Commons Codec]的Base64(http://commons.apache.org/proper/commons-編解碼器/)或[Java 8]中的Base64(http://hg.openjdk.java.net/jdk8/jdk8/jdk/raw-file/tip/src/share/classes/java/util/Base64.java)而不是(內部的,即將被棄用的(Java 8)和-removed(Java 9))sun.misc.BASE64Encoder/Decoder類。 – ntoskrnl

回答

7

Cipher.getInstance("AES")返回使用PKCS#5填充的加密。在所有情況下都會添加此填充 - 當明文已經是塊大小的倍數時,將添加整個填充塊。

明確指定你的意圖在Cipher.getInstance()調用避免依賴於默認值,並有可能造成混亂:

Cipher.getInstance("AES/ECB/NoPadding"); 

您也將看到您正在使用ECB模式,這是一個不錯的選擇在幾乎任何情況。

+0

謝謝你,你救了我的命。 – user2717511

相關問題