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

时间:2016-05-15 21:54:34

标签: java security random key

如何使用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

1 个答案:

答案 0 :(得分:2)

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

现代对称密码的密钥由位组成。通常你不需要它们的人/字符串表示(这实际上可能会损害安全性)。将它们存储在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位。