· 8 years ago · Nov 18, 2017, 05:26 AM
1const sodium = require('sodium-universal')
2
3function keyPair(seed) {
4 var publicKey = new Buffer(sodium.crypto_sign_PUBLICKEYBYTES)
5 var secretKey = new Buffer(sodium.crypto_sign_SECRETKEYBYTES)
6
7 sodium.crypto_sign_keypair(publicKey, secretKey)
8
9 return {
10 publicKey: publicKey,
11 secretKey: secretKey
12 }
13}
14
15function seal(msg, publicKey) {
16 var cipher = new Buffer(msg.length + sodium.crypto_box_SEALBYTES)
17 sodium.crypto_box_seal(cipher, msg, publicKey)
18 return cipher
19}
20
21function unseal(cipher, publicKey, secretKey) {
22 if (cipher.length < sodium.crypto_box_SEALBYTES) return null
23 var msg = new Buffer(cipher.length - sodium.crypto_box_SEALBYTES)
24 if (!sodium.crypto_box_seal_open(msg, cipher, publicKey, secretKey)) return null
25 return msg
26}
27
28function verifyKeyPair(publicKey, secretKey) {
29 const msg = Buffer.from('test', 'utf-8')
30 const cipher = seal(msg, publicKey)
31 const decrypted = unseal(cipher, publicKey, secretKey)
32 // 'decrypted' is always null
33 console.log('verify:', msg.toString('utf-8'), decrypted ? decrypted.toString('utf-8') : decrypted)
34}
35
36const keypair = keyPair()
37console.info(keypair)
38verifyKeyPair(keypair.publicKey, keypair.secretKey)