1

我有这个 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');
};
4

1 回答 1

2

我已经找到了我的问题的答案。希望这将有助于将来的某人。

短:

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 字节的缓冲区。然后我们对该数组进行编码并返回它。

于 2019-08-18T18:16:54.770 回答