react-native-quick-crypto
Version:
A fast implementation of Node's `crypto` module written in C/C++ JSI
90 lines (89 loc) • 2.65 kB
JavaScript
;
import { NitroModules } from 'react-native-nitro-modules';
import { Buffer } from '@craftzdog/react-native-buffer';
import { binaryLikeToArrayBuffer, ab2str } from './utils';
const BLAKE3_KEY_LEN = 32;
const BLAKE3_OUT_LEN = 32;
export class Blake3 {
constructor(opts) {
this.native = NitroModules.createHybridObject('Blake3');
if (opts?.key && opts?.context) {
throw new Error('BLAKE3: cannot use both key and context options together');
}
if (opts?.key) {
if (opts.key.length !== BLAKE3_KEY_LEN) {
throw new Error(`BLAKE3: key must be exactly ${BLAKE3_KEY_LEN} bytes`);
}
this.mode = 'keyed';
this.keyData = opts.key;
this.native.initKeyed(opts.key.buffer);
} else if (opts?.context !== undefined) {
if (typeof opts.context !== 'string' || opts.context.length === 0) {
throw new Error('BLAKE3: context must be a non-empty string');
}
this.mode = 'deriveKey';
this.contextData = opts.context;
this.native.initDeriveKey(opts.context);
} else {
this.mode = 'hash';
this.native.initHash();
}
}
update(data, inputEncoding) {
const buffer = binaryLikeToArrayBuffer(data, inputEncoding ?? 'utf8');
this.native.update(buffer);
return this;
}
digest(encodingOrLength) {
let length;
let encoding;
if (typeof encodingOrLength === 'number') {
length = encodingOrLength;
} else if (encodingOrLength) {
encoding = encodingOrLength;
}
const result = this.native.digest(length);
if (encoding && encoding !== 'buffer') {
return ab2str(result, encoding);
}
return Buffer.from(result);
}
digestLength(length) {
return Buffer.from(this.native.digest(length));
}
reset() {
this.native.reset();
return this;
}
copy() {
const copied = new Blake3();
// Replace the native with a copy
copied.native = this.native.copy();
copied.mode = this.mode;
copied.keyData = this.keyData;
copied.contextData = this.contextData;
return copied;
}
static getVersion() {
const native = NitroModules.createHybridObject('Blake3');
native.initHash();
return native.getVersion();
}
}
export function createBlake3(opts) {
return new Blake3(opts);
}
export function blake3(data, opts) {
const hasher = new Blake3(opts);
hasher.update(data);
const length = opts?.dkLen ?? BLAKE3_OUT_LEN;
const result = hasher.digestLength(length);
return new Uint8Array(result);
}
blake3.create = createBlake3;
export const blake3Exports = {
Blake3,
createBlake3,
blake3
};
//# sourceMappingURL=blake3.js.map