Cryptography

suggest change

Ruby ships two standard libraries for cryptography:

Both come with Ruby, so you don't need a gem. The examples below were run with Ruby 4.0 and OpenSSL 3.6. Most of them also work on Ruby 3.x.

require 'openssl'
puts OpenSSL::OPENSSL_LIBRARY_VERSION
puts OpenSSL::VERSION   # version of the openssl gem
OpenSSL 3.6.4 25 Aug 2026
4.0.2

Pick the primitive by what you need:

Goal Use
Fingerprint data, deduplicate, check downloads SHA-256 (Digest, OpenSSL::Digest)
Prove a message came from someone who knows a shared key HMAC-SHA256 (OpenSSL::HMAC)
Store user passwords bcrypt / Argon2, see Password hashing
Keep data secret and detect tampering AES-256-GCM (OpenSSL::Cipher)
Turn a password or master secret into keys PBKDF2 / scrypt / HKDF (OpenSSL::KDF)
Let anyone verify who signed something Ed25519 or RSA-PSS signatures (OpenSSL::PKey)
Agree on a shared key over an open channel X25519 key exchange
Tokens, keys, salts, IVs SecureRandom / OpenSSL::Random

Hashing

A cryptographic hash maps any input to a fixed-size digest. The same input always gives the same digest, and you can't feasibly find a different input with the same digest.

require 'digest'

data = "The quick brown fox jumps over the lazy dog"

puts Digest::SHA256.hexdigest(data)
puts Digest::SHA256.base64digest(data)
p    Digest::SHA256.digest(data).bytesize
puts Digest::SHA512.hexdigest(data)[0, 32] + "..."
puts Digest::MD5.hexdigest(data)    # legacy: checksums only, never security
d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
16j7swfXgJRpypq8sAguT41WUeRtPNt2LQLQvzfJ5ZI=
32
07e547d9586f6a73f73fbac0435ed769...
9e107d9d372bb6826bd81d3542a419d6

digest returns raw binary bytes. hexdigest and base64digest return text versions you can print or store (see Base64 and hex encoding). MD5 and SHA-1 are broken: attackers can create collisions. Don't use them for signatures, certificates or anything else where an attacker chooses the input.

OpenSSL::Digest covers every algorithm your OpenSSL build supports, including SHA-3 and BLAKE2. You select the algorithm by name:

require 'openssl'

data = "The quick brown fox jumps over the lazy dog"

puts OpenSSL::Digest.hexdigest("SHA256", data)
puts OpenSSL::Digest.hexdigest("SHA3-256", data)
puts OpenSSL::Digest.hexdigest("BLAKE2b512", data)[0, 32] + "..."

d = OpenSSL::Digest.new("SHA256")
p d.name, d.digest_length, d.block_length
d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
69070dda01975c8c120c3aada1b282394e7f032fa9cf32f4cb2259a0897dfc04
a8add4bdddfd93e4877d2746e62817b1...
"SHA256"
32
64

Hashing large files and streams

Don't read a multi-gigabyte file into one string. Digest::SHA256.file reads the file in chunks. A digest object also accepts data one piece at a time with << (an alias of update):

require 'digest'

File.binwrite("big.bin", "x" * 10_000_000)

# reads the file in chunks, memory use stays flat
puts Digest::SHA256.file("big.bin").hexdigest

# incremental hashing of data that arrives in pieces
sha = Digest::SHA256.new
File.open("big.bin", "rb") do |f|
  while (chunk = f.read(64 * 1024))
    sha << chunk
  end
end
puts sha.hexdigest

File.delete("big.bin")
0c9a42b3d065a64063eca67e98c932fa2e9a077bc7973a421a964a11304c998c
0c9a42b3d065a64063eca67e98c932fa2e9a077bc7973a421a964a11304c998c

A plain hash proves nothing about who produced the data. Anyone who can change the file can also recompute its hash. For that you need an HMAC or a signature.

HMAC: authenticating messages with a shared key

An HMAC is a hash computed with a secret key. Only someone who knows the key can produce a valid HMAC, so the receiver knows the message wasn't forged or modified. Webhooks are a common use: the sender (GitHub, Stripe, Slack and so on) signs the request body with a secret you both know, and you check the signature before trusting the payload:

require 'openssl'

