Last active
November 16, 2017 02:49
-
-
Save samuelmaddock/488c2389dcc75f5eddadeaff2a1b652f to your computer and use it in GitHub Desktop.
Dat crypto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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