在java中生成128位随机密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23607293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:17:12  来源:igfitidea点击:

Generating 128 bit random key in java

javarandom

提问by Phalguni Mukherjee

I want to generate a 128 bit random key in java. I am using the following:

我想在java中生成一个128位的随机密钥。我正在使用以下内容:

byte[] byteBucket = new byte[bytelength];
randomizer.nextBytes(byteBucket);

Will my byte array length be 16 as (16*8=128) or 128?

我的字节数组长度是 16 为 (16*8=128) 还是 128?

回答by Bilbo Baggins

UUID

用户名

There is a class called java.util.UUID, with a methodto generate a random-basedUUID. This 128-bitvalue has 122 of its bits generated randomly.

有一种称为类java.util.UUID,用方法来生成一个基于随机UUID。这个128 位值有 122 位随机生成。

UUID uuid = UUID.randomUUID() ;

Call toStringto view the value as a hex string in canonical format with hyphens inserted.

调用toString以将值查看为规范格式的十六进制字符串,并插入连字符。

uuid.toString(): 24b47cf5-fb53-4fb1-a5a2-8b415260304d

uuid.toString(): 24b47cf5-fb53-4fb1-a5a2-8b415260304d

You can extract the 128 bits as a pair of 64-bit longinteger numbers. Call getMostSignificantBits()and getLeastSignificantBits().

您可以将 128 位提取为一对 64 位long整数。呼叫getMostSignificantBits()getLeastSignificantBits()

long mostSignificant = uuid.getMostSignificantBits() ;
long leastSignificant = uuid.getLeastSignificantBits() ;

This value may not be appropriate for critical security applications with 4 bits being predictable (not random). But in other practical applications, this handy class may work well.

此值可能不适用于具有 4 位可预测(非随机)的关键安全应用程序。但是在其他实际应用中,这个方便的类可能会很好用。

Here is a question which I found on SO with more detailed explanation: Likelihood of collision using most significant bits of a UUID in Java

这是我在 SO 上发现的一个问题,有更详细的解释:在 Java 中使用 UUID 的最重要位的碰撞可能性

回答by Pramod S. Nikam

try SecureRandom API.

尝试 SecureRandom API。

SecureRandom random = new SecureRandom();
byte bytes[] = new byte[16]; // 128 bits are converted to 16 bytes;
random.nextBytes(bytes);