secret  = "webhook-secret-from-dashboard"
payload = '{"event":"push","ref":"refs/heads/main"}'

mac = OpenSSL::HMAC.hexdigest("SHA256", secret, payload)
puts mac

# what the sender puts in a header, e.g. X-Hub-Signature-256
header = "sha256=#{mac}"

def valid_signature?(secret, body, header)
  expected = "sha256=" + OpenSSL::HMAC.hexdigest("SHA256", secret, body)
  OpenSSL.secure_compare(expected, header.to_s)
end

p valid_signature?(secret, payload, header)
p valid_signature?(secret, payload.sub("main", "evil"), header)
p valid_signature?(secret, payload, nil)
9db5ae3813aa6a70751b6d2ef88d73b52abc523c8c88394427d727705ec3e4c0
true
false
false

Two details matter:

Application security shows how to sign tokens with an HMAC.

Random keys, IVs and salts

Every key, IV, nonce and salt must come from a cryptographically secure generator. Never use rand or Random.

require 'securerandom'
require 'openssl'

key  = SecureRandom.bytes(32)            # 256-bit binary key
salt = OpenSSL::Random.random_bytes(16)  # same OS generator, different API
p key.bytesize, salt.bytesize
p key.encoding
puts SecureRandom.hex(32)                # printable form of a 256-bit key
32
16
#<Encoding:BINARY (ASCII-8BIT)>
d41bbd645c01e0d28a24946073059a3939a0c05794fb80b44ebdd283bbc0702e

Keys are binary strings. To keep a key in an environment variable, store it as hex or Base64 and decode it when you load it: [ENV.fetch("APP_KEY")].pack("H*").

Symmetric encryption with AES-256-GCM

With symmetric encryption the same key encrypts and decrypts. Use an AEAD mode such as AES-GCM. It encrypts the data and also produces an authentication tag. If anyone changes even one bit of the ciphertext, decryption fails instead of returning garbage.

Each encryption needs a fresh random 12-byte IV (nonce). The IV isn't secret, so the usual approach is to store it next to the ciphertext, together with the 16-byte tag:

require 'openssl'
require 'base64'

KEY = OpenSSL::Random.random_bytes(32)
IV_LEN, TAG_LEN = 12, 16

def encrypt(plaintext, key: KEY, aad: "")
  cipher = OpenSSL::Cipher.new("aes-256-gcm").encrypt
  cipher.key = key
  iv = cipher.random_iv
  cipher.auth_data = aad
  ciphertext = cipher.update(plaintext) + cipher.final
  Base64.strict_encode64(iv + cipher.auth_tag + ciphertext)
end

def decrypt(token, key: KEY, aad: "")
  raw = Base64.strict_decode64(token)
  raise ArgumentError, "token too short" if raw.bytesize < IV_LEN + TAG_LEN
  iv, tag, ciphertext = raw[0, IV_LEN], raw[IV_LEN, TAG_LEN], raw[(IV_LEN + TAG_LEN)..]
  cipher = OpenSSL::Cipher.new("aes-256-gcm").decrypt
  cipher.key = key
  cipher.iv = iv
  cipher.auth_tag = tag
  cipher.auth_data = aad
  cipher.update(ciphertext) + cipher.final
end

token = encrypt("card ending 4242")
puts token
puts decrypt(token)
puts encrypt("card ending 4242")       # same input, different output
XzeHdAdT+vw8SRJ2dS1OXgBxmJRuB0LwW8P9mETSE0OYIQLEXMs1tqA3Ni0=
card ending 4242
dLbOGVVI9wCm74BZKURYCxcZNm6+0TVleU5exnfYQKSapAARstKM5aBgBN8=

Some things to get right:

Tampering and wrong keys raise errors

token = encrypt("amount=100")

# flip one bit of the ciphertext
raw = Base64.strict_decode64(token)
raw.setbyte(-1, raw.getbyte(-1) ^ 1)
tampered = Base64.strict_encode64(raw)

begin
  decrypt(tampered)
rescue OpenSSL::Cipher::CipherError => e
  puts "rejected: #{e.class}"
end

begin
  decrypt(token, key: OpenSSL::Random.random_bytes(32))
rescue OpenSSL::Cipher::CipherError => e
  puts "wrong key: #{e.class}"
