java - 如何使用 SecureRandom.getInstanceStrong() 生成 key ?

标签 java security random key

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

通过这段代码,我可以接收具有随机值的字节数组。有什么简单的方法可以生成给定长度(例如256 位)、类型(int、String)和格式(hex)的 key >, 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 派生类中。

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

这可能是生成强 AES key 的最佳方式:

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 运行时环境的无限强度管辖文件, key > 128 位。

关于java - 如何使用 SecureRandom.getInstanceStrong() 生成 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244064/

相关文章:

security - 为什么不建议在 MongoDB 中使用服务器端存储函数?

java - 如何在 Payara 中引用文件

java - 在 hibernate 中设置最大结果不按要求工作

java - 使用 Java 为 Google App Engine 自定义基于 JWT 的身份验证

java - 加载数据时达到饱和点;我如何控制 Java GC 生成?

security - 我可以通过对现有 MD5 哈希加盐并使用 Scrypt 或 PBKDF2 HMACSHA256 对结果进行哈希处理来提高 MD5 哈希密码的安全性吗?

react-native - 如何安全地保存 redux-persist-transform-encrypt key ?

javascript - 在 Javascript 骰子游戏中为骰子分配数字

c# - 随机排列元素,使得任何元素都不应出现在其原始索引处

c++ - 关于C++中的随机数