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.

<std:crypto>:23

Classes and modules

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

<std:crypto>:44