@stellot/crypto
Version:
Crypto libraries for front and backend
47 lines (46 loc) • 1.88 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBuffer = exports.parseBigInt = exports.getBigPrime = exports.getRandomBigInt = exports.getRandomNbitBigInt = exports.BIG_TWO = void 0;
const randombytes_1 = __importDefault(require("randombytes"));
const jsbn_1 = require("jsbn");
const bn_js_1 = __importDefault(require("bn.js"));
exports.BIG_TWO = new jsbn_1.BigInteger('2');
function trimBigInt(bi, bits) {
const trimLength = bi.bitLength() - bits;
return trimLength > 0 ? bi.shiftRight(trimLength) : bi;
}
function getRandomNbitBigInt(bits) {
const buf = randombytes_1.default(Math.ceil(bits / 8));
const bi = new jsbn_1.BigInteger(buf.toString('hex'), 16);
return trimBigInt(bi, bits).setBit(bits - 1);
}
exports.getRandomNbitBigInt = getRandomNbitBigInt;
function getRandomBigInt(min, max) {
const range = max.subtract(min).subtract(jsbn_1.BigInteger.ONE);
let bi;
do {
const buf = randombytes_1.default(Math.ceil(range.bitLength() / 8));
bi = new jsbn_1.BigInteger(buf.toString('hex'), 16).add(min);
} while (bi.compareTo(max) >= 0);
return bi;
}
exports.getRandomBigInt = getRandomBigInt;
function getBigPrime(bits) {
let bi = (getRandomNbitBigInt(bits)).or(jsbn_1.BigInteger.ONE);
while (!bi.isProbablePrime()) {
bi = bi.add(exports.BIG_TWO);
}
return trimBigInt(bi, bits).setBit(bits - 1);
}
exports.getBigPrime = getBigPrime;
function parseBigInt(obj) {
return obj instanceof Object ? obj : new jsbn_1.BigInteger(`${obj}`);
}
exports.parseBigInt = parseBigInt;
function toBuffer(bigInt) {
return new bn_js_1.default(Buffer.from(bigInt.toByteArray())).toArrayLike(Buffer);
}
exports.toBuffer = toBuffer;