Secret Key Encryption
Clone this wiki locally
RbNaCl::SecretBox provides authenticated secret-key encryption.
Think of SecretBox like a safe: you can put information inside of it, and anyone with the combination can open it. Also, like any high security safe, any attempts to tamper with the safe or its contents will be detected.
Important Usage Notes
- What the algorithm does for you: ensures data is kept confidential and that it cannot be undetectably modified by an attacker
- What the algorithm expects from you: a secret key which must be kept confidential, and a unique ("nonce") value each time the SecretBox function is used. The SecretBox function must never ever be called with the same key:nonce pair!
- What happens if you reuse a nonce: ALL IS LOST! complete loss of the confidentiality of your data (provided nonces are reused with the same key). Do NOT let this happen or you are breaking the security of your system.
- What nonces should I use then?: Use SimpleBox if you're at all confused about what nonces to use.
# generate a random secret key (or perhaps use scrypt or PBKDF2) key = RbNaCl::Random.random_bytes(RbNaCl::SecretBox.key_bytes) # initialize the box secret_box = RbNaCl::SecretBox.new(key) # 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. # The SecretBox instance has a nonce_bytes method for determining how many bytes should be in a nonce nonce = RbNaCl::Random.random_bytes(secret_box.nonce_bytes) message = "..." ciphertext = secret_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 = secret_box.decrypt(nonce, ciphertext) #=> "..." # But if the ciphertext has been tampered with: secret_box.open(nonce, corrupted_ciphertext) #=> RbNaCl::CryptoError exception is raised. # Chosen ciphertext attacks are prevented by authentication and constant-time comparisons