end
rejected: OpenSSL::Cipher::AuthTagError
wrong key: OpenSSL::Cipher::AuthTagError

AuthTagError is a subclass of CipherError added in recent versions of the openssl gem. Older versions raise CipherError itself, so rescue CipherError to work everywhere.

Additional authenticated data

auth_data (AAD) is data that isn't encrypted but is covered by the tag. Use it to tie a ciphertext to its context. Then an attacker who can write to your database can't copy an encrypted value from one row into another:

# bind the ciphertext to the record it belongs to
token = encrypt("123-45-6789", aad: "users:42:ssn")

puts decrypt(token, aad: "users:42:ssn")
begin
  decrypt(token, aad: "users:43:ssn")    # copied into another user's row
rescue OpenSSL::Cipher::CipherError
  puts "ciphertext does not belong to users:43"
end
123-45-6789
ciphertext does not belong to users:43

Why not ECB or plain CBC

Never use ECB mode. It encrypts each 16-byte block on its own, so identical plaintext blocks produce identical ciphertext blocks and patterns in the data show through:

require 'openssl'

key = OpenSSL::Random.random_bytes(32)
plaintext = "ATTACK AT DAWN!!" * 3              # three identical 16-byte blocks

ecb = OpenSSL::Cipher.new("aes-256-ecb").encrypt
ecb.key = key
ct = ecb.update(plaintext) + ecb.final
puts ct.unpack1("H*").scan(/.{32}/).first(3)
d559337623e1993523dcfbb23f34e927
d559337623e1993523dcfbb23f34e927
d559337623e1993523dcfbb23f34e927

CBC with a random IV hides those patterns, but it doesn't detect tampering, and decryption errors can lead to padding-oracle attacks. If you must use CBC to interoperate with another system, add an HMAC over the IV and the ciphertext (encrypt-then-MAC), and verify the HMAC before you decrypt.

Deriving keys

From a password

A password isn't a key: it's too short and too predictable. A slow KDF with a random salt stretches it into a key. Store the salt (and the parameters) next to the ciphertext:

require 'openssl'

password = "correct horse battery staple"
salt = OpenSSL::Random.random_bytes(16)   # store next to the ciphertext

key = OpenSSL::KDF.pbkdf2_hmac(password, salt: salt, iterations: 600_000,
                               length: 32, hash: "SHA256")
p key.bytesize

# same password + salt => same key
again = OpenSSL::KDF.pbkdf2_hmac(password, salt: salt, iterations: 600_000,
                                 length: 32, hash: "SHA256")
p key == again

# scrypt is memory-hard and a better choice when available
key2 = OpenSSL::KDF.scrypt(password, salt: salt, N: 2**15, r: 8, p: 1, length: 32)
p key2.bytesize
32
true
32

600,000 iterations of PBKDF2-HMAC-SHA256 is the current OWASP recommendation. To store passwords for login (as opposed to encrypting with them), use bcrypt or Argon2 as described in Password hashing.

Subkeys from a master key with HKDF

If you already have a strong random secret, you don't need a slow KDF. Use HKDF to derive independent keys for different purposes, so that the same key is never used for two jobs:

require 'openssl'

master = OpenSSL::Random.random_bytes(32)

enc_key  = OpenSSL::KDF.hkdf(master, salt: "", info: "myapp encryption v1", length: 32, hash: "SHA256")
mac_key  = OpenSSL::KDF.hkdf(master, salt: "", info: "myapp cookie-mac v1", length: 32, hash: "SHA256")

p enc_key.bytesize
p enc_key == mac_key
32
false

Digital signatures with Ed25519

With public-key cryptography the private key signs and the public key verifies. You can publish the public key, and anyone can check that a release, a license file or an API request came from the holder of the private key. Ed25519 is fast, has small keys and signatures, and is hard to misuse, so choose it for new designs:

require 'openssl'

private_key = OpenSSL::PKey.generate_key("ED25519")
public_key  = OpenSSL::PKey.read(private_key.public_to_pem)

message = "release v2.4.0 sha256=0c9a42b3d065a640"

signature = private_key.sign(nil, message)   # nil: Ed25519 has a built-in hash
p signature.bytesize

p public_key.verify(nil, signature, message)
p public_key.verify(nil, signature, message.sub("2.4.0", "2.4.1"))

