UNPKG

@stellot/crypto

Version:

Crypto libraries for front and backend

36 lines (35 loc) 1.2 kB
import rand from 'randombytes'; import { BigInteger as BigInt } from 'jsbn'; import BN from 'bn.js'; export const BIG_TWO = new BigInt('2'); function trimBigInt(bi, bits) { const trimLength = bi.bitLength() - bits; return trimLength > 0 ? bi.shiftRight(trimLength) : bi; } export function getRandomNbitBigInt(bits) { const buf = rand(Math.ceil(bits / 8)); const bi = new BigInt(buf.toString('hex'), 16); return trimBigInt(bi, bits).setBit(bits - 1); } export function getRandomBigInt(min, max) { const range = max.subtract(min).subtract(BigInt.ONE); let bi; do { const buf = rand(Math.ceil(range.bitLength() / 8)); bi = new BigInt(buf.toString('hex'), 16).add(min); } while (bi.compareTo(max) >= 0); return bi; } export function getBigPrime(bits) { let bi = (getRandomNbitBigInt(bits)).or(BigInt.ONE); while (!bi.isProbablePrime()) { bi = bi.add(BIG_TWO); } return trimBigInt(bi, bits).setBit(bits - 1); } export function parseBigInt(obj) { return obj instanceof Object ? obj : new BigInt(`${obj}`); } export function toBuffer(bigInt) { return new BN(Buffer.from(bigInt.toByteArray())).toArrayLike(Buffer); }