std.crypto
std.crypto provides AES encryption, file encryption, and secure random bytes.
It is available only when the engine was built with OpenSSL — otherwise
calls throw UNSUPPORTED.
Reference
aes_encrypt(data, passphrase[, bits = 256])
aes_decrypt(payload, passphrase)
encrypt_file(in, out, passphrase[, bits = 256])
decrypt_file(in, out, passphrase) // bits read from the file header
random_bytes(n)
| Function | Description |
|---|---|
aes_encrypt(data, pass[, bits]) | AES-128/256-CBC, PKCS#7, random salt + IV → binary payload |
aes_decrypt(payload, pass) | Reverse aes_encrypt; throws on wrong password |
encrypt_file(in, out, pass[, bits]) | File variant of aes_encrypt |
decrypt_file(in, out, pass) | File variant — key size read from the file header |
random_bytes(n) | n cryptographically secure random bytes |
bits is 128 or 256 (default 256). The payload/header encodes salt,
IV, and mode so decrypt does not need the bit size repeated.
Examples
// in-memory round-trip
var payload = std.crypto.aes_encrypt("secret", "my-pass")
print(std.crypto.aes_decrypt(payload, "my-pass")) // secret
// print(std.crypto.aes_decrypt(payload, "wrong")) // throws
// file round-trip
std.crypto.encrypt_file("plain.txt", "plain.enc", "my-pass")
std.crypto.decrypt_file("plain.enc", "plain2.txt", "my-pass")
// random material → hash it
var bytes = std.crypto.random_bytes(16)
print(std.hash.sha256(bytes))
// explicit AES-128
var p128 = std.crypto.aes_encrypt("hi", "pass", 128)
print(std.crypto.aes_decrypt(p128, "pass"))
File paths accept ~ and $VAR expansion, like std.file.
Availability
Check at runtime whether the engine was built with OpenSSL:
// std.crypto itself is always present as an object;
// its functions throw UNSUPPORTED if OpenSSL was not linked.
print(std.crypto.random_bytes(4)) // throws UNSUPPORTED without OpenSSL
note
Without OpenSSL, std.hash still works (its digests are built in), but every
std.crypto call throws UNSUPPORTED.