Java AES-128 encryption of 1 block (16 bytes) returns 2 blocks (32 bytes) as output

I use the following code to encrypt AES-128 to encode a single block of 16 bytes, but the length of the encoded value gives 2 blocks of 32 bytes. Did I miss 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;  }} 
+4
source share
1 answer

Cipher.getInstance("AES") returns the cipher that uses the PKCS # 5 add-on. This add-on is added in all cases - when the plaintext is already a multiple of the block size, a whole block of add-ons is added.

Indicate your intent explicitly in a call to Cipher.getInstance() so as not to rely on the default values ​​and potentially cause confusion:

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

You will also see that you are using ECB mode, which is a poor choice in almost any situation.

+7
source

Source: https://habr.com/ru/post/1498924/


All Articles