backup + decriptare toate fisiere done
This commit is contained in:
@@ -6,7 +6,7 @@ async function readKeyFromFile(filePath) {
|
||||
try {
|
||||
await fs.promises.access(filePath, fs.constants.F_OK);
|
||||
return fs.promises.readFile(filePath); // Use asynchronous readFile
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
console.error('Error reading key file:', error);
|
||||
return null;
|
||||
}
|
||||
@@ -70,7 +70,46 @@ async function decryptFileInPlace(filePath) {
|
||||
});
|
||||
}
|
||||
|
||||
function cryptForKey(content, key, decrypt = false) {
|
||||
const algorithm = 'aes-256-ctr';
|
||||
const secretKey = crypto.createHash('sha256').update(String(key)).digest('base64').substr(0, 32);
|
||||
let cipher;
|
||||
|
||||
if (decrypt) {
|
||||
cipher = crypto.createDecipheriv(algorithm, secretKey, Buffer.alloc(16, 0)); // Using a zeroed IV for CTR
|
||||
} else {
|
||||
cipher = crypto.createCipheriv(algorithm, secretKey, Buffer.alloc(16, 0));
|
||||
}
|
||||
|
||||
return Buffer.concat([cipher.update(content), cipher.final()]);
|
||||
}
|
||||
|
||||
// Encrypts a file in place with a given key
|
||||
async function encryptFileWithKey(filePath, key) {
|
||||
try {
|
||||
const fileContent = await fs.promises.readFile(filePath);
|
||||
const encryptedContent = cryptForKey(fileContent, key, false);
|
||||
await fs.promises.writeFile(filePath, encryptedContent);
|
||||
console.log(`File encrypted successfully: ${filePath}`);
|
||||
} catch (error) {
|
||||
console.error(`Error encrypting file: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function decryptFileWithKey(filePath, key) {
|
||||
try {
|
||||
const fileContent = await fs.promises.readFile(filePath);
|
||||
const decryptedContent = cryptForKey(fileContent, key, true);
|
||||
await fs.promises.writeFile(filePath, decryptedContent);
|
||||
console.log(`File decrypted successfully: ${filePath}`);
|
||||
} catch (error) {
|
||||
console.error(`Error decrypting file: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
encryptFileInPlace,
|
||||
decryptFileInPlace
|
||||
decryptFileInPlace,
|
||||
encryptFileWithKey,
|
||||
decryptFileWithKey,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user