如何使用 SecureRandom.getInstanceStrong() 生成密钥?

How to generate secret key using SecureRandom.getInstanceStrong()?

如何使用 SecureRandom.getInstanceStrong() 生成密钥?

使用这段代码,我可以接收具有随机值的字节数组。有什么简单的方法可以生成给定长度的密钥(例如,256 位)、类型(int、String)和格式(hex,bin,dec)?

package com.company;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class KeyGen {

    public void generate() throws NoSuchAlgorithmException {

        SecureRandom random = SecureRandom.getInstanceStrong();
        byte[] values = new byte[32]; // 256 bit
        random.nextBytes(values);

        StringBuilder sb = new StringBuilder();
        for (byte b : values) {
            sb.append(String.format("%02x", b));
        }
        System.out.print("Key: ");
        System.out.println(sb.toString());
    }
}

输出:

Key: 8fcea84897f48f575c22441ece4e7ddb43ac08cd2c1a83fca46c080768468059

键应该是特定类型的,例如AES。它们最好保存在 SecretKey 实例或类似的 Key 派生的 class.

现代对称密码的密钥由位组成。通常你不需要它们的 human/String 表示(这实际上可能会损害安全性)。将它们存储在 KeyStore 中或从密码中派生。如果您对它们进行编码,则表示格式无关紧要,只要您在转换过程中不丢失数据即可。

这可能是生成强 AES 密钥的最佳方法:

public class GenerateStrongAESKey {

    public static SecretKey generateStrongAESKey(final int keysize) {
        final KeyGenerator kgen;
        try {
            kgen = KeyGenerator.getInstance("AES");
        } catch (final NoSuchAlgorithmException e) {
            throw new RuntimeException("AES key generator should always be available in a Java runtime", e);
        }
        final SecureRandom rng;
        try {
            rng = SecureRandom.getInstanceStrong();
        } catch (final NoSuchAlgorithmException e) {
            throw new RuntimeException("No strong secure random available to generate strong AES key", e);
        }
        // already throws IllegalParameterException for wrong key sizes
        kgen.init(keysize, rng);

        return kgen.generateKey();
    }

    public static void main(String[] args) {
        SecretKey strongAESKey = generateStrongAESKey(256);
        // well, if you must have a human readable string, here it is
        // but you've been warned
        System.out.println(toHex(strongAESKey.getEncoded()));
    }

    private static String toHex(final byte[] data) {
        final StringBuilder sb = new StringBuilder(data.length * 2);
        for (byte b : data) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
}

注意:这需要 Oracle 运行时环境的无限强度管辖文件,用于密钥 > 128 位。