@alephium/web3-wallet
Version:
Simple wallets for Alephium
70 lines (66 loc) • 2.93 kB
JavaScript
;
/*
Copyright 2018 - 2022 The Alephium Authors
This file is part of the alephium project.
The library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the library. If not, see <http://www.gnu.org/licenses/>.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.decrypt = exports.encrypt = void 0;
const web3_1 = require("@alephium/web3");
const crypto_1 = require("crypto");
const saltByteLength = 64;
const ivByteLength = 64;
const authTagLength = 16;
const encrypt = (password, dataRaw) => {
const data = new TextEncoder().encode(dataRaw);
const salt = (0, crypto_1.randomBytes)(saltByteLength);
const derivedKey = keyFromPassword(password, salt);
const iv = (0, crypto_1.randomBytes)(ivByteLength);
const cipher = createCipher(derivedKey, iv);
const encrypted = (0, web3_1.concatBytes)([cipher.update(data), cipher.final()]);
const authTag = cipher.getAuthTag();
const payload = {
salt: salt.toString('hex'),
iv: iv.toString('hex'),
encrypted: (0, web3_1.binToHex)((0, web3_1.concatBytes)([encrypted, authTag])),
version: 1
};
return JSON.stringify(payload);
};
exports.encrypt = encrypt;
const decrypt = (password, payloadRaw) => {
const payload = JSON.parse(payloadRaw);
const version = payload.version;
if (version !== 1) {
throw new Error(`Invalid version: got ${version}, expected: 1`);
}
const salt = (0, web3_1.hexToBinUnsafe)(payload.salt);
const iv = (0, web3_1.hexToBinUnsafe)(payload.iv);
const encrypted = (0, web3_1.hexToBinUnsafe)(payload.encrypted);
const derivedKey = keyFromPassword(password, salt);
const decipher = createDecipher(derivedKey, iv);
const data = encrypted.slice(0, encrypted.length - authTagLength);
const authTag = encrypted.slice(encrypted.length - authTagLength, encrypted.length);
decipher.setAuthTag(authTag);
const decrypted = (0, web3_1.concatBytes)([decipher.update(data), decipher.final()]);
return new TextDecoder().decode(decrypted);
};
exports.decrypt = decrypt;
const createCipher = (key, iv) => {
return (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
};
const createDecipher = (key, iv) => {
return (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
};
const keyFromPassword = (password, salt) => {
return (0, crypto_1.pbkdf2Sync)(password, salt, 10000, 32, 'sha256');
};