从AES源码分析AES对称加密如何生成key

key 的说明

key 长度为16、24、32个字节,128、192、256个bit, 使用SecureRandom生成随机字节
jdk 1.8.0_212
jre/lib/ext/sunjce_provider.jar!/com/sun/crypto/provider/AESConstants.class

package com.sun.crypto.provider;

interface AESConstants {
    int AES_BLOCK_SIZE = 16;
    int[] AES_KEYSIZES = new int[]{16, 24, 32};
}

AESCrypt.class

    static final boolean isKeySizeValid(int var0) {
        for(int var1 = 0; var1 < AES_KEYSIZES.length; ++var1) {
            if (var0 == AES_KEYSIZES[var1]) {
                return true;
            }
        }

        return false;
    }

AESKeyGenerator.class

    protected void engineInit(int var1, SecureRandom var2) {
        if (var1 % 8 == 0 && AESCrypt.isKeySizeValid(var1 / 8)) {
            this.keySize = var1 / 8;
            this.engineInit(var2);
        } else {
            throw new InvalidParameterException("Wrong keysize: must be equal to 128, 192 or 256");
        }
    }
    public final void init(int var1) {
        this.init(var1, JceSecurity.RANDOM);
    }
package javax.crypto;

...

final class JceSecurity {
    static final SecureRandom RANDOM = new SecureRandom();

如何生成key

public static SecretKey generateAESKey(int keysize) {
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES/ECB/PKCS5Padding");
        keyGenerator.init(256);
        SecretKey secretKey = keyGenerator.generateKey();
}

KeyGenerator 使用了 SecureRandom

SecureRandom is recommended by Java for generating a random number for cryptographic applications.

也可以 直接使用 SecureRandom 生成 key

    public static Key getSecureRandomKey(String algorithm, int keySize) {
        byte[] secureRandomKeyBytes = new byte[keySize / 8];
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(secureRandomKeyBytes);
        return new SecretKeySpec(secureRandomKeyBytes, algorithm);
    }

如何交给解密方使用

只需将 key 进行base64转换

key.getEncoded();

java-secure-aes-key

Java加解密security目录-策略文件 local_policy.jar

java.security.InvalidKeyException: Illegal key size错误

研发某个项目进行AES 256方式加密时报错

《实战开发》AES加密报错:Illegal key size or default parameters

你可能感兴趣的:(java,AES,对称加密,crypto,keygenerator)