// ChaCha20-Poly1305 (RFC 8439 ยง2.8.2) and HKDF-SHA-256 (RFC 5869, test // cases 1 and 3) on both backends (ADR 0071). import std/bytes import std/crypto import std/io import std/list import std/string /// The bytes a lowercase hexadecimal text spells, two digits a byte. fn unhex :: text: String -> Bytes { bytes.from_list (byte_values (list.map (string.chars text) digit)) } fn byte_values :: digits: List -> List { match digits { [high, low, ..rest] -> [high * 16 + low, ..byte_values rest], _ -> [] } } fn digit :: c: String -> Int { match string.find "0123456789abcdef" c { Some(at) -> at, None -> 0 } } pub fn main :: -> () / { let key = bytes.from_list (list.range 128 159) let nonce = unhex "070000004041424344454647" let aad = unhex "50515253c0c1c2c3c4c5c6c7" let plaintext = bytes.from_string "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it." let expected = unhex "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd0600691" let sealed = crypto.chacha20_poly1305_seal key nonce plaintext aad io.println "sealed {sealed == expected}" io.println "opened {crypto.chacha20_poly1305_open key nonce sealed aad == Ok(plaintext)}" let other = bytes.from_string "other" let refusals = [ crypto.chacha20_poly1305_open key nonce sealed other , crypto.chacha20_poly1305_open (bytes.concat (bytes.slice key 1 32) (unhex "00")) nonce sealed aad , crypto.chacha20_poly1305_open key (unhex "000000000000000000000000") sealed aad , crypto.chacha20_poly1305_open key nonce (bytes.slice sealed 1 129) aad , crypto.chacha20_poly1305_open key nonce (bytes.empty ()) aad ] io.println "{list.map refusals fn r { r == Error("crypto: the sealed message does not authenticate under this key, nonce and associated data") }:?}" let empty = crypto.chacha20_poly1305_seal key nonce (bytes.empty ()) (bytes.empty ()) io.println "{bytes.length empty} {crypto.chacha20_poly1305_open key nonce empty (bytes.empty ()) == Ok(bytes.empty ())}" let secret = unhex "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" let one = crypto.hkdf_sha256 secret (unhex "000102030405060708090a0b0c") (unhex "f0f1f2f3f4f5f6f7f8f9") 42 io.println "hkdf 1 {one == unhex "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"}" let three = crypto.hkdf_sha256 secret (bytes.empty ()) (bytes.empty ()) 42 io.println "hkdf 3 {three == unhex "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"}" io.println "{bytes.length (crypto.hkdf_sha256 secret (bytes.empty ()) (bytes.empty ()) 8160)}" } //> sealed True //> opened True //> [True, True, True, True, True] //> 16 True //> hkdf 1 True //> hkdf 3 True //> 8160