Module std.crypto.encrypt
Symmetric encryption and decryption.
Encrypt and decrypt data using AES-256-GCM.
Examples
import std.crypto.hash;
import std.crypto.encrypt;
fn main() {
let key = match hash.random_bytes(32) {
.Ok(key) => key,
.Err(reason) => panic(f"{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 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.
Types
Enum CryptoError
Structured errors returned by open.
Variants
InvalidKeyThe key input was not a valid AES-256 key.
ShortCiphertextThe ciphertext was too short to contain a nonce and GCM tag.
AuthFailedAES-GCM authentication failed.
InvalidUtf8The decrypted plaintext was not valid UTF-8.
AllocationFailureNative string allocation failed.
EntropyFailureThe system entropy source could not produce a nonce.