Java AES-128加密1个块(16字节)的输出结果为2个块(32字节)

8
我使用以下代码对16字节的单个块进行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("字符串长度:" + (Data.getBytes()).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("输出长度:" + encVal.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,Commons Codec的Base64或Java 8中的Base64,而不是(sun.misc.BASE64Encoder/Decoder类是内部的,在Java 8中即将被弃用,在Java 9中将会被移除。)。 - ntoskrnl
1个回答

15

Cipher.getInstance("AES") 返回一个使用PKCS #5填充的密码器。无论何时,当明文已经是块大小的倍数时,都会添加填充块。

Cipher.getInstance() 调用中明确指定您的意图,以避免依赖默认值并可能引起混淆:

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

你还会发现你正在使用ECB模式,这几乎在任何情况下都是一个糟糕的选择。


但它仍然返回32个字符编码的字符串。 - Asad Rao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接