Advertisement
Guest User

Untitled

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