46 lines
1.4 KiB
JavaScript
46 lines
1.4 KiB
JavaScript
import crypto from 'crypto';
|
||
|
||
const algorithm = 'aes-256-ecb';
|
||
|
||
const secret = process.env.SECRET_KEY;
|
||
if (!secret) {
|
||
console.warn('[encryption] SECRET_KEY fehlt – verwende unsicheren Fallback (nur für Entwicklung).');
|
||
}
|
||
const key = crypto.scryptSync(secret || 'DEV_FALLBACK_SECRET', 'salt', 32);
|
||
|
||
export const generateIv = () => {
|
||
return crypto.randomBytes(16).toString('base64');
|
||
};
|
||
|
||
export const encrypt = (text) => {
|
||
const cipher = crypto.createCipheriv(algorithm, key, null);
|
||
let encrypted = cipher.update(text, 'utf8', 'base64');
|
||
encrypted += cipher.final('base64');
|
||
return encrypted;
|
||
};
|
||
|
||
export const decrypt = (text) => {
|
||
if (!text) {
|
||
return null;
|
||
}
|
||
|
||
const input = String(text);
|
||
try {
|
||
const decipher = crypto.createDecipheriv(algorithm, key, null);
|
||
let decrypted = decipher.update(input, 'base64', 'utf8');
|
||
decrypted += decipher.final('utf8');
|
||
return decrypted;
|
||
} catch (base64Error) {
|
||
try {
|
||
// Rueckwaertskompatibel fuer bereits gespeicherte Hex-Werte.
|
||
const decipher = crypto.createDecipheriv(algorithm, key, null);
|
||
let decrypted = decipher.update(input, 'hex', 'utf8');
|
||
decrypted += decipher.final('utf8');
|
||
return decrypted;
|
||
} catch (hexError) {
|
||
console.log(hexError);
|
||
return null;
|
||
}
|
||
}
|
||
};
|