Crypto
import "std/data" (included in import "std") · namespace std.data
Cryptography through the system's OpenSSL (libcrypto, loaded the first time it is needed): digests and HMAC with SHA-1, SHA-256, SHA-384 and SHA-512; secure random bytes and constant-time comparison; AES-GCM authenticated encryption; asymmetric keys (RSA, ECDSA on P-256/P-384/P-521, Ed25519) that sign and verify and read and write PEM and JWK; and scrypt password hashes. Key generation and JWK output need OpenSSL 3 (Crypto.hasKeyGeneration()).
import "std"
fn main() {
print(Crypto.sha512(Bytes.fromString("abc")).toHex()[..16])
print(Crypto.hmac("sha256", Bytes.fromString("Jefe"), Bytes.fromString("what do ya want for nothing?")).toHex()[..16])
let key = AesGcm.generateKey()
let sealed = AesGcm.encrypt(key, Bytes.fromString("attack at dawn"))
print(AesGcm.decrypt(key, sealed).toString())
let signer = CryptoKey.generate("ed25519")
let msg = Bytes.fromString("hello")
let sig = signer.sign(msg)
let pub = CryptoKey.fromPem(signer.publicPem())
print("${pub.kind()}: ${pub.verify(msg, sig)}, tampered: ${pub.verify(Bytes.fromString("hellp"), sig)}")
PasswordHash.costLog = 12 // (the default, 15, takes 32 MiB and ~0.1 s)
let h = PasswordHash.make("hunter2")
print("${Str.startsWith(h, "$scrypt$")} ${PasswordHash.verify("hunter2", h)} ${PasswordHash.verify("hunter3", h)}")
}ddaf35a193617aba
5bdcc146bf60754e
attack at dawn
ed25519: true, tampered: false
true true false- AES-GCM output is the nonce (12 bytes, random each time), the ciphertext and the tag (16 bytes). Decrypting checks the tag: altered data, other associated data or the wrong key is a
ValueError, never garbage. - Keys:
CryptoKey.generate("rsa" | "rsa-2048" | "rsa-4096" | "p256" | "p384" | "p521" | "ed25519"),fromPem(private or public, any common PEM form),fromJwk(public). ECDSA signatures fromsignare DER; JWT turns them into ther || sform JWS uses. - Passwords:
PasswordHash.makewrites$scrypt$ln=15,r=8,p=1$<salt>$<hash>, carrying its own settings, soverifykeeps working after the defaults change andneedsRehashsays when to store a stronger one. Crypto.equalscompares bytes in time that depends only on their lengths;Hash.equalsdoes the same for strings.
class Crypto
Digests, HMAC, random bytes and constant-time comparison, through libcrypto.
Static members
static fn available() -> bool— Whether libcrypto could be loaded.static fn hasKeyGeneration() -> bool— Whether key generation and JWK output work (OpenSSL 3).static fn digest(algorithm: string, data: Bytes) -> Bytes— The digest ofdatawith "sha1", "sha256", "sha384" or "sha512".static fn sha256(data: Bytes) -> Bytesstatic fn sha384(data: Bytes) -> Bytesstatic fn sha512(data: Bytes) -> Bytesstatic fn sha512Hex(text: string) -> string— SHA-512 of text, as 128 hex digits.static fn hmac(algorithm: string, key: Bytes, data: Bytes) -> Bytes— The HMAC ofdataunderkeywith "sha1", "sha256", "sha384" or "sha512".static fn randomBytes(n: int) -> Bytes—nbytes from the system's secure random source.static fn equals(a: Bytes, b: Bytes) -> bool— Whetheraandbhold the same bytes, in time that depends only on their lengths.static fn require()static fn digestId(algorithm: string) -> int
class AesGcm
AES-GCM authenticated encryption: what comes out is the nonce (12 bytes), the ciphertext and the tag (16 bytes); decrypting checks the tag, so altered data (or the wrong key) is a ValueError, never garbage.
Static members
static fn generateKey(bits: int = 256) -> Bytes— A new random 256-bit (or 128-bit) key.static fn encrypt(key: Bytes, plaintext: Bytes, associated: Bytes = null) -> Bytes—plaintextsealed underkey(16 or 32 bytes), with optional associated data that must match on decryption (and is not encrypted).static fn decrypt(key: Bytes, sealed: Bytes, associated: Bytes = null) -> Bytes— The plaintext ofsealed; ValueError when it was altered or the key is wrong.static fn encryptText(key: Bytes, text: string) -> string— Text sealed, as URL-safe Base64.static fn decryptText(key: Bytes, sealed: string) -> string— The text that encryptText sealed.
class CryptoKey
An asymmetric key: RSA, ECDSA (P-256, P-384, P-521) or Ed25519, private (signs, and holds its public half) or public (verifies).
Static members
static fn generate(kind: string) -> CryptoKey— A new key: "rsa" (3072 bits), "rsa-2048", "rsa-3072", "rsa-4096", "p256", "p384", "p521", or "ed25519" (needs OpenSSL 3).static fn fromPem(pem: string) -> CryptoKey— A key from PEM: a private key ("PRIVATE KEY", "RSA PRIVATE KEY", "EC PRIVATE KEY") or a public one ("PUBLIC KEY"); ValueError otherwise.static fn fromJwk(jwk: JsonValue) -> CryptoKey— A public key from a JWK (kty RSA with n and e, EC with crv, x and y, or OKP Ed25519 with x).
Methods
fn kind() -> string— "rsa", "ec" or "ed25519".fn bits() -> int— The key's size in bits (3072 for RSA-3072, 256 for P-256 and Ed25519's 253).fn isPrivate() -> boolfn privatePem() -> string— The private key as PKCS#8 PEM (unencrypted: keep it secret).fn publicPem() -> string— The public key as PEM ("PUBLIC KEY").fn publicKey() -> CryptoKey— The public half, as its own key.fn sign(data: Bytes, hash: string = "sha256") -> Bytes— A signature ofdata(hash: "sha256", "sha384" or "sha512"; Ed25519 ignores it). ECDSA signatures are DER (see JWT for r || s).fn verify(data: Bytes, signature: Bytes, hash: string = "sha256") -> bool— Whethersignatureis this key's (or its private half's) signature ofdata.fn toJwk() -> JsonValue— The public key as a JWK (kty, and n/e, crv/x/y or crv/x), for publishing in a JWKS (OpenSSL 3).
class Der
DER pieces, for writing keys (SubjectPublicKeyInfo) from their parts.
Static members
static fn raw(hex: string) -> Bytesstatic fn tagged(tag: int, body: Bytes) -> Bytesstatic fn seq(body: Bytes) -> Bytesstatic fn uint(b: Bytes) -> Bytes— A non-negative INTEGER from big-endian bytes.static fn bitString(b: Bytes) -> Bytesstatic fn pem(label: string, der: Bytes) -> string— DER as PEM with the given label.
class PasswordHash
Password hashes with scrypt (memory-hard), as text that carries its own parameters and salt: "$scrypt$ln=15,r=8,p=1$<salt>$<hash>". The default cost (N = 2^15, r = 8) uses 32 MiB and about a tenth of a second per hash.
Static members
static costLog: int = 15— log2 of N, r and p for new hashes.static blockSize: int = 8static parallelism: int = 1static fn make(password: string) -> stringstatic fn verify(password: string, hash: string) -> bool— Whetherpasswordis the onehashwas made from (false for text that is not such a hash).static fn needsRehash(hash: string) -> bool— Whetherhashwas made with weaker settings than the current ones (make a new one at sign-in).