feat/mfa: Added multifactor authentication.
This commit is contained in:
25
server/src/services/mfaCrypto.ts
Normal file
25
server/src/services/mfaCrypto.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import crypto from 'crypto';
|
||||
import { JWT_SECRET } from '../config';
|
||||
|
||||
function getKey(): Buffer {
|
||||
return crypto.createHash('sha256').update(`${JWT_SECRET}:mfa:v1`).digest();
|
||||
}
|
||||
|
||||
/** Encrypt TOTP secret for storage in SQLite. */
|
||||
export function encryptMfaSecret(plain: string): string {
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', getKey(), iv);
|
||||
const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return Buffer.concat([iv, tag, enc]).toString('base64');
|
||||
}
|
||||
|
||||
export function decryptMfaSecret(blob: string): string {
|
||||
const buf = Buffer.from(blob, 'base64');
|
||||
const iv = buf.subarray(0, 12);
|
||||
const tag = buf.subarray(12, 28);
|
||||
const enc = buf.subarray(28);
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', getKey(), iv);
|
||||
decipher.setAuthTag(tag);
|
||||
return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8');
|
||||
}
|
||||
Reference in New Issue
Block a user