Crypto¶
Use these APIs for hashes, secure random bytes, and authenticated encryption. They produce byte arrays; use Encoding to display or store those bytes as text. Check the availability table before choosing encryption for a browser app.
Import: import system.crypto;
SHA-2 hashes, HMAC, a secure RNG, and AES-256-GCM. SHA-256, SHA-512, and HMAC-SHA256 give identical results on every target, including the browser. The secure RNG uses the operating system (native or Node) or Web Crypto in the browser. APIs return raw byte[] — format with encoding. Not TLS.
import system;
import system.crypto;
import system.encoding;
fun main() {
let msg = Encoding.utf8_encode("hello");
System.println(Encoding.hex_encode(Sha256.hash(msg)));
}
| Runtime | Digests / CSPRNG | AES-GCM |
|---|---|---|
| Native / Node | yes | yes |
| Browser | Web Crypto | compile error (@native / @node only) |
| Call | Meaning |
|---|---|
Sha256.hash(bytes) |
32-byte digest |
Sha512.hash(bytes) |
64-byte digest |
HmacSha256.sign(key, data) |
HMAC |
SecureRandom.bytes(n) |
CSPRNG bytes |
AesGcm / AesGcmKey |
authenticated encryption (native/Node) |
let key = AesGcmKey.generate().unwrap();
let nonce = AesGcm.generate_nonce().unwrap();
let plain = Encoding.utf8_encode("secret");
let aad = Encoding.utf8_encode("");
let cipher = (AesGcm.encrypt(key, nonce, plain, aad)).unwrap();
let back = (AesGcm.decrypt(key, nonce, cipher, aad)).unwrap();
System.println(Encoding.utf8_decode(back));
For games and tests, use Random instead of SecureRandom.