22 lines
819 B
TypeScript
22 lines
819 B
TypeScript
import { createCipheriv } from "node:crypto";
|
|
|
|
export function prepareAuthPassword(password: string, input: {
|
|
passwordEncrypted?: boolean;
|
|
passwordEncryptionKey?: string;
|
|
}): string {
|
|
if (input.passwordEncrypted) return password;
|
|
const key = input.passwordEncryptionKey?.trim();
|
|
if (!key) return password;
|
|
return encryptPasswordCFB(password, key);
|
|
}
|
|
|
|
export function encryptPasswordCFB(password: string, key: string): string {
|
|
const keyBytes = Buffer.from(key);
|
|
if (![16, 24, 32].includes(keyBytes.length)) {
|
|
throw new Error("password encryption key must be 16, 24, or 32 bytes");
|
|
}
|
|
const algorithm = `aes-${keyBytes.length * 8}-cfb`;
|
|
const cipher = createCipheriv(algorithm, keyBytes, keyBytes);
|
|
return Buffer.concat([cipher.update(password, "utf8"), cipher.final()]).toString("base64");
|
|
}
|