Java –如何生成随机的12个字节?

在Java中,我们可以使用SecureRandom.nextBytes(byte[] bytes)生成用户指定数量的随机字节。 此SecureRandom是加密安全的随机数生成器(RNG)。

1.随机的12个字节(96位)

1.1生成一个随机的12字节(96位)随机数。

HelloCryptoApp.java
package com.mkyong.crypto;

import java.security.SecureRandom;

public class HelloCryptoApp {

    public static void main(String[] args) {

        byte[] nonce = new byte[12];
        new SecureRandom().nextBytes(nonce);

        System.out.println(convertBytesToHex(nonce));

    }

    // util to print bytes in hex
    private static String convertBytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte temp : bytes) {
            result.append(String.format("%02x", temp));
        }
        return result.toString();
    }

}

输出量

Terminal
0747a9ad467d4dc29ce70344

1.2随机产生20个字节(160位)

byte[] nonce = new byte[20];
  new SecureRandom().nextBytes(nonce);

  System.out.println(convertBytesToHex(nonce));

输出量

Terminal
e2ac8893b23ef174461e4ec37598080ec910b87b

2.随机32字节(256位)+ DRBG算法

2.1使用NIST SP 800-90Ar1中定义的DRBG算法生成一个随机的32字节(256位)。 默认情况下, SecureRandom使用SHA1PRNG算法生成一个随机数。

HelloCryptoApp2.java
package com.mkyong.java11;

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

public class HelloCryptoApp2 {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        byte[] nonce = new byte[32];
        SecureRandom rand = SecureRandom.getInstance("DRBG");
        rand.nextBytes(nonce);

        System.out.println(convertBytesToHex(nonce));

    }

    private static String convertBytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte temp : bytes) {
            result.append(String.format("%02x", temp));
        }
        return result.toString();
    }

}

输出量

Terminal
7d5bca7a4cfab6abec28da5cc899c32a0c36f17128f242a3df20301b3812b881

进一步阅读
有关所有受支持的随机算法,请参阅此SecureRandom编号生成算法

参考文献

翻译自: https://mkyong.com/java/java-how-to-generate-a-random-12-bytes/

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值