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; } }
考慮使用[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