chaingate
Version:
A complete TypeScript library for connecting to and making transactions on different blockchains
42 lines • 1.9 kB
JavaScript
import { IncorrectPassword } from './errors';
import { blake2b } from '@noble/hashes/blake2b';
import { bytesToHex, hexToBytes } from '../../../InternalUtils/Utils';
import { ctr } from '@noble/ciphers/aes';
import { pbkdf2 } from '../../../InternalUtils/Crypto';
export class LegacyKeystore {
keystoreData;
_derivedKey;
constructor(keystoreData) {
this.keystoreData = keystoreData;
}
async checkPassword(password) {
const derivedKey = this._derivedKey ?? (await this.deriveKey(password));
const ciphertext = hexToBytes(this.keystoreData.crypto.ciphertext);
const mac = bytesToHex(blake2b(Buffer.concat([derivedKey.passwordCheck, ciphertext]), { dkLen: 32 }), false);
if (mac === this.keystoreData.crypto.mac)
this._derivedKey = derivedKey;
return mac === this.keystoreData.crypto.mac;
}
async deriveKey(password) {
const salt = hexToBytes(this.keystoreData.crypto.kdfparams.salt);
const iterations = this.keystoreData.crypto.kdfparams.c;
const dkLen = this.keystoreData.crypto.kdfparams.dklen;
const derivedKeyRaw = await pbkdf2({ password, salt, dkLen, iterations });
return {
decryptKey: derivedKeyRaw.slice(0, 16),
passwordCheck: derivedKeyRaw.slice(16, 32),
};
}
async decrypt(password) {
const derivedKey = this._derivedKey ?? (await this.deriveKey(password));
if (!(await this.checkPassword(password)))
throw new IncorrectPassword();
const nonce = hexToBytes(this.keystoreData.crypto.cipherparams.iv);
const encryptedData = hexToBytes(this.keystoreData.crypto.ciphertext);
return ctr(derivedKey.decryptKey, nonce).decrypt(encryptedData);
}
static isKeystore(obj) {
return 'version' in obj && obj.version == 1;
}
}
//# sourceMappingURL=LegacyKeystore.js.map