[英]Java AES-128 encryption of 1 block (16 byte) returns 2 blocks(32 byte) as output
I'm using the following code for AES-128 encryption to encode a single block of 16 byte but the length of the encoded value gives 2 blocks of 32 byte. 我使用以下代码进行AES-128加密,以编码16字节的单个块,但编码值的长度为2个32字节的块。 Am I missing something?
我错过了什么吗?
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; } }
Cipher.getInstance("AES")
returns a cipher that uses PKCS #5 padding. Cipher.getInstance("AES")
返回使用PKCS#5填充的密码。 This padding is added in all cases – when the plaintext is already a multiple of the block size, a whole block of padding is added. 在所有情况下都添加了此填充 - 当明文已经是块大小的倍数时,将添加整个填充块。
Specify your intentions explicitly in the Cipher.getInstance()
call to avoid relying on defaults and potentially causing confusion: 在
Cipher.getInstance()
调用中明确指定您的意图,以避免依赖于默认值并可能导致混淆:
Cipher.getInstance("AES/ECB/NoPadding");
You will also see that you are using ECB mode, which is a bad choice in almost any situation. 您还将看到您正在使用ECB模式,这在几乎任何情况下都是一个糟糕的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.