module Crypto
Cryptography: require "crypto". RSA keys (PEM and DER, PKCS#8, PKCS#1
and SPKI) and signatures (PKCS#1 v1.5 and PSS), as HTTP Signatures, JWT
RS256 and webhook signatures need; AES-GCM, to encrypt a secret at rest
or seal a cookie; argon2id (Crypto::Argon2), to store passwords; and
Crypto.random_bytes, for keys and nonces.
require "crypto"
key = Crypto::RSA::PrivateKey.from_pem(File.read("std/test/fixtures/crypto/rsa2048_pkcs8.pem"))
sig = key.sign("hello", :sha256)
key.public_key.verify("hello", sig, :sha256) # => true
key.public_key.verify("hullo", sig, :sha256) # => false
Keys are data values holding their DER, so they are immutable and
Shareable, and two readings of one key are ==; their inspect and
to_s never show the key. The runtime keeps the keys it parsed (by
contents), so signing again with one key does not parse it again.
Keys of 1024 to 8192 bits are read (generate makes 2048 to 4096).
There is no RSA encryption, no encrypted PEM, no EC or Ed25519 key, no
other cipher mode (CBC, CTR), and no key derivation but
Digest::PBKDF2 (argon2id makes password hashes, not keys) yet.
Classes and modules
Crypto::AESAES, in its authenticated mode GCM.Crypto::Argon2argon2id password hashes (RFC 9106), through the RustCrypto argon2 crate: what a server stores for a password, as a PHC string such as $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash> (the salt and the 32-byte hash in unpadded Base64), which names its parameters, so that stored hashes stay readable when the parameters change.Crypto::AuthenticationErrorData that did not authenticate: the key, the nonce or the associated data is not the one it was sealed with, or the data was changed. The message never includes the data.Crypto::ErrorA key that does not parse, is of another kind, or is too small; a PEM text that is not one key.Crypto::RSARSA keys and signatures, through the RustCrypto rsa crate. A hash is named by a symbol: :sha256, :sha384 or :sha512 (ArgumentError otherwise).
Class methods
def self.random_bytes(n: Int) -> Bytes
n bytes (0 to 1 MiB, ArgumentError otherwise) from the operating
system's cryptographic random source (getrandom): for keys, nonces
and tokens; Crypto::Error if that source fails. Not a replacement
for Random, which is reproducible.
Crypto.random_bytes(16).size # => 16
Crypto.random_bytes(16) == Crypto.random_bytes(16) # => false