Javascript 相当于从 Value 创建随机数值

标签 javascript java node.js groovy amadeus

我有这个 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(byte[]) groovy/java 代码选择特定的算法来生成随机字节。它使用毫秒作为生成这些字节(也称为种子)的基础。之后,byte[16] 生成一个数组来保存 16 个字节。 random.nextBytes 使用算法生成的随机字节填充该数组。然后对数组进行编码并返回它。

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

关于Javascript 相当于从 Value 创建随机数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57546570/

相关文章:

javascript - jquery 如何检查函数是否被触发

javascript - JavaScript 如何解释作用域中的变量?

javascript - 通过导航键选择适当的 div 元素

java - 没有主题备用 DNS 名称匹配

javascript - 无服务器( Node AWS) "TypeError","errorMessage":"callback is not a function"

javascript - 如何将JS中的数组转换成这种格式

java - 在端口 8761 上的 AppEngine 上部署应用程序

java - IntelliJ : How can I always show parameter hints?

javascript - 如何将上传功能外包为node.js服务

node.js - 如何导入 npm 包的特定变体