forked from holepunchto/sodium-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.js
22 lines (16 loc) · 834 Bytes
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const sodium = require('.')
const nonce = Buffer.alloc(sodium.crypto_secretbox_NONCEBYTES)
const key = sodium.sodium_malloc(sodium.crypto_secretbox_KEYBYTES)
const message = Buffer.from('Hello, World!')
const cipher = Buffer.alloc(message.length + sodium.crypto_secretbox_MACBYTES)
sodium.randombytes_buf(nonce) // insert random data into nonce
sodium.randombytes_buf(key) // insert random data into key
// encrypted message is stored in cipher.
sodium.crypto_secretbox_easy(cipher, message, nonce, key)
console.log('Encrypted message:', cipher)
const plainText = Buffer.alloc(cipher.length - sodium.crypto_secretbox_MACBYTES)
if (!sodium.crypto_secretbox_open_easy(plainText, cipher, nonce, key)) {
console.log('Decryption failed!')
} else {
console.log('Decrypted message:', plainText, '(' + plainText.toString() + ')')
}