Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const libsodium          = require('libsodium-wrappers');
  2. const concat_typed_array = require("concat-typed-array");
  3. const nonce_length       = libsodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES;
  4.  
  5. (async () => {
  6.     await libsodium.ready;
  7. }).then(function(){
  8.     module.exports = class Sodium {
  9.         constructor(key){
  10.              if(key === null) {
  11.                  throw "Sodium: Private key not set."
  12.              }
  13.              
  14.             this.key = libsodium.from_hex(key);
  15.         }
  16.        
  17.         encrypt(plaintext){
  18.             var nonce      = libsodium.randombytes_buf(nonce_length),
  19.                 ciphertext = libsodium.crypto_aead_xchacha20poly1305_ietf_encrypt(plaintext, null, nonce, nonce, this.key);
  20.  
  21.             console.log("nonce", nonce);
  22.             console.log("ciphertext", ciphertext);
  23.  
  24.             return concat_typed_array(Uint8Array, nonce, ciphertext);
  25.         }
  26.        
  27.         decrypt(encryption){
  28.             var nonce      = encryption.slice(0, nonce_length),
  29.                 ciphertext = encryption.slice(nonce_length);
  30.  
  31.             console.log("nonce", nonce);
  32.             console.log("ciphertext", ciphertext);
  33.        
  34.             return libsodium.crypto_aead_xchacha20poly1305_ietf_decrypt(nonce, ciphertext, null, nonce, this.key, "text");
  35.         }
  36.     }
  37. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement