Module std::crypto::encrypt

Symmetric encryption and decryption.

Encrypt and decrypt data using AES-256-GCM.

Examples

import std::crypto::encrypt;

fn main() {
    let key = crypto.random_bytes(32);
    let ciphertext = encrypt.seal(key, "hello world");
    match encrypt.try_open(key, ciphertext) {
        Ok(plaintext) => println(plaintext),
        Err(err) => println(encrypt.error_message(err)),
    }
}

Contents

Functions

Function error_message

pub fn error_message(err: CryptoError) -> string

Return a human-readable message for a [CryptoError].

Function last_open_error

pub fn last_open_error() -> CryptoError

Return the last try_open error observed on this thread.

Function seal

pub fn seal(key: bytes, plaintext: string) -> bytes

Encrypt plaintext using AES-256-GCM with the given key.

Returns the ciphertext (nonce + encrypted data) as bytes.

Function try_open

pub fn try_open(key: bytes, ciphertext: bytes) -> Result<string, CryptoError>

Decrypt ciphertext using AES-256-GCM with the given key.

Returns Err(CryptoError) when the key or ciphertext is invalid, AES-GCM authentication fails, or the decrypted bytes are not valid UTF-8.

Function open

pub fn open(key: bytes, ciphertext: bytes) -> string

Decrypt ciphertext using AES-256-GCM with the given key.

Panics on invalid input or authentication failure. Use try_open for structured error handling of attacker-controlled ciphertext.

Function must_open

pub fn must_open(key: bytes, ciphertext: bytes) -> string

Decrypt ciphertext and panic on failure.

Alias for open, provided for callers that prefer an explicit must-style name at the call site.

Types

Enum CryptoError

Structured errors returned by try_open.

Variants

None

No error was observed.

InvalidKey

The key input was not a valid AES-256 key.

ShortCiphertext

The ciphertext was too short to contain a nonce and GCM tag.

AuthFailed

AES-GCM authentication failed.

InvalidUtf8

The decrypted plaintext was not valid UTF-8.

AllocationFailure

Native string allocation failed.