react-native-quick-crypto
Version:
A fast implementation of Node's `crypto` module written in C/C++ JSI
98 lines (97 loc) • 2.96 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Blake3 = void 0;
exports.blake3 = blake3;
exports.blake3Exports = void 0;
exports.createBlake3 = createBlake3;
var _reactNativeNitroModules = require("react-native-nitro-modules");
var _reactNativeBuffer = require("@craftzdog/react-native-buffer");
var _utils = require("./utils");
const BLAKE3_KEY_LEN = 32;
const BLAKE3_OUT_LEN = 32;
class Blake3 {
constructor(opts) {
this.native = _reactNativeNitroModules.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 = (0, _utils.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 (0, _utils.ab2str)(result, encoding);
}
return _reactNativeBuffer.Buffer.from(result);
}
digestLength(length) {
return _reactNativeBuffer.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 = _reactNativeNitroModules.NitroModules.createHybridObject('Blake3');
native.initHash();
return native.getVersion();
}
}
exports.Blake3 = Blake3;
function createBlake3(opts) {
return new Blake3(opts);
}
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;
const blake3Exports = exports.blake3Exports = {
Blake3,
createBlake3,
blake3
};
//# sourceMappingURL=blake3.js.map