sodium-javascript/example.js

23 lines
678 B
JavaScript
Raw Normal View History

2020-06-24 12:49:26 +00:00
const sodium = require('./')
2017-01-24 10:41:06 +00:00
2020-06-24 12:49:26 +00:00
const key = Buffer.alloc(sodium.crypto_secretbox_KEYBYTES)
const nonce = Buffer.alloc(sodium.crypto_secretbox_NONCEBYTES)
2017-01-24 10:41:06 +00:00
sodium.randombytes_buf(key)
sodium.randombytes_buf(nonce)
2020-06-24 12:49:26 +00:00
const message = Buffer.from('Hello, World!')
const cipher = Buffer.alloc(message.length + sodium.crypto_secretbox_MACBYTES)
2017-01-24 10:41:06 +00:00
sodium.crypto_secretbox_easy(cipher, message, nonce, key)
console.log('Encrypted:', cipher)
2020-06-24 12:49:26 +00:00
const plainText = Buffer.alloc(cipher.length - sodium.crypto_secretbox_MACBYTES)
2017-01-24 10:41:06 +00:00
sodium.crypto_secretbox_open_easy(plainText, cipher, nonce, key)
console.log('Plaintext:', plainText.toString())
if (typeof window !== 'undefined') window.close()