@bicycle-codes/simple-aes
Version:
An easy way to use symmetric keys in browsers or node
57 lines (56 loc) • 2.61 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var compat_exports = {};
__export(compat_exports, {
decryptMessage: () => decryptMessage,
encryptMessage: () => encryptMessage
});
module.exports = __toCommonJS(compat_exports);
var import_aes = require("@noble/ciphers/aes");
var import_webcrypto = require("@noble/ciphers/webcrypto");
var import_uint8arrays = require("uint8arrays");
var import_CONSTANTS = require("./CONSTANTS.js");
var import_util = require("./util.js");
var import_index = require("./index.js");
async function encryptMessage(msg, opts = { length: import_index.DEFAULT_SYMM_LEN }) {
const newKey = (0, import_webcrypto.randomBytes)(opts.length / 8);
const nonce = (0, import_webcrypto.randomBytes)(12);
const aes = (0, import_aes.gcm)(newKey, nonce);
const encryptedContent = await aes.encrypt((0, import_uint8arrays.fromString)(msg.content));
const encryptedString = (0, import_uint8arrays.toString)(
new Uint8Array([...nonce, ...encryptedContent]),
import_CONSTANTS.CONTENT_ENCODING
);
const keyAsString = (0, import_uint8arrays.toString)(newKey, import_CONSTANTS.KEY_ENCODING);
return [{ content: encryptedString }, { key: keyAsString }];
}
__name(encryptMessage, "encryptMessage");
async function decryptMessage(msg, keyString) {
const cipherText = (0, import_util.normalizeBase64ToBuf)(msg.content, "base64pad");
const nonce = cipherText.slice(0, 12);
const cipherBytes = cipherText.slice(12);
const aes = (0, import_aes.gcm)(
(0, import_uint8arrays.fromString)(keyString, import_CONSTANTS.KEY_ENCODING),
new Uint8Array(nonce)
);
const decrypted = aes.decrypt(new Uint8Array(cipherBytes));
return { content: (0, import_uint8arrays.toString)(decrypted) };
}
__name(decryptMessage, "decryptMessage");
;