* brand new source of entropy will be generated at the maximum size of 256 bits.
*/
export class Entropy {
- static MIN: 16 = 16
- static MAX: 32 = 32
- static MOD: 4 = 4
+ static #MIN: 16 = 16
+ static #MAX: 32 = 32
+ static #MOD: 4 = 4
#bytes: Uint8Array<ArrayBuffer>
get bits (): string { return bytes.toBin(this.#bytes) }
constructor (input?: unknown) {
if (input == null) {
- this.#bytes = crypto.getRandomValues(new Uint8Array(Entropy.MAX))
+ this.#bytes = crypto.getRandomValues(new Uint8Array(Entropy.#MAX))
} else if (typeof input === 'number') {
- if (input < Entropy.MIN || input > Entropy.MAX) {
- throw new RangeError(`Entropy must be ${Entropy.MIN}-${Entropy.MAX} bytes`)
+ if (input < Entropy.#MIN || input > Entropy.#MAX) {
+ throw new RangeError(`Entropy must be ${Entropy.#MIN}-${Entropy.#MAX} bytes`)
}
- if (input % Entropy.MOD !== 0) {
- throw new RangeError(`Entropy must be a multiple of ${Entropy.MOD} bytes`)
+ if (input % Entropy.#MOD !== 0) {
+ throw new RangeError(`Entropy must be a multiple of ${Entropy.#MOD} bytes`)
}
this.#bytes = crypto.getRandomValues(new Uint8Array(input))
} else if (input instanceof ArrayBuffer || input instanceof Uint8Array) {
- if (input.byteLength < Entropy.MIN || input.byteLength > Entropy.MAX) {
- throw new Error(`Entropy must be ${Entropy.MIN}-${Entropy.MAX} bytes`)
+ if (input.byteLength < Entropy.#MIN || input.byteLength > Entropy.#MAX) {
+ throw new Error(`Entropy must be ${Entropy.#MIN}-${Entropy.#MAX} bytes`)
}
- if (input.byteLength % Entropy.MOD !== 0) {
- throw new RangeError(`Entropy must be a multiple of ${Entropy.MOD} bytes`)
+ if (input.byteLength % Entropy.#MOD !== 0) {
+ throw new RangeError(`Entropy must be a multiple of ${Entropy.#MOD} bytes`)
}
this.#bytes = new Uint8Array(input)
} else if (typeof input === 'string') {
- if (input.length < Entropy.MIN * 2 || input.length > Entropy.MAX * 2) {
- throw new RangeError(`Entropy must be ${Entropy.MIN * 2}-${Entropy.MAX * 2} characters`)
+ if (input.length < Entropy.#MIN * 2 || input.length > Entropy.#MAX * 2) {
+ throw new RangeError(`Entropy must be ${Entropy.#MIN * 2}-${Entropy.#MAX * 2} characters`)
}
- if (input.length % Entropy.MOD * 2 !== 0) {
- throw new RangeError(`Entropy must be a multiple of ${Entropy.MOD * 2} characters`)
+ if (input.length % Entropy.#MOD * 2 !== 0) {
+ throw new RangeError(`Entropy must be a multiple of ${Entropy.#MOD * 2} characters`)
}
if (!/^[0-9a-fA-F]+$/i.test(input)) {
throw new RangeError('Entropy contains invalid hexadecimal characters')