Javascript 等同于从 Value 创建随机数值



我有这个Java代码/Groovy代码:

import org.apache.ws.security.util.Base64;
import java.security.SecureRandom;
def generate_nonce() {  
def random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(System.currentTimeMillis());
def nonceValue = new byte[16];
random.nextBytes(nonceValue);
return Base64.encode(nonceValue);
}

我正在尝试在Javascript-NodeJs中创建等效项。实用程序/SHA1PRNG是此模块 https://github.com/bombworm/SHA1PRNG。有人可以帮忙吗?

const crypto = require('crypto');
const secureRandom = require('./utilities/SHA1PRNG');
function generate_nonce () {
let nonce = secureRandom(Date.now().toString());
let nonceValue = crypto.randomBytes(16);
// incomplete part, below does not work
// return nonceValue.update(secureRandom).toString('base64');
};

我找到了问题的答案。希望这将在未来对某人有所帮助。

短片:

const secureRandom = require('./utilities/SHA1PRNG');
function generate_nonce () {
const nonceValue = secureRandom(Date.now());
// I've added a type check in the SHA1PRNG module, it's local rather than installed through npm, this was to remove the toString.
return nonceValue.toString('base64');
};

长: https://docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html#nextBytes(字节[]( Groovy/Java 代码正在选择一种特定的算法来生成随机字节。 它使用毫秒作为生成这些字节(又名种子(的基础。紧接着,字节[16]生成一个数组来保存16个字节。random.nextBytes 正在用算法生成的随机字节填充该数组。然后,它对数组进行编码并返回它。

我们在javascript中做等效的事情。它根据我们提供的种子返回一个 16 字节缓冲区,即毫秒数。然后我们对该数组进行编码并返回它。

最新更新