Skip to content

Instantly share code, notes, and snippets.

@starbeast
Created November 24, 2019 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starbeast/9cfbc9f499bff84a57db815a2dfa81d2 to your computer and use it in GitHub Desktop.
Save starbeast/9cfbc9f499bff84a57db815a2dfa81d2 to your computer and use it in GitHub Desktop.
NaCl secret box (RbNaCl BE + TweetNaCl.js FE)
Ruby - https://github.com/RubyCrypto/rbnacl
JavaScript - https://github.com/dchest/tweetnacl-js
## FE encrypt -> BE decrypt
# FE
const { publicKey, secretKey } = nacl.box.keyPair();
// every time you encrypt change the nonce
const nonce = nacl.randomBytes(nacl.secretbox.nonceLength);
const encodedNonce = nacl.util.encodeBase64(nonce);
const encodedPublic = nacl.util.encodeBase64(publicKey);
const message = 'my random message';
const theirPublicKey = nacl.util.decodeBase64(theirEncodedPublicKey) // theirEncodedPublicKey is encoded_public_key from BE
const encryptedMessage = nacl.box(nacl.util.decodeUTF8(message), nonce, theirPublicKey, secretKey);
const encodedMessage = nacl.util.encodeBase64(encryptedMessage);
// send encodedMessage to BE
# BE
private_key = RbNaCl::PrivateKey.generate
public_key = private_key.public_key
encoded_public_key = Base64.strict_encode64(public_key.to_bytes)
decoded_nonce = Base64.strict_decode64(encoded_nonce) # encoded_nonce is encodedNonce from FE
decoded_their_public_key = Base64.strict_decode64(encoded_their_public_key) # encoded_their_public_key is encodedPublic from FE
decoded_message = Base64.strict_decode64(encodedMessage)
box = RbNaCl::Box.new(decoded_their_public_key, private_key)
decrypted_message = box.decrypt(decoded_nonce, decoded_message)
## BE encrypt -> FE decrypt
# BE
# every time you encrypt change the nonce
nonce = RbNaCl::Random.random_bytes(box.nonce_bytes)
message = 'this is the message'
encrypted_message = box.encrypt(nonce, message)
encoded_message = Base64.strict_encode64(encrypted_message)
encoded_nonce = Base64.strict_encode64(nonce)
# FE
encryptedMessage = nacl.util.decodeBase64(encodedMessage); # encodedMessage is encoded_message from BE
nonce = nacl.util.decodeBase64(encodedNonce); # encodedNonce is encoded_nonce from BE
encodedMessage = nacl.box.open(encryptedMessage, nonce, theirPublicKey, secretKey);
decodedMessage = nacl.util.encodeUTF8(encodedMessage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment