0

我曾经以这种方式访问​​ jsbn.js 中的 SecureRandom


var jsbn = require('jsbn');
var SecureRandom = jsbn.SecureRandom;
var secureRandom = new SecureRandom();
secureRandom.nextBytes(x);

如何在 jsbn.ts 中访问它?由于似乎要导入的功能有限

 import jsbn, {BigInteger, RandomGenerator as SecureRandom} from "jsbn";

包.json

"dependencies": {
  "jsbn": "^1.1.0"
},
"devDependencies": {
  "@types/jsbn": "^1.2.29",
}

谢谢你。

4

1 回答 1

1

@types/jsbn npm 包仅提供RandomGenerator接口的声明,不导出 SecureRandom:

export interface RandomGenerator {
    nextBytes(bytes: number[]): void;
}

您应该使用 prng 作为WebAPI Crypto getRandomValues()来实现该接口和此nextBytes方法

例如:

class SecureRandomGenerator implements RandomGenerator {

    private static getRandomBytes(size: number): Uint8Array {
        // User agent WebAPI Crypto
        if (typeof window !== "undefined" && window.crypto && window.crypto.getRandomValues) {
            return window.crypto.getRandomValues(new Uint8Array(size));
        }

        throw new Error("Web API Crypto is not available");
    }

    public nextBytes(bytes: number[]): void {
        const generatedBytes = SecureRandomGenerator.getRandomBytes(bytes.length);
        for (let i = 0; i < bytes.length; i++) {
            bytes[i] = generatedBytes[i];
        }
    }

}
于 2021-07-07T10:32:19.517 回答