Created
April 23, 2022 11:10
-
-
Save roshnet/75770ae98fa5234d50ea5623205dea6d to your computer and use it in GitHub Desktop.
uCrypt encryption module reference
This file contains hidden or 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 crypto = require('crypto') | |
const fs = require('fs') | |
const ALGO = 'aes-256-ctr' | |
// const message = Buffer.from('Enemies incoming!', 'binary') | |
const message = fs.readFileSync('docs.pdf', { encoding: 'binary' }) | |
const password = 'secret' | |
const key = crypto | |
.createHash('sha256') | |
.update(password) | |
.digest('base64') | |
.substring(0, 32) | |
// [encryption] | |
function encrypt() { | |
const iv = crypto.randomBytes(16).toString('hex').slice(0, 16) | |
const cipher = crypto.createCipheriv(ALGO, key, iv) | |
const result = | |
iv + cipher.update(message, 'binary', 'hex') + cipher.final('hex') | |
fs.writeFileSync('tmp/docs.pdf.uncrypt', result, { encoding: 'binary' }) | |
} | |
// [decryption] | |
function decrypt() { | |
let stored = fs.readFileSync('tmp/docs.pdf.uncrypt', { encoding: 'binary' }) | |
const iv = stored.slice(0, 16) | |
stored = stored.slice(16) | |
const decipher = crypto.createDecipheriv(ALGO, key, iv) | |
const result = | |
decipher.update(stored, 'hex', 'binary') + decipher.final('binary') | |
fs.writeFileSync('tmp/docs-unlocked.pdf', result, { encoding: 'binary' }) | |
} | |
try { | |
process.argv[2] === 'e' | |
? encrypt() | |
: process.argv[2] === 'd' | |
? decrypt() | |
: console.log('No args. Exiting.') | |
} catch (e) { | |
console.log('FAILED') | |
console.error(e) | |
} | |
// Since decryption does not fail, compare MD5 sum with original and unlocked | |
// file to see if decryption was OK. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment