///| fn rotl32(x : UInt32, n : Int32) -> UInt32 { (x << n) | (x >> (32 - n)) } ///| fn read_u32_le(data : Bytes, offset : Int32) -> UInt32 { data[offset].to_uint() | (data[offset + 1].to_uint() << 8) | (data[offset + 2].to_uint() << 16) | (data[offset + 3].to_uint() << 24) } ///| fn write_u32_le(buf : FixedArray[Byte], offset : Int32, v : UInt32) -> Unit { buf[offset] = (v & 0xFFU).to_byte() buf[offset + 1] = ((v >> 8) & 0xFFU).to_byte() buf[offset + 2] = ((v >> 16) & 0xFFU).to_byte() buf[offset + 3] = ((v >> 24) & 0xFFU).to_byte() } ///| fn quarter_round( s : FixedArray[UInt32], a : Int32, b : Int32, c : Int32, d : Int32, ) -> Unit { s[a] = s[a] + s[b] s[d] = rotl32(s[d] ^ s[a], 16) s[c] = s[c] + s[d] s[b] = rotl32(s[b] ^ s[c], 12) s[a] = s[a] + s[b] s[d] = rotl32(s[d] ^ s[a], 8) s[c] = s[c] + s[d] s[b] = rotl32(s[b] ^ s[c], 7) } ///| /// Computes a single 64-byte ChaCha20 keystream block (RFC 8439 Section 2.3). pub fn chacha20_block( key : Bytes, counter : UInt32, nonce : Bytes, ) -> Bytes raise CryptoError { if key.length() != 32 { raise InvalidKeyLength( "ChaCha20 requires a 32-byte key, got \{key.length()}", ) } if nonce.length() != 12 { raise InvalidNonceLength( "ChaCha20 requires a 12-byte nonce, got \{nonce.length()}", ) } let state : FixedArray[UInt32] = [ 0x61707865U, 0x3320646eU, 0x79622d32U, 0x6b206574U, read_u32_le(key, 0), read_u32_le(key, 4), read_u32_le(key, 8), read_u32_le(key, 12), read_u32_le(key, 16), read_u32_le(key, 20), read_u32_le(key, 24), read_u32_le(key, 28), counter, read_u32_le(nonce, 0), read_u32_le(nonce, 4), read_u32_le(nonce, 8), ] let working = FixedArray::make(16, 0U) for i = 0; i < 16; i = i + 1 { working[i] = state[i] } for _i = 0; _i < 10; _i = _i + 1 { quarter_round(working, 0, 4, 8, 12) quarter_round(working, 1, 5, 9, 13) quarter_round(working, 2, 6, 10, 14) quarter_round(working, 3, 7, 11, 15) quarter_round(working, 0, 5, 10, 15) quarter_round(working, 1, 6, 11, 12) quarter_round(working, 2, 7, 8, 13) quarter_round(working, 3, 4, 9, 14) } let out = FixedArray::make(64, b'\x00') for i = 0; i < 16; i = i + 1 { write_u32_le(out, i * 4, working[i] + state[i]) } Bytes::from_array(out) } ///| /// Encrypts or decrypts `input` with ChaCha20 starting at `counter` (RFC 8439 Section 2.4). pub fn chacha20_xor( key : Bytes, counter : UInt32, nonce : Bytes, input : Bytes, ) -> Bytes raise CryptoError { if key.length() != 32 { raise InvalidKeyLength( "ChaCha20 requires a 32-byte key, got \{key.length()}", ) } if nonce.length() != 12 { raise InvalidNonceLength( "ChaCha20 requires a 12-byte nonce, got \{nonce.length()}", ) } let len = input.length() let out = FixedArray::make(len, b'\x00') let mut ctr = counter let mut offset = 0 while offset < len { let block = chacha20_block(key, ctr, nonce) let chunk = if len - offset < 64 { len - offset } else { 64 } for i = 0; i < chunk; i = i + 1 { out[offset + i] = (input[offset + i].to_int() ^ block[i].to_int()).to_byte() } offset += chunk ctr = ctr + 1U } Bytes::from_array(out) } ///| /// Computes the 16-byte Poly1305 MAC (RFC 8439 Section 2.5). /// `key` must be a 32-byte one-time key. pub fn poly1305_mac(key : Bytes, msg : Bytes) -> Bytes raise CryptoError { if key.length() != 32 { raise InvalidKeyLength( "Poly1305 requires a 32-byte one-time key, got \{key.length()}", ) } // Load and clamp r (first 16 bytes) into 5 x 26-bit limbs let t0 = read_u32_le(key, 0).to_uint64() let t1 = read_u32_le(key, 4).to_uint64() let t2 = read_u32_le(key, 8).to_uint64() let t3 = read_u32_le(key, 12).to_uint64() let r0 = t0 & 0x03ffffffUL let r1 = ((t0 >> 26) | (t1 << 6)) & 0x03ffff03UL let r2 = ((t1 >> 20) | (t2 << 12)) & 0x03ffc0ffUL let r3 = ((t2 >> 14) | (t3 << 18)) & 0x03f03fffUL let r4 = (t3 >> 8) & 0x000fffffUL let s1 = r1 * 5UL let s2 = r2 * 5UL let s3 = r3 * 5UL let s4 = r4 * 5UL let mut h0 = 0UL let mut h1 = 0UL let mut h2 = 0UL let mut h3 = 0UL let mut h4 = 0UL let len = msg.length() let mut offset = 0 while offset < len { let rem = len - offset let block_len = if rem >= 16 { 16 } else { rem } let blk = FixedArray::make(16, b'\x00') for i = 0; i < block_len; i = i + 1 { blk[i] = msg[offset + i] } let hibit = if block_len == 16 { 1UL << 24 } else { blk[block_len] = b'\x01' 0UL } let b_bytes = Bytes::from_array(blk) let m0 = read_u32_le(b_bytes, 0).to_uint64() let m1 = read_u32_le(b_bytes, 4).to_uint64() let m2 = read_u32_le(b_bytes, 8).to_uint64() let m3 = read_u32_le(b_bytes, 12).to_uint64() h0 = h0 + (m0 & 0x03ffffffUL) h1 = h1 + (((m0 >> 26) | (m1 << 6)) & 0x03ffffffUL) h2 = h2 + (((m1 >> 20) | (m2 << 12)) & 0x03ffffffUL) h3 = h3 + (((m2 >> 14) | (m3 << 18)) & 0x03ffffffUL) h4 = h4 + (m3 >> 8) + hibit let d0 = h0 * r0 + h1 * s4 + h2 * s3 + h3 * s2 + h4 * s1 let mut d1 = h0 * r1 + h1 * r0 + h2 * s4 + h3 * s3 + h4 * s2 let mut d2 = h0 * r2 + h1 * r1 + h2 * r0 + h3 * s4 + h4 * s3 let mut d3 = h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * s4 let mut d4 = h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0 let mut c = d0 >> 26 h0 = d0 & 0x03ffffffUL d1 = d1 + c c = d1 >> 26 h1 = d1 & 0x03ffffffUL d2 = d2 + c c = d2 >> 26 h2 = d2 & 0x03ffffffUL d3 = d3 + c c = d3 >> 26 h3 = d3 & 0x03ffffffUL d4 = d4 + c c = d4 >> 26 h4 = d4 & 0x03ffffffUL h0 = h0 + c * 5UL c = h0 >> 26 h0 = h0 & 0x03ffffffUL h1 = h1 + c offset += block_len } // Final carry propagation let mut c = h1 >> 26 h1 = h1 & 0x03ffffffUL h2 = h2 + c c = h2 >> 26 h2 = h2 & 0x03ffffffUL h3 = h3 + c c = h3 >> 26 h3 = h3 & 0x03ffffffUL h4 = h4 + c c = h4 >> 26 h4 = h4 & 0x03ffffffUL h0 = h0 + c * 5UL c = h0 >> 26 h0 = h0 & 0x03ffffffUL h1 = h1 + c // Compute h + 5 - 2^130 let mut g0 = h0 + 5UL c = g0 >> 26 g0 = g0 & 0x03ffffffUL let mut g1 = h1 + c c = g1 >> 26 g1 = g1 & 0x03ffffffUL let mut g2 = h2 + c c = g2 >> 26 g2 = g2 & 0x03ffffffUL let mut g3 = h3 + c c = g3 >> 26 g3 = g3 & 0x03ffffffUL let g4 = h4 + c - (1UL << 26) // Select h if h < p else g (constant-time) let mask = (g4 >> 63) - 1UL // all 1s if g4 >= 0 (i.e. h >= p), 0 otherwise g0 = g0 & mask g1 = g1 & mask g2 = g2 & mask g3 = g3 & mask let g4_masked = g4 & mask let nmask = mask.lnot() h0 = (h0 & nmask) | g0 h1 = (h1 & nmask) | g1 h2 = (h2 & nmask) | g2 h3 = (h3 & nmask) | g3 h4 = (h4 & nmask) | g4_masked // Pack 5 x 26-bit limbs into 4 x 32-bit words let f0 = (h0 | (h1 << 26)) & 0xffffffffUL let f1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffffUL let f2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffffUL let f3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffffUL // Add s (second 16 bytes of key) mod 2^128 let mut acc = f0 + read_u32_le(key, 16).to_uint64() let w0 = (acc & 0xffffffffUL).to_uint() acc = f1 + read_u32_le(key, 20).to_uint64() + (acc >> 32) let w1 = (acc & 0xffffffffUL).to_uint() acc = f2 + read_u32_le(key, 24).to_uint64() + (acc >> 32) let w2 = (acc & 0xffffffffUL).to_uint() acc = f3 + read_u32_le(key, 28).to_uint64() + (acc >> 32) let w3 = (acc & 0xffffffffUL).to_uint() let out = FixedArray::make(16, b'\x00') write_u32_le(out, 0, w0) write_u32_le(out, 4, w1) write_u32_le(out, 8, w2) write_u32_le(out, 12, w3) Bytes::from_array(out) } ///| fn build_aead_mac_data(aad : Bytes, ciphertext : Bytes) -> Bytes { let pad16 = fn(n : Int32) -> Int32 { let rem = n % 16 if rem == 0 { 0 } else { 16 - rem } } let aad_pad = pad16(aad.length()) let ct_pad = pad16(ciphertext.length()) let total = aad.length() + aad_pad + ciphertext.length() + ct_pad + 16 let buf = FixedArray::make(total, b'\x00') let mut pos = 0 for i = 0; i < aad.length(); i = i + 1 { buf[pos] = aad[i] pos += 1 } pos += aad_pad for i = 0; i < ciphertext.length(); i = i + 1 { buf[pos] = ciphertext[i] pos += 1 } pos += ct_pad let aad_len = aad.length().to_uint64() let ct_len = ciphertext.length().to_uint64() for i = 0; i < 8; i = i + 1 { buf[pos + i] = ((aad_len >> (i * 8)) & 0xFFUL).to_byte() buf[pos + 8 + i] = ((ct_len >> (i * 8)) & 0xFFUL).to_byte() } Bytes::from_array(buf) } ///| /// AEAD_CHACHA20_POLY1305 encryption (RFC 8439 Section 2.8). /// Returns `ciphertext || 16-byte tag`. pub fn aead_chacha20_poly1305_encrypt( key : Bytes, nonce : Bytes, aad : Bytes, plaintext : Bytes, ) -> Bytes raise CryptoError { let otk_block = chacha20_block(key, 0U, nonce) let otk = FixedArray::make(32, b'\x00') for i = 0; i < 32; i = i + 1 { otk[i] = otk_block[i] } let ciphertext = chacha20_xor(key, 1U, nonce, plaintext) let mac_data = build_aead_mac_data(aad, ciphertext) let tag = poly1305_mac(Bytes::from_array(otk), mac_data) let out = FixedArray::make(ciphertext.length() + 16, b'\x00') for i = 0; i < ciphertext.length(); i = i + 1 { out[i] = ciphertext[i] } for i = 0; i < 16; i = i + 1 { out[ciphertext.length() + i] = tag[i] } Bytes::from_array(out) } ///| /// AEAD_CHACHA20_POLY1305 decryption (RFC 8439 Section 2.8). /// Expects `ciphertext_and_tag` to be `ciphertext || 16-byte tag`. pub fn aead_chacha20_poly1305_decrypt( key : Bytes, nonce : Bytes, aad : Bytes, ciphertext_and_tag : Bytes, ) -> Bytes raise CryptoError { if ciphertext_and_tag.length() < 16 { raise AuthenticationFailed } let ct_len = ciphertext_and_tag.length() - 16 let ct_arr = FixedArray::make(ct_len, b'\x00') for i = 0; i < ct_len; i = i + 1 { ct_arr[i] = ciphertext_and_tag[i] } let ciphertext = Bytes::from_array(ct_arr) let tag_arr = FixedArray::make(16, b'\x00') for i = 0; i < 16; i = i + 1 { tag_arr[i] = ciphertext_and_tag[ct_len + i] } let expected_tag = Bytes::from_array(tag_arr) let otk_block = chacha20_block(key, 0U, nonce) let otk = FixedArray::make(32, b'\x00') for i = 0; i < 32; i = i + 1 { otk[i] = otk_block[i] } let mac_data = build_aead_mac_data(aad, ciphertext) let computed_tag = poly1305_mac(Bytes::from_array(otk), mac_data) if !ct_eq(computed_tag, expected_tag) { raise AuthenticationFailed } chacha20_xor(key, 1U, nonce, ciphertext) }