node-json-db
Version:
Database using JSON file as storage for Node.JS
65 lines • 2.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CipheredFileAdapter = void 0;
const FileAdapter_1 = require("./FileAdapter");
const crypto_1 = require("crypto");
const ALGO = 'aes-256-gcm';
class CipheredFileAdapter extends FileAdapter_1.FileAdapter {
key;
constructor(key, filename, fsync) {
super(filename, fsync);
this.key = key;
}
decrypt(data) {
const decipher = (0, crypto_1.createDecipheriv)(ALGO, this.key, Buffer.from(data.iv, 'hex'));
decipher.setAuthTag(Buffer.from(data.tag, 'hex'));
const decrypted = Buffer.concat([
decipher.update(Buffer.from(data.data, 'hex')),
decipher.final()
]);
return decrypted.toString('utf8');
}
async readAsync() {
try {
const rawData = await super.readAsync();
if (rawData) {
const cipheredData = JSON.parse(rawData);
if (!cipheredData ||
typeof cipheredData.iv !== 'string' ||
typeof cipheredData.tag !== 'string' ||
typeof cipheredData.data !== 'string') {
throw new Error('Invalid encrypted data format.');
}
return this.decrypt(cipheredData);
}
return null;
}
catch (e) {
throw e;
}
}
encrypt(data) {
const iv = (0, crypto_1.randomBytes)(12); // 96 bits recommandé pour GCM
const cipher = (0, crypto_1.createCipheriv)(ALGO, this.key, iv);
const encrypted = Buffer.concat([
cipher.update(data, 'utf8'),
cipher.final()
]);
const tag = cipher.getAuthTag();
return {
iv: iv.toString('hex'),
tag: tag.toString('hex'),
data: encrypted.toString('hex')
};
}
async writeAsync(data) {
try {
await super.writeAsync(JSON.stringify(this.encrypt(data)));
}
catch (err) {
throw err;
}
}
}
exports.CipheredFileAdapter = CipheredFileAdapter;
//# sourceMappingURL=CipheredFileAdapter.js.map