Skip to content

Instantly share code, notes, and snippets.

@samuelmaddock
Last active November 16, 2017 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelmaddock/488c2389dcc75f5eddadeaff2a1b652f to your computer and use it in GitHub Desktop.
Save samuelmaddock/488c2389dcc75f5eddadeaff2a1b652f to your computer and use it in GitHub Desktop.
Dat crypto
const sodium = require('sodium-universal')
function keyPair(seed) {
var publicKey = new Buffer(sodium.crypto_sign_PUBLICKEYBYTES)
var secretKey = new Buffer(sodium.crypto_sign_SECRETKEYBYTES)
sodium.crypto_sign_keypair(publicKey, secretKey)
return {
publicKey: publicKey,
secretKey: secretKey
}
}
function seal(msg, publicKey) {
var cipher = new Buffer(msg.length + sodium.crypto_box_SEALBYTES)
sodium.crypto_box_seal(cipher, msg, publicKey)
return cipher
}
function unseal(cipher, publicKey, secretKey) {
if (cipher.length < sodium.crypto_box_SEALBYTES) return null
var msg = new Buffer(cipher.length - sodium.crypto_box_SEALBYTES)
if (!sodium.crypto_box_seal_open(msg, cipher, publicKey, secretKey)) return null
return msg
}
function verifyKeyPair(publicKey, secretKey) {
const msg = Buffer.from('test', 'utf-8')
const cipher = seal(msg, publicKey)
const decrypted = unseal(cipher, publicKey, secretKey)
// 'decrypted' is always null
console.log('verify:', msg.toString('utf-8'), decrypted ? decrypted.toString('utf-8') : decrypted)
}
const keypair = keyPair()
console.info(keypair)
verifyKeyPair(keypair.publicKey, keypair.secretKey)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment