Java AES-128 encryption of 1 block (16 byte) returns 2 blocks(32 byte) as output
我使用以下代码进行AES-128加密,以编码16字节的单个块,但编码值的长度为2个32字节的块。 我错过了什么吗?
1 | plainEnc = AES.encrypt("thisisapassword!"); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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; } } |
在
1 | Cipher.getInstance("AES/ECB/NoPadding"); |
您还将看到您正在使用ECB模式,这在几乎任何情况下都是一个糟糕的选择。