Files
note2any/server/dist/crypto.js
2026-04-21 17:55:41 +08:00

54 lines
2.2 KiB
JavaScript

"use strict";
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 = void 0;
const crypto = __importStar(require("crypto"));
const config_1 = require("./config");
const ALGORITHM = "aes-256-cbc";
const IV_LENGTH = 16;
function getKey() {
if (config_1.config.encryptKey.length !== 32) {
throw new Error("ENCRYPT_KEY must be a 32-character string");
}
return Buffer.from(config_1.config.encryptKey, "utf8");
}
function encrypt(text) {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(ALGORITHM, getKey(), iv);
const encrypted = Buffer.concat([cipher.update(text, "utf8"), cipher.final()]);
return iv.toString("hex") + encrypted.toString("hex");
}
exports.encrypt = encrypt;
function decrypt(encrypted) {
const ivHex = encrypted.slice(0, IV_LENGTH * 2);
const contentHex = encrypted.slice(IV_LENGTH * 2);
const iv = Buffer.from(ivHex, "hex");
const content = Buffer.from(contentHex, "hex");
const decipher = crypto.createDecipheriv(ALGORITHM, getKey(), iv);
const decrypted = Buffer.concat([decipher.update(content), decipher.final()]);
return decrypted.toString("utf8");
}
exports.decrypt = decrypt;