SHARE
TWEET

Untitled

a guest Apr 21st, 2019 101 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.  
  6. module.exports = class Sodium {
  7.     ready() {
  8.         return libsodium.ready;
  9.     }
  10.  
  11.     setKey(key){
  12.          if(key === null) {
  13.              throw "Sodium: Private key not set."
  14.          }
  15.          
  16.         this.key = libsodium.from_hex(key);
  17.     }
  18.    
  19.     encrypt(plaintext){
  20.         var nonce      = libsodium.randombytes_buf(nonce_length),
  21.             ciphertext = libsodium.crypto_aead_xchacha20poly1305_ietf_encrypt(plaintext, null, nonce, nonce, this.key);
  22.  
  23.         console.log("nonce", nonce);
  24.         console.log("ciphertext", ciphertext);
  25.  
  26.         return concat_typed_array(Uint8Array, nonce, ciphertext);
  27.     }
  28.    
  29.     decrypt(encryption){
  30.         var nonce      = encryption.slice(0, nonce_length),
  31.             ciphertext = encryption.slice(nonce_length);
  32.  
  33.         console.log("nonce", nonce);
  34.         console.log("ciphertext", ciphertext);
  35.    
  36.         return libsodium.crypto_aead_xchacha20poly1305_ietf_decrypt(nonce, ciphertext, null, nonce, this.key, "text");
  37.     }
  38. }
  39.  
  40.  
  41.  
  42. // other file:
  43.  
  44. const Sodium = require('./sodium');
  45.  
  46. const sodium = new Sodium();
  47.  
  48. sodium.ready().then(() => {
  49.     sodium.setKey(...);
  50.     sodium.encrypt(...);
  51.    
  52.     //...
  53. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top