Grav v1.14.0

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()).

grav
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)}")
}
Output
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 from sign are DER; JWT turns them into the r || s form JWS uses.
  • Passwords: PasswordHash.make writes $scrypt$ln=15,r=8,p=1$<salt>$<hash>, carrying its own settings, so verify keeps working after the defaults change and needsRehash says when to store a stronger one.
  • Crypto.equals compares bytes in time that depends only on their lengths; Hash.equals does 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 of data with "sha1", "sha256", "sha384" or "sha512".
  • static fn sha256(data: Bytes) -> Bytes
  • static fn sha384(data: Bytes) -> Bytes
  • static fn sha512(data: Bytes) -> Bytes
  • static 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 of data under key with "sha1", "sha256", "sha384" or "sha512".
  • static fn randomBytes(n: int) -> Bytes — n bytes from the system's secure random source.
  • static fn equals(a: Bytes, b: Bytes) -> bool — Whether a and b hold 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 — plaintext sealed under key (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 of sealed; 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() -> bool
  • fn 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 of data (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 — Whether signature is this key's (or its private half's) signature of data.
  • 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) -> Bytes
  • static fn tagged(tag: int, body: Bytes) -> Bytes
  • static fn seq(body: Bytes) -> Bytes
  • static fn uint(b: Bytes) -> Bytes — A non-negative INTEGER from big-endian bytes.
  • static fn bitString(b: Bytes) -> Bytes
  • static 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 = 8
  • static parallelism: int = 1
  • static fn make(password: string) -> string
  • static fn verify(password: string, hash: string) -> bool — Whether password is the one hash was made from (false for text that is not such a hash).
  • static fn needsRehash(hash: string) -> bool — Whether hash was made with weaker settings than the current ones (make a new one at sign-in).

Edit this page on GitHub