Module std::crypto::encrypt

Symmetric encryption and decryption.

Encrypt and decrypt data using AES-256-GCM.

Examples

import std.crypto.crypto;
import std.crypto.encrypt;

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

Contents

Functions

Function last_open_error

pub fn last_open_error() -> CryptoError

Return the last open error observed on this thread.

Function last_seal_error

pub fn last_seal_error() -> CryptoError

Return the last seal error observed on this thread.

Reading consumes the status, so a later successful seal is never read as this failure.

Function seal

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

Encrypt plaintext using AES-256-GCM, reporting an unusable key instead of failing out of the FFI boundary.

A key that is not 32 bytes, a plaintext the boundary cannot read, an entropy failure, and an allocation failure are all returned as Err(CryptoError). No path returns an empty ciphertext as success: an empty plaintext still seals to a nonce plus a GCM tag.

Function open

pub fn 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 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 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.

EntropyFailure

The system entropy source could not produce a nonce.