hy2-panel/lib/crypto.ts
2026-04-14 18:05:32 +08:00

39 lines
1.1 KiB
TypeScript

import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
import { getEnv } from "@/lib/env";
function getKey() {
return createHash("sha256").update(getEnv().SESSION_SECRET).digest();
}
export function encryptText(value: string) {
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", getKey(), iv);
const encrypted = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return `${iv.toString("base64url")}.${tag.toString("base64url")}.${encrypted.toString("base64url")}`;
}
export function decryptText(payload: string | null | undefined) {
if (!payload) return null;
const [ivPart, tagPart, encryptedPart] = payload.split(".");
if (!ivPart || !tagPart || !encryptedPart) {
return null;
}
const decipher = createDecipheriv(
"aes-256-gcm",
getKey(),
Buffer.from(ivPart, "base64url"),
);
decipher.setAuthTag(Buffer.from(tagPart, "base64url"));
const decrypted = Buffer.concat([
decipher.update(Buffer.from(encryptedPart, "base64url")),
decipher.final(),
]);
return decrypted.toString("utf8");
}