103 lines
2.5 KiB
JavaScript
103 lines
2.5 KiB
JavaScript
import crypto from 'crypto'
|
|
|
|
// Verschlüsselungskonfiguration
|
|
const ALGORITHM = 'aes-256-cbc'
|
|
const IV_LENGTH = 16
|
|
const SALT_LENGTH = 32
|
|
|
|
/**
|
|
* Generiert einen Schlüssel aus einem Passwort und Salt
|
|
*/
|
|
function deriveKey(password, salt) {
|
|
return crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha512')
|
|
}
|
|
|
|
/**
|
|
* Verschlüsselt einen Text
|
|
*/
|
|
export function encrypt(text, password) {
|
|
try {
|
|
// Salt generieren
|
|
const salt = crypto.randomBytes(SALT_LENGTH)
|
|
|
|
// Schlüssel ableiten
|
|
const key = deriveKey(password, salt)
|
|
|
|
// IV generieren
|
|
const iv = crypto.randomBytes(IV_LENGTH)
|
|
|
|
// Cipher erstellen
|
|
const cipher = crypto.createCipheriv(ALGORITHM, key, iv)
|
|
|
|
// Verschlüsseln
|
|
let encrypted = cipher.update(text, 'utf8', 'hex')
|
|
encrypted += cipher.final('hex')
|
|
|
|
// Salt + IV + Verschlüsselter Text kombinieren
|
|
const combined = Buffer.concat([
|
|
salt,
|
|
iv,
|
|
Buffer.from(encrypted, 'hex')
|
|
])
|
|
|
|
return combined.toString('base64')
|
|
} catch (error) {
|
|
console.error('Verschlüsselungsfehler:', error)
|
|
throw new Error('Fehler beim Verschlüsseln der Daten')
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Entschlüsselt einen Text
|
|
*/
|
|
export function decrypt(encryptedData, password) {
|
|
try {
|
|
// Base64 dekodieren
|
|
const combined = Buffer.from(encryptedData, 'base64')
|
|
|
|
// Komponenten extrahieren
|
|
const salt = combined.subarray(0, SALT_LENGTH)
|
|
const iv = combined.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH)
|
|
const encrypted = combined.subarray(SALT_LENGTH + IV_LENGTH)
|
|
|
|
// Schlüssel ableiten
|
|
const key = deriveKey(password, salt)
|
|
|
|
// Decipher erstellen
|
|
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)
|
|
|
|
// Entschlüsseln
|
|
let decrypted = decipher.update(encrypted, null, 'utf8')
|
|
decrypted += decipher.final('utf8')
|
|
|
|
return decrypted
|
|
} catch (error) {
|
|
console.error('Entschlüsselungsfehler:', error)
|
|
throw new Error('Fehler beim Entschlüsseln der Daten')
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Verschlüsselt ein Objekt (konvertiert zu JSON)
|
|
*/
|
|
export function encryptObject(obj, password) {
|
|
const jsonString = JSON.stringify(obj)
|
|
return encrypt(jsonString, password)
|
|
}
|
|
|
|
/**
|
|
* Entschlüsselt ein Objekt (konvertiert von JSON)
|
|
*/
|
|
export function decryptObject(encryptedData, password) {
|
|
const jsonString = decrypt(encryptedData, password)
|
|
return JSON.parse(jsonString)
|
|
}
|
|
|
|
/**
|
|
* Generiert einen sicheren Schlüssel für die Datenverschlüsselung
|
|
*/
|
|
export function generateEncryptionKey() {
|
|
return crypto.randomBytes(32).toString('hex')
|
|
}
|
|
|