@oslojs/crypto
Advanced tools
Comparing version 0.2.1 to 0.3.0
export declare function random(): number; | ||
export declare function generateRandomInteger(max: number): number; | ||
export declare function generateRandomInteger(max: bigint): bigint; | ||
export declare function generateRandomIntegerNumber(max: number): number; | ||
export declare function generateRandomString(length: number, alphabet: string): string; | ||
export type AlphabetPattern = "a-z" | "A-Z" | "0-9" | "-" | "_"; | ||
export declare function alphabet(...patterns: AlphabetPattern[]): string; |
@@ -1,2 +0,2 @@ | ||
import { bigEndian } from "@oslojs/binary"; | ||
import { bigIntFromBytes } from "@oslojs/binary"; | ||
export function random() { | ||
@@ -13,8 +13,8 @@ const buffer = new ArrayBuffer(8); | ||
export function generateRandomInteger(max) { | ||
if (max < 0 || max > 2 ** 32 - 1) { | ||
throw new Error("Argument 'max' must be an unsigned 32 bit integer"); | ||
if (max < 2) { | ||
throw new Error("Argument 'max' must be a positive integer"); | ||
} | ||
const bitLength = (max - 1).toString(2).length; | ||
const shift = bitLength % 8; | ||
const bytes = new Uint8Array(Math.ceil(bitLength / 8)); | ||
const inclusiveMaxBitLength = (max - 1n).toString(2).length; | ||
const shift = inclusiveMaxBitLength % 8; | ||
const bytes = new Uint8Array(Math.ceil(inclusiveMaxBitLength / 8)); | ||
crypto.getRandomValues(bytes); | ||
@@ -26,3 +26,3 @@ // This zeroes bits that can be ignored to increase the chance `result` < `max`. | ||
} | ||
let result = bigEndian.uint32(bytes); | ||
let result = bigIntFromBytes(bytes); | ||
while (result >= max) { | ||
@@ -33,10 +33,16 @@ crypto.getRandomValues(bytes); | ||
} | ||
result = bigEndian.uint32(bytes); | ||
result = bigIntFromBytes(bytes); | ||
} | ||
return result; | ||
} | ||
export function generateRandomIntegerNumber(max) { | ||
if (max < 2 || max > Number.MAX_SAFE_INTEGER) { | ||
throw new Error("Argument 'max' must be a positive integer"); | ||
} | ||
return Number(generateRandomInteger(BigInt(max))); | ||
} | ||
export function generateRandomString(length, alphabet) { | ||
let result = ""; | ||
for (let i = 0; i < length; i++) { | ||
result += alphabet[generateRandomInteger(alphabet.length)]; | ||
result += alphabet[generateRandomIntegerNumber(alphabet.length)]; | ||
} | ||
@@ -43,0 +49,0 @@ return result; |
{ | ||
"name": "@oslojs/crypto", | ||
"type": "module", | ||
"version": "0.2.1", | ||
"version": "0.3.0", | ||
"description": "A very basic crypto library", | ||
@@ -6,0 +6,0 @@ "files": [ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
54974
1429