RbNaCl::Box provides authenticated public-key encryption
Imagine Alice wants something valuable shipped to her. Because it's valuable, she wants to make sure it arrives securely (i.e. hasn't been opened or tampered with) and that it's not a forgery (i.e. it's actually from the sender she's expecting it to be from and nobody's pulling the old switcheroo)
One way she can do this is by providing the sender (let's call him Bob) with a high-security box of her choosing. She provides Bob with this box, and something else: a padlock, but a padlock without a key. Alice is keeping that key all to herself. Bob can put items in the box then put the padlock onto it, but once the padlock snaps shut, the box cannot be opened by anyone who doesn't have Alice's private key.
Here's the twist though, Bob also puts a padlock onto the box. This padlock uses a key Bob has published to the world, such that if you have one of Bob's keys, you know a box came from him because Bob's keys will open Bob's padlocks (let's imagine a world where padlocks cannot be forged even if you know the key). Bob then sends the box to Alice.
In order for Alice to open the box, she needs two keys: her private key that opens her own padlock, and Bob's well-known key. If Bob's key doesn't open the second padlock then Alice knows that this is not the box she was expecting from Bob, it's a forgery.
This bidirectional guarantee around identity is known as mutual authentication.
# generate a private key private_key = RbNaCl::PrivateKey.generate # send the public key to someone (or everyone) public_key = private_key.public_key # initialize the box box = RbNaCl::Box.new(someones_public_key, private_key) # the other person does this with your key other_box = RbNaCl::Box.new(public_key, someones_private_key) # on sending or receiving the first message, the shared key is derived. # encrypt a message using the box. # First, make a nonce. One simple strategy is to use 24 random bytes. # The nonce isn't secret, and can be sent with the ciphertext. # crypto_box provides the #nonce_bytes method for its nonce length. nonce = RbNaCl::Random.random_bytes(box.nonce_bytes) message = "..." ciphertext = box.encrypt(nonce, message) #=> "..." # string of random looking bytes, 16 bytes longer than message. # The extra 16-bytes are the authenticator # decrypt a message # NB: Same nonce used here. decrypted_message = other_box.decrypt(nonce, ciphertext) #=> "..." # But if the ciphertext has been tampered with: other_box.open(nonce, corrupted_ciphertext) #=> RbNaCl::CryptoError exception is raised. # Chosen ciphertext attacks are prevented by authentication and constant-time comparisons