Skip to content

Instantly share code, notes, and snippets.

@anned20
Last active September 10, 2024 08:00
Show Gist options
  • Save anned20/fcb3a97e8281b608bfcb4d046a640fe7 to your computer and use it in GitHub Desktop.
Save anned20/fcb3a97e8281b608bfcb4d046a640fe7 to your computer and use it in GitHub Desktop.

Revisions

  1. anned20 revised this gist Nov 4, 2018. 3 changed files with 34 additions and 4 deletions.
    34 changes: 34 additions & 0 deletions encryption.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    const crypto = require('crypto');
    const algorithm = 'aes-256-ctr';
    let key = 'MySuperSecretKey';
    key = crypto.createHash('sha256').update(String(key)).digest('base64').substr(0, 32);

    const encrypt = (buffer) => {
    // Create an initialization vector
    const iv = crypto.randomBytes(16);
    // Create a new cipher using the algorithm, key, and iv
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    // Create the new (encrypted) buffer
    const result = Buffer.concat([iv, cipher.update(buffer), cipher.final()]);
    return result;
    };

    const decrypt = (encrypted) => {
    // Get the iv: the first 16 bytes
    const iv = encrypted.slice(0, 16);
    // Get the rest
    encrypted = encrypted.slice(16);
    // Create a decipher
    const decipher = crypto.createDecipheriv(algorithm, key, iv);
    // Actually decrypt it
    const result = Buffer.concat([decipher.update(encrypted), decipher.final()]);
    return result;
    };

    const plain = Buffer.from('Hello world');

    const encrypted = encrypt(plain);
    console.log('Encrypted:', encrypted.toString());

    const decrypted = decrypt(encrypted);
    console.log('Decrypted:', decrypted.toString());
    1 change: 0 additions & 1 deletion step-1.js
    Original file line number Diff line number Diff line change
    @@ -1 +0,0 @@
    const crypto = require('crypto');
    3 changes: 0 additions & 3 deletions step-2.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +0,0 @@
    const crypto = require('crypto');
    const algorithm = 'aes-256-ctr';
    const key = 'MySuperSecretKey';
  2. anned20 revised this gist Nov 4, 2018. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions step-2.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    const crypto = require('crypto');
    const algorithm = 'aes-256-ctr';
    const key = 'MySuperSecretKey';
  3. anned20 created this gist Nov 4, 2018.
    1 change: 1 addition & 0 deletions step-1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    const crypto = require('crypto');