xud
Version:
Exchange Union Daemon
61 lines • 2.95 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generatePreimageAndHash = exports.decrypt = exports.encrypt = exports.randomBytes = void 0;
const crypto_1 = require("crypto");
const util_1 = require("util");
const ENCRYPTION_IV_LENGTH = 16;
/** A promisified wrapper for the NodeJS `crypto.randomBytes` method. */
exports.randomBytes = util_1.promisify(crypto_1.randomBytes);
function getCipherKey(password) {
return crypto_1.createHash('sha256').update(password).digest();
}
/**
* Encrypts a Buffer or base64 string using a password
* @param payload a Buffer or base64 string
* @returns an encrypted Buffer
*/
function encrypt(payload, password) {
return __awaiter(this, void 0, void 0, function* () {
const buf = typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload;
const iv = yield exports.randomBytes(ENCRYPTION_IV_LENGTH);
const key = getCipherKey(password);
const cipher = crypto_1.createCipheriv('aes-256-cbc', key, iv);
return Buffer.concat([iv, cipher.update(buf), cipher.final()]);
});
}
exports.encrypt = encrypt;
/**
* Decrypts a Buffer or base64 string using a password
* @param payload a Buffer or base64 string
* @returns a decrypted Buffer
*/
function decrypt(payload, password) {
const buf = typeof payload === 'string' ? Buffer.from(payload, 'base64') : payload;
// the first 16 bytes contain the initialization vector
const iv = buf.slice(0, ENCRYPTION_IV_LENGTH);
const key = getCipherKey(password);
const encrypted = buf.slice(ENCRYPTION_IV_LENGTH);
const decipher = crypto_1.createDecipheriv('aes-256-cbc', key, iv);
return Buffer.concat([decipher.update(encrypted), decipher.final()]);
}
exports.decrypt = decrypt;
/** Returns a random payment preimage and hash in hex encoding. */
function generatePreimageAndHash() {
return __awaiter(this, void 0, void 0, function* () {
const bytes = yield exports.randomBytes(32);
const rPreimage = bytes.toString('hex');
const rHash = crypto_1.createHash('sha256').update(bytes).digest('hex');
return { rPreimage, rHash };
});
}
exports.generatePreimageAndHash = generatePreimageAndHash;
//# sourceMappingURL=cryptoUtils.js.map