2025-04-19 15:38:48 +08:00

79 lines
3.3 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decrypt = exports.encrypt = exports.verifyHmac = exports.generateKey = void 0;
const tslib_1 = require("tslib");
const crypto = tslib_1.__importStar(require("@walletconnect/crypto"));
const encoding = tslib_1.__importStar(require("@walletconnect/encoding"));
const utils_1 = require("@walletconnect/utils");
function generateKey(length) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const _length = (length || 256) / 8;
const bytes = crypto.randomBytes(_length);
const result = (0, utils_1.convertBufferToArrayBuffer)(encoding.arrayToBuffer(bytes));
return result;
});
}
exports.generateKey = generateKey;
function verifyHmac(payload, key) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const cipherText = encoding.hexToArray(payload.data);
const iv = encoding.hexToArray(payload.iv);
const hmac = encoding.hexToArray(payload.hmac);
const hmacHex = encoding.arrayToHex(hmac, false);
const unsigned = encoding.concatArrays(cipherText, iv);
const chmac = yield crypto.hmacSha256Sign(key, unsigned);
const chmacHex = encoding.arrayToHex(chmac, false);
if (encoding.removeHexPrefix(hmacHex) === encoding.removeHexPrefix(chmacHex)) {
return true;
}
return false;
});
}
exports.verifyHmac = verifyHmac;
function encrypt(data, key, providedIv) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const _key = encoding.bufferToArray((0, utils_1.convertArrayBufferToBuffer)(key));
const ivArrayBuffer = providedIv || (yield generateKey(128));
const iv = encoding.bufferToArray((0, utils_1.convertArrayBufferToBuffer)(ivArrayBuffer));
const ivHex = encoding.arrayToHex(iv, false);
const contentString = JSON.stringify(data);
const content = encoding.utf8ToArray(contentString);
const cipherText = yield crypto.aesCbcEncrypt(iv, _key, content);
const cipherTextHex = encoding.arrayToHex(cipherText, false);
const unsigned = encoding.concatArrays(cipherText, iv);
const hmac = yield crypto.hmacSha256Sign(_key, unsigned);
const hmacHex = encoding.arrayToHex(hmac, false);
return {
data: cipherTextHex,
hmac: hmacHex,
iv: ivHex,
};
});
}
exports.encrypt = encrypt;
function decrypt(payload, key) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const _key = encoding.bufferToArray((0, utils_1.convertArrayBufferToBuffer)(key));
if (!_key) {
throw new Error("Missing key: required for decryption");
}
const verified = yield verifyHmac(payload, _key);
if (!verified) {
return null;
}
const cipherText = encoding.hexToArray(payload.data);
const iv = encoding.hexToArray(payload.iv);
const buffer = yield crypto.aesCbcDecrypt(iv, _key, cipherText);
const utf8 = encoding.arrayToUtf8(buffer);
let data;
try {
data = JSON.parse(utf8);
}
catch (error) {
return null;
}
return data;
});
}
exports.decrypt = decrypt;
//# sourceMappingURL=index.js.map