SHOW:
|
|
- or go back to the newest paste.
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 () => { |
5 | + | |
6 | - | await libsodium.ready; |
6 | + | module.exports = class Sodium { |
7 | - | }).then(function(){ |
7 | + | ready() { |
8 | - | module.exports = class Sodium { |
8 | + | return libsodium.ready; |
9 | - | constructor(key){ |
9 | + | |
10 | - | if(key === null) { |
10 | + | |
11 | - | throw "Sodium: Private key not set." |
11 | + | setKey(key){ |
12 | - | } |
12 | + | if(key === null) { |
13 | - | |
13 | + | throw "Sodium: Private key not set." |
14 | - | this.key = libsodium.from_hex(key); |
14 | + | } |
15 | - | } |
15 | + | |
16 | - | |
16 | + | this.key = libsodium.from_hex(key); |
17 | - | encrypt(plaintext){ |
17 | + | |
18 | - | var nonce = libsodium.randombytes_buf(nonce_length), |
18 | + | |
19 | - | ciphertext = libsodium.crypto_aead_xchacha20poly1305_ietf_encrypt(plaintext, null, nonce, nonce, this.key); |
19 | + | encrypt(plaintext){ |
20 | var nonce = libsodium.randombytes_buf(nonce_length), | |
21 | - | console.log("nonce", nonce); |
21 | + | ciphertext = libsodium.crypto_aead_xchacha20poly1305_ietf_encrypt(plaintext, null, nonce, nonce, this.key); |
22 | - | console.log("ciphertext", ciphertext); |
22 | + | |
23 | console.log("nonce", nonce); | |
24 | - | return concat_typed_array(Uint8Array, nonce, ciphertext); |
24 | + | console.log("ciphertext", ciphertext); |
25 | - | } |
25 | + | |
26 | - | |
26 | + | return concat_typed_array(Uint8Array, nonce, ciphertext); |
27 | - | decrypt(encryption){ |
27 | + | |
28 | - | var nonce = encryption.slice(0, nonce_length), |
28 | + | |
29 | - | ciphertext = encryption.slice(nonce_length); |
29 | + | decrypt(encryption){ |
30 | var nonce = encryption.slice(0, nonce_length), | |
31 | - | console.log("nonce", nonce); |
31 | + | ciphertext = encryption.slice(nonce_length); |
32 | - | console.log("ciphertext", ciphertext); |
32 | + | |
33 | - | |
33 | + | console.log("nonce", nonce); |
34 | - | return libsodium.crypto_aead_xchacha20poly1305_ietf_decrypt(nonce, ciphertext, null, nonce, this.key, "text"); |
34 | + | console.log("ciphertext", ciphertext); |
35 | - | } |
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 | }); |