puts public_key.public_to_pem
64
true
false
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEATsyUKEd/m1Nwp+b63SFrp1TrmPvtyoQ6tGYyC9hdVGU=
-----END PUBLIC KEY-----

Saving and loading keys

Write private keys to disk encrypted with a passphrase. OpenSSL::PKey.read detects the key type from the PEM, so the same call loads RSA, EC and Ed25519 keys:

require 'openssl'

key = OpenSSL::PKey.generate_key("ED25519")

# private key encrypted with a passphrase (PKCS#8, AES-256-CBC)
pem = key.private_to_pem(OpenSSL::Cipher.new("aes-256-cbc"), "s3cret passphrase")
puts pem.lines.first
File.write("signing_key.pem", pem)

loaded = OpenSSL::PKey.read(File.read("signing_key.pem"), "s3cret passphrase")
p loaded.oid
p loaded.public_to_pem == key.public_to_pem

begin
  OpenSSL::PKey.read(File.read("signing_key.pem"), "wrong")
rescue OpenSSL::PKey::PKeyError => e
  puts "bad passphrase: #{e.class}"
end
File.delete("signing_key.pem")
-----BEGIN ENCRYPTED PRIVATE KEY-----
"ED25519"
true
bad passphrase: OpenSSL::PKey::PKeyError

Keys made with the openssl command line tool load the same way, for example a key from openssl genpkey -algorithm ed25519 -out key.pem.

RSA: signatures and key wrapping

You still need RSA to interoperate with JWT RS256/PS256, SAML, older APIs and X.509 certificates. Use keys of at least 3072 bits, PSS padding for signatures and OAEP padding for encryption. Avoid the legacy public_encrypt/private_decrypt methods: they default to PKCS#1 v1.5 padding, which is vulnerable to padding-oracle attacks.

require 'openssl'

rsa = OpenSSL::PKey::RSA.generate(3072)
pub = OpenSSL::PKey.read(rsa.public_to_pem)

data = "invoice #1001 total=99.00"

# RSA-PSS signature with SHA-256
sig = rsa.sign_pss("SHA256", data, salt_length: :digest, mgf1_hash: "SHA256")
p sig.bytesize
p pub.verify_pss("SHA256", sig, data, salt_length: :auto, mgf1_hash: "SHA256")

# RSA-OAEP encryption: only for small payloads such as a symmetric key
opts = { "rsa_padding_mode" => "oaep", "rsa_oaep_md" => "sha256", "rsa_mgf1_md" => "sha256" }
aes_key = OpenSSL::Random.random_bytes(32)
wrapped = pub.encrypt(aes_key, opts)
p wrapped.bytesize
p rsa.decrypt(wrapped, opts) == aes_key
384
true
384
true

RSA can only encrypt a few hundred bytes. To encrypt a file for someone's public key, generate a random AES key, encrypt the file with AES-GCM, and encrypt only the AES key with RSA-OAEP. This is called hybrid encryption. Generating a 3072-bit key takes a noticeable fraction of a second, so generate keys once and load them afterwards.

Key exchange with X25519

Two parties can agree on a shared secret while exchanging only public keys. Anyone who sees both public keys still can't compute the secret. This is how TLS and the Signal protocol set up session keys:

require 'openssl'

alice = OpenSSL::PKey.generate_key("X25519")
bob   = OpenSSL::PKey.generate_key("X25519")

# each side only needs the other's public key
alice_pub = OpenSSL::PKey.read(alice.public_to_pem)
bob_pub   = OpenSSL::PKey.read(bob.public_to_pem)

s1 = alice.derive(bob_pub)
s2 = bob.derive(alice_pub)
p s1 == s2, s1.bytesize

# never use the raw shared secret as a key: run it through HKDF
key = OpenSSL::KDF.hkdf(s1, salt: "", info: "chat session v1", length: 32, hash: "SHA256")
p key.bytesize
true
32
32

Key exchange on its own doesn't tell you who you're talking to: a man in the middle can swap in their own public keys. Authenticate the public keys, for example by signing them with Ed25519 or by using certificates. That's why you should normally just use TLS (Net::HTTP with use_ssl: true) instead of building your own protocol.

Higher-level options

Use a higher-level API that has already made these decisions when you can:

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents