简体   繁体   中英

How to use SecureRandom instead of using hardcoded bytes array for Java AES Encrytion and Decryption?

In my code I am using hardcoded arrays(given below) for IV and key

**private static byte[] IVAes = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

private static byte[] keyAes = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

public static String encryptAes(String strPlain) {
        byte[] encrypted = null;
        if (StringUtils.isBlank(strPlain)) {
            return strPlain;
        }
        byte[] toEncrypt = strPlain.getBytes();
        try {
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(IVAes);
            // Generate the key specs.
            SecretKeySpec skeySpec = new SecretKeySpec(keyAes, AES_ALGORITHM);
            // Instantiate the cipher
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, paramSpec);
            encrypted = cipher.doFinal(toEncrypt);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return new String(Base64.encodeBase64(encrypted));
    }**

but using hardcoded array as IV and Key is not prefered due to security perspective. Instead of this type of Hardcoded array can I use SecureRandom() as given below-

**public static String encryptAes(String strPlain) {
        byte[] encrypted = null;
        if (StringUtils.isBlank(strPlain)) {
            return strPlain;
        }
        byte[] toEncrypt = strPlain.getBytes();
        try {
//---------calling generateIV method

            AlgorithmParameterSpec paramSpec = generateIv();
                // Instantiate the cipher
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, paramSpec);
            encrypted = cipher.doFinal(toEncrypt);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return new String(Base64.encodeBase64(encrypted));
    }

public static IvParameterSpec generateIv() {
    byte[] IVAes = new byte[16];
    new SecureRandom().nextBytes(IVAes);
    return new IvParameterSpec(IVAes);
}

int n = 128;
public static SecretKey generateKey(int n) throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(n);
    SecretKey key = keyGenerator.generateKey();
    return key;
}**

I just wanted to know that creating array of 16 bytes for IV and key by using SecureRandom and also key generator will give same result as it was giving when I use hardcoded array as shown above??

The whole idea of a cipher is that it is indistinguishable from random (not considering the length of the ciphertext, that obviously depends on the size of the message in some way). If you have a unique key and IV then the ciphertext should be indistinguishable from random, although for CBC the IV should also be randomized. If you want to test if it "works" then you'll have to decrypt the ciphertext. Otherwise you can only check if the ciphertext size is about right.

However, if you are asking about the security of your code then sure, the use of SecureRandom and KeyGenerator seems fine. You might want to prefix the IV to the ciphertext, that's the common way to communicate a random IV. If you want to know how to distribute keys then I'd suggest reading into symmetric key management; that depends on the use case.


For my fellow crypto nerds, yes, sure related key attacks are a thing so having a unique key & IV is not entirely the whole story, but these keys are randomized, so that's fine. There are probably some other theoretical / practical issues with the answer which can usually be ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM