• XSS.stack #1 – первый литературный журнал от юзеров форума

NodeJS file encryptor

GridsNetwork

ripper
КИДАЛА
Регистрация
30.03.2023
Сообщения
426
Реакции
128
Гарант сделки
2
Пожалуйста, обратите внимание, что пользователь заблокирован
JavaScript:
const fs = require('fs');
const crypto = require('crypto');
const zlib = require('zlib');

// Generate public and private keys
function generateKeys() {
  const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', {
    namedCurve: 'secp256k1'
  });
  return { publicKey, privateKey };
}

// Encrypt file
function encryptFile(filename, publicKey) {
  const plaintext = fs.readFileSync(filename);
  const iv = crypto.randomBytes(16);
  const key = crypto.createHash('sha256').update(publicKey).digest();
  const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
  return { iv, ciphertext };
}

// Decrypt file
function decryptFile(filename, privateKey, iv, ciphertext) {
  const key = crypto.createHash('sha256').update(privateKey).digest();
  const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
  const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
  fs.writeFileSync(filename, plaintext);
}

// Compress file with zlib
function compressFile(filename) {
  const plaintext = fs.readFileSync(filename);
  const compressed = zlib.gzipSync(plaintext, { level: zlib.constants.Z_BEST_COMPRESSION });
  const MAX_COMPRESSED_SIZE = 2048; // 2KB
  if (compressed. length > MAX_COMPRESSED_SIZE) {
    throw new Error('Compressed file is too large');
  }
  fs.writeFileSync(filename, compressed);
}

// Encrypt and compress file
function encryptAndCompressFile(filename) {
  const { publicKey, privateKey } = generateKeys();
  const { iv, ciphertext } = encryptFile(filename, publicKey);
  fs.writeFileSync(filename + '.enc', JSON.stringify({ publicKey, iv, ciphertext }));
  fs.writeFileSync(filename + '.keys', JSON.stringify({ publicKey, privateKey }));
  compressFile(filename + '.enc');
}

// Decompress and decrypt file
decompressAndDecryptFile(filename) {
  const compressed = fs.readFileSync(filename);
  const data = JSON.parse(zlib.gunzipSync(compressed).toString());
  const keys = JSON.parse(fs.readFileSync(filename.replace('.enc.gz', '.keys')));
  decryptFile(filename.replace('.enc.gz', ''), keys.privateKey, data.iv, data.ciphertext);
  fs.unlinkSync(filename);
  fs.unlinkSync(filename.replace('.enc.gz', '.keys'));
}

// Usage
encryptAndCompressFile('file.sample');
decompressAndDecryptFile('file.sample.enc.gz');
 


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх