Java AES cipher text size

后端 未结 2 1366
粉色の甜心
粉色の甜心 2021-02-06 17:11

I\'m using a very standard way of Java AES encryption / decryption.

byte[] key = hexStringToByteArray(\"C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF\");

byte[] message = he         


        
2条回答
  •  野的像风
    2021-02-06 18:02

    Your cipher instance is using PKCS5Padding padding, which adds up to 16 bytes of padding to the ciphertext. There are a couple of ways to correct this:

    Option 1: Instead of using Cipher.getInstance("AES"), which uses padding, use Cipher.getInstance("AES/CBC/NoPadding"). This is NOT recommended, however, as it requires that the plaintext be a multiple of 16 bytes.

    Option 2: Use BouncyCastle as your crypto provider, and then use

    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    Cipher.getInstance("AES/CTR/NoPadding", new BouncyCastleProvider());
    

    to initialize the cipher. This uses Counter mode (CTR) instead of Cipher Block Chaining mode (CBC), and Counter mode does not require any padding. With Counter mode it is important that you use a unique initialization vector, which can be transmitted in plaintext along with the ciphertext; for example,

    byte[] IV = new byte[16];
    new SecureRandom().getBytes(IV);
    cipher.init(Cipher.ENCRYPT_MODE, key, IV);
    

    Then when decrypting the ciphertext, initialize the cipher with the same initialization vector. It is up to you how you transmit the IV, but again, it does not need to be kept secret.

    The initialization vector for Cipher Block Chaining mode should also be unique, but this is not as critical as it is for Counter mode.

提交回复
热议问题