Created
February 20, 2023 19:03
-
-
Save IvanAdmaers/2ecee98fcb3eb8188cc5216b6875fabc to your computer and use it in GitHub Desktop.
NodeJS Encrypt / Decrypt files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { readdir, readFile, writeFile } = require('fs/promises'); | |
const { | |
randomBytes, | |
createCipheriv, | |
createDecipheriv, | |
createHash, | |
} = require('crypto'); | |
const { join } = require('path'); | |
/** | |
* Encrypts or decrypts all files in a directory using the specified algorithm and key | |
* @param {string} dirPath - The path to the directory containing the files to encrypt or decrypt | |
* @param {boolean} encrypt - A boolean indicating whether to encrypt (true) or decrypt (false) the files | |
* @param {string} algorithm - The encryption algorithm to use | |
* @param {Buffer} key - The encryption key to use | |
*/ | |
async function encryptOrDecryptFiles(dirPath, encrypt, algorithm, key) { | |
try { | |
const files = await readdir(dirPath); | |
// Loop through all files and encrypt or decrypt them | |
for (const file of files) { | |
const filePath = join(dirPath, file); | |
// Read the file contents | |
const data = await readFile(filePath); | |
// Encrypt or decrypt the file contents | |
const iv = encrypt ? randomBytes(16) : data.slice(0, 16); | |
const dataToProcess = encrypt ? data : data.slice(16); | |
const cipher = encrypt | |
? createCipheriv(algorithm, key, iv) | |
: createDecipheriv(algorithm, key, iv); | |
const processedData = Buffer.concat([ | |
cipher.update(dataToProcess), | |
cipher.final(), | |
]); | |
// Write the processed contents back to the file | |
await writeFile( | |
filePath, | |
encrypt ? Buffer.concat([iv, processedData]) : processedData | |
); | |
console.log( | |
`File ${file} ${encrypt ? 'encrypted' : 'decrypted'} successfully` | |
); | |
} | |
} catch (err) { | |
console.error(`Error processing files: ${err}`); | |
} | |
} | |
const dirPath = join(__dirname, 'test_dir'); | |
const shouldEncrypt = true; | |
const algorithm = 'aes-256-cbc'; | |
const BASE_64_KEY = 'QDBLMXhGNl43MDU3'; | |
const key = createHash('sha256') | |
.update(String(BASE_64_KEY)) | |
.digest('base64') | |
.substring(0, 32); | |
encryptOrDecryptFiles(dirPath, shouldEncrypt, algorithm, key); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment