Skip to content

crypto

The crypto module provides cryptographic hashing, HMAC authentication, encoding utilities, random byte generation, and Ed25519 digital signatures.

use std::core::crypto

All hash functions take a string and return a hex-encoded digest string.

Compute the SHA-256 hash.

crypto::sha256("hello")
// "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

Compute the SHA-512 hash.

Compute the SHA-1 hash. Provided for legacy compatibility — prefer SHA-256 for new applications.

Compute the MD5 hash. Provided for legacy compatibility — not suitable for security purposes.

crypto::hmac_sha256(data: string, key: string) -> string

Section titled “crypto::hmac_sha256(data: string, key: string) -> string”

Compute HMAC-SHA256 of data with the given key, returning a hex-encoded digest.

let mac = crypto::hmac_sha256("message", "secret-key")

crypto::base64_encode(data: string) -> string

Section titled “crypto::base64_encode(data: string) -> string”

Encode a string to Base64.

crypto::base64_encode("Hello, World!") // "SGVsbG8sIFdvcmxkIQ=="

crypto::base64_decode(encoded: string) -> Result<string, string>

Section titled “crypto::base64_decode(encoded: string) -> Result<string, string>”

Decode a Base64 string. Returns Err if the input is not valid Base64.

let text = crypto::base64_decode("SGVsbG8sIFdvcmxkIQ==")?
// "Hello, World!"

crypto::hex_encode(data: string) -> string

Section titled “crypto::hex_encode(data: string) -> string”

Encode a string as hexadecimal.

crypto::hex_encode("hello") // "68656c6c6f"

crypto::hex_decode(hex: string) -> Result<string, string>

Section titled “crypto::hex_decode(hex: string) -> Result<string, string>”

Decode a hexadecimal string. Returns Err if the input is not valid hex.

Generate n random bytes, returned as a hex-encoded string. Maximum 65,536 bytes.

let token = crypto::random_bytes(32) // 64-char hex string

crypto::ed25519_generate_keypair() -> object

Section titled “crypto::ed25519_generate_keypair() -> object”

Generate an Ed25519 keypair. Returns a HashMap with hex-encoded keys:

let kp = crypto::ed25519_generate_keypair()
// kp["public_key"] -- 64-char hex (32 bytes)
// kp["secret_key"] -- 64-char hex (32 bytes)

crypto::ed25519_sign(message: string, secret_key: string) -> string

Section titled “crypto::ed25519_sign(message: string, secret_key: string) -> string”

Sign a message with an Ed25519 secret key. Returns a hex-encoded 64-byte signature.

let sig = crypto::ed25519_sign("my message", kp["secret_key"])

crypto::ed25519_verify(message: string, signature: string, public_key: string) -> bool

Section titled “crypto::ed25519_verify(message: string, signature: string, public_key: string) -> bool”

Verify an Ed25519 signature against a message and public key.

let valid = crypto::ed25519_verify("my message", sig, kp["public_key"])
// true