evm-blockchain-tools
Version:
This is a collection of resuseable tools to support development for EVM-powered blockchains
72 lines • 2.99 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decrypt = exports.encrypt = exports.genSalt = void 0;
const crypto = __importStar(require("crypto"));
const algorithm = "aes-256-gcm";
const ivLength = 12;
const saltLength = 16;
function generateRandomBytes(length) {
return crypto.randomBytes(length);
}
function getKeyFromPrivateString(privateString, realSalt) {
return crypto.scryptSync(privateString, realSalt, 32);
}
function genSalt(length = saltLength) {
return generateRandomBytes(length);
}
exports.genSalt = genSalt;
function encrypt(text, privateString) {
const iv = generateRandomBytes(ivLength);
const salt = genSalt();
const key = getKeyFromPrivateString(privateString, salt);
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, "utf8");
encrypted = Buffer.concat([encrypted, cipher.final()]);
const authTag = cipher.getAuthTag();
const combined = Buffer.concat([iv, authTag, encrypted, salt]);
return combined.toString("hex");
}
exports.encrypt = encrypt;
function decrypt(encryptedMessage, privateString) {
try {
const data = Buffer.from(encryptedMessage, "hex");
const iv = data.subarray(0, ivLength);
const authTag = data.subarray(ivLength, ivLength + 16);
const salt = data.subarray(data.length - saltLength);
const encryptedText = data.subarray(ivLength + 16, data.length - saltLength);
const key = getKeyFromPrivateString(privateString, salt);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encryptedText, undefined, "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
catch (error) {
throw new Error(`failed to decrypt: ${error.message}`);
}
}
exports.decrypt = decrypt;
//# sourceMappingURL=aes-encryption.js.map