feat: bootstrap moon-i2p core protocol foundation
check / check (ubuntu-latest) (push) Failing after 30s
check / check (macos-latest) (push) Failing after 33s
check / check (windows-latest) (push) Failing after 32s

This commit is contained in:
Antigravity committed 2026-11-27 15:37:42 +00:00
commit e527b84bc3
47 files changed
+5350

No files matched your search

+384
View File
@@ -0,0 +1,384 @@
///|
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)
}
+119
View File
@@ -0,0 +1,119 @@
///|
test "sha256 NIST standard test vectors" {
assert_eq(
@encoding.hex_encode(@crypto.sha256(b"")),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
)
assert_eq(
@encoding.hex_encode(@crypto.sha256(b"abc")),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
)
assert_eq(
@encoding.hex_encode(
@crypto.sha256(
b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
),
),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
)
}
///|
test "hmac_sha256 RFC 4231 test cases 1 and 2" {
// Case 1
let key1 = Bytes::make(20, b'\x0b')
let data1 = b"Hi There"
assert_eq(
@encoding.hex_encode(@crypto.hmac_sha256(key1, data1)),
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
)
// Case 2
let key2 = b"Jefe"
let data2 = b"what do ya want for nothing?"
assert_eq(
@encoding.hex_encode(@crypto.hmac_sha256(key2, data2)),
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
)
}
///|
test "hkdf_sha256 RFC 5869 test case 1" {
let ikm = @encoding.hex_decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b")
let salt = @encoding.hex_decode("000102030405060708090a0b0c")
let info = @encoding.hex_decode("f0f1f2f3f4f5f6f7f8f9")
let prk = @crypto.hkdf_extract(salt, ikm)
assert_eq(
@encoding.hex_encode(prk),
"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5",
)
let okm = @crypto.hkdf_expand(prk, info, 42)
assert_eq(
@encoding.hex_encode(okm),
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865",
)
}
///|
test "chacha20_poly1305 AEAD RFC 8439 Section 2.8.2" {
let key = @encoding.hex_decode(
"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
)
let nonce = @encoding.hex_decode("070000004041424344454647")
let aad = @encoding.hex_decode("50515253c0c1c2c3c4c5c6c7")
let pt = b"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_ct_and_tag = @encoding.hex_decode(
"d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd0600691",
)
let ct_and_tag = @crypto.aead_chacha20_poly1305_encrypt(key, nonce, aad, pt)
assert_eq(ct_and_tag, expected_ct_and_tag)
let opened = @crypto.aead_chacha20_poly1305_decrypt(
key, nonce, aad, ct_and_tag,
)
assert_eq(opened, pt)
}
///|
test "x25519 RFC 7748 Section 5.2 and 6.1 test vectors" {
// Section 5.2 scalar multiplication
let scalar = @encoding.hex_decode(
"a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4",
)
let u_coord = @encoding.hex_decode(
"e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c",
)
let expected = "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552"
assert_eq(@encoding.hex_encode(@crypto.x25519(scalar, u_coord)), expected)
// Section 6.1 Diffie-Hellman key exchange
let alice_priv = @encoding.hex_decode(
"77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
)
let alice_pub = @crypto.x25519_public_key(alice_priv)
assert_eq(
@encoding.hex_encode(alice_pub),
"8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a",
)
let bob_priv = @encoding.hex_decode(
"5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb",
)
let bob_pub = @crypto.x25519_public_key(bob_priv)
assert_eq(
@encoding.hex_encode(bob_pub),
"de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f",
)
let shared_a = @crypto.x25519(alice_priv, bob_pub)
let shared_b = @crypto.x25519(bob_priv, alice_pub)
assert_eq(shared_a, shared_b)
assert_eq(
@encoding.hex_encode(shared_a),
"4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742",
)
}
///|
test "siphash_2_4 official test vector" {
// Key = 00 01 ... 0f, msg = 00 01 ... 0e (15 bytes) -> 0xa129ca6149be45e5
let key = @encoding.hex_decode("000102030405060708090a0b0c0d0e0f")
let msg = @encoding.hex_decode("000102030405060708090a0b0c0d0e")
assert_eq(@crypto.siphash_2_4(key, msg), 0xa129ca6149be45e5UL)
}
+80
View File
@@ -0,0 +1,80 @@
///|
/// Computes HMAC-SHA256 (RFC 2104 / RFC 4231).
pub fn hmac_sha256(key : Bytes, data : Bytes) -> Bytes {
let block_key = FixedArray::make(64, b'\x00')
let effective_key = if key.length() > 64 { sha256(key) } else { key }
for i = 0; i < effective_key.length(); i = i + 1 {
block_key[i] = effective_key[i]
}
let ipad = FixedArray::make(64, b'\x00')
let opad = FixedArray::make(64, b'\x00')
for i = 0; i < 64; i = i + 1 {
ipad[i] = (block_key[i].to_int() ^ 0x36).to_byte()
opad[i] = (block_key[i].to_int() ^ 0x5c).to_byte()
}
let inner = Sha256::new()
inner.update(Bytes::from_array(ipad))
inner.update(data)
let inner_digest = inner.finalize()
let outer = Sha256::new()
outer.update(Bytes::from_array(opad))
outer.update(inner_digest)
outer.finalize()
}
///|
/// HKDF-Extract (RFC 5869) using SHA-256.
pub fn hkdf_extract(salt : Bytes, ikm : Bytes) -> Bytes {
let actual_salt = if salt.length() == 0 {
Bytes::make(32, b'\x00')
} else {
salt
}
hmac_sha256(actual_salt, ikm)
}
///|
/// HKDF-Expand (RFC 5869) using SHA-256.
pub fn hkdf_expand(
prk : Bytes,
info : Bytes,
length : Int32,
) -> Bytes raise CryptoError {
if length < 0 || length > 255 * 32 {
raise InvalidLength("HKDF-Expand output length out of range: \{length}")
}
if length == 0 {
return b""
}
let n = (length + 31) / 32
let out : Array[Byte] = Array(capacity=length)
let mut prev : Bytes = b""
for i = 1; i <= n; i = i + 1 {
let msg : Array[Byte] = Array(capacity=prev.length() + info.length() + 1)
for j = 0; j < prev.length(); j = j + 1 {
msg.push(prev[j])
}
for j = 0; j < info.length(); j = j + 1 {
msg.push(info[j])
}
msg.push(i.to_byte())
prev = hmac_sha256(prk, Bytes::from_array(msg))
for j = 0; j < prev.length() && out.length() < length; j = j + 1 {
out.push(prev[j])
}
}
Bytes::from_array(out)
}
///|
/// Full HKDF-SHA256 (Extract + Expand, RFC 5869).
pub fn hkdf(
salt : Bytes,
ikm : Bytes,
info : Bytes,
length : Int32,
) -> Bytes raise CryptoError {
let prk = hkdf_extract(salt, ikm)
hkdf_expand(prk, info, length)
}
+3
View File
@@ -0,0 +1,3 @@
import {
"experiments/moon_i2p/encoding",
} for "test"
+59
View File
@@ -0,0 +1,59 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/moon_i2p/crypto"
import {
"moonbitlang/core/debug",
}
// Values
pub fn aead_chacha20_poly1305_decrypt(Bytes, Bytes, Bytes, Bytes) -> Bytes raise CryptoError
pub fn aead_chacha20_poly1305_encrypt(Bytes, Bytes, Bytes, Bytes) -> Bytes raise CryptoError
pub fn chacha20_block(Bytes, UInt32, Bytes) -> Bytes raise CryptoError
pub fn chacha20_xor(Bytes, UInt32, Bytes, Bytes) -> Bytes raise CryptoError
pub fn ct_eq(Bytes, Bytes) -> Bool
pub fn hkdf(Bytes, Bytes, Bytes, Int32) -> Bytes raise CryptoError
pub fn hkdf_expand(Bytes, Bytes, Int32) -> Bytes raise CryptoError
pub fn hkdf_extract(Bytes, Bytes) -> Bytes
pub fn hmac_sha256(Bytes, Bytes) -> Bytes
pub fn poly1305_mac(Bytes, Bytes) -> Bytes raise CryptoError
pub fn sha256(Bytes) -> Bytes
pub fn siphash_2_4(Bytes, Bytes) -> UInt64 raise CryptoError
pub fn x25519(Bytes, Bytes) -> Bytes raise CryptoError
pub fn x25519_public_key(Bytes) -> Bytes raise CryptoError
// Errors
#derive(Eq, @debug.Debug)
pub suberror CryptoError {
InvalidKeyLength(String)
InvalidNonceLength(String)
InvalidLength(String)
AuthenticationFailed
}
// Types and methods
pub struct Sha256 {
state : FixedArray[UInt32]
block : FixedArray[Byte]
mut block_len : Int32
mut total_len : UInt64
}
pub fn Sha256::finalize(Self) -> Bytes
pub fn Sha256::new() -> Self
pub fn Sha256::update(Self, Bytes) -> Unit
// Type aliases
// Traits
+166
View File
@@ -0,0 +1,166 @@
///|
/// Cryptographic errors raised by I2P crypto primitives.
#derive(Eq, Debug)
pub suberror CryptoError {
InvalidKeyLength(String)
InvalidNonceLength(String)
InvalidLength(String)
AuthenticationFailed
}
///|
/// Constant-time equality comparison for two byte slices.
pub fn ct_eq(a : Bytes, b : Bytes) -> Bool {
if a.length() != b.length() {
return false
}
let mut diff = 0
for i = 0; i < a.length(); i = i + 1 {
diff = diff | (a[i].to_int() ^ b[i].to_int())
}
diff == 0
}
///|
let sha256_k : FixedArray[UInt32] = [
0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U, 0x923f82a4U,
0xab1c5ed5U, 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U, 0x72be5d74U, 0x80deb1feU,
0x9bdc06a7U, 0xc19bf174U, 0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU, 0x2de92c6fU,
0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU, 0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U,
0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U, 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU,
0x53380d13U, 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, 0xa2bfe8a1U, 0xa81a664bU,
0xc24b8b70U, 0xc76c51a3U, 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U, 0x19a4c116U,
0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U,
0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U, 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U,
0xc67178f2U,
]
///|
fn rotr32(x : UInt32, n : Int32) -> UInt32 {
(x >> n) | (x << (32 - n))
}
///|
/// Incremental SHA-256 hasher (FIPS 180-4).
pub struct Sha256 {
state : FixedArray[UInt32]
block : FixedArray[Byte]
mut block_len : Int32
mut total_len : UInt64
}
///|
pub fn Sha256::new() -> Sha256 {
{
state: [
0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, 0x510e527fU, 0x9b05688cU,
0x1f83d9abU, 0x5be0cd19U,
],
block: FixedArray::make(64, b'\x00'),
block_len: 0,
total_len: 0UL,
}
}
///|
fn Sha256::compress(self : Sha256) -> Unit {
let w = FixedArray::make(64, 0U)
for i = 0; i < 16; i = i + 1 {
let j = i * 4
w[i] = (self.block[j].to_uint() << 24) |
(self.block[j + 1].to_uint() << 16) |
(self.block[j + 2].to_uint() << 8) |
self.block[j + 3].to_uint()
}
for i = 16; i < 64; i = i + 1 {
let s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >> 3)
let s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >> 10)
w[i] = w[i - 16] + s0 + w[i - 7] + s1
}
let mut a = self.state[0]
let mut b = self.state[1]
let mut c = self.state[2]
let mut d = self.state[3]
let mut e = self.state[4]
let mut f = self.state[5]
let mut g = self.state[6]
let mut h = self.state[7]
for i = 0; i < 64; i = i + 1 {
let s1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25)
let ch = (e & f) ^ (e.lnot() & g)
let temp1 = h + s1 + ch + sha256_k[i] + w[i]
let s0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22)
let maj = (a & b) ^ (a & c) ^ (b & c)
let temp2 = s0 + maj
h = g
g = f
f = e
e = d + temp1
d = c
c = b
b = a
a = temp1 + temp2
}
self.state[0] = self.state[0] + a
self.state[1] = self.state[1] + b
self.state[2] = self.state[2] + c
self.state[3] = self.state[3] + d
self.state[4] = self.state[4] + e
self.state[5] = self.state[5] + f
self.state[6] = self.state[6] + g
self.state[7] = self.state[7] + h
}
///|
pub fn Sha256::update(self : Sha256, data : Bytes) -> Unit {
let len = data.length()
self.total_len = self.total_len + len.to_uint64()
for i = 0; i < len; i = i + 1 {
self.block[self.block_len] = data[i]
self.block_len += 1
if self.block_len == 64 {
self.compress()
self.block_len = 0
}
}
}
///|
pub fn Sha256::finalize(self : Sha256) -> Bytes {
let bit_len = self.total_len * 8UL
self.block[self.block_len] = b'\x80'
self.block_len += 1
if self.block_len > 56 {
while self.block_len < 64 {
self.block[self.block_len] = b'\x00'
self.block_len += 1
}
self.compress()
self.block_len = 0
}
while self.block_len < 56 {
self.block[self.block_len] = b'\x00'
self.block_len += 1
}
for i = 0; i < 8; i = i + 1 {
self.block[56 + i] = ((bit_len >> (56 - i * 8)) & 0xFFUL).to_byte()
}
self.compress()
let out = FixedArray::make(32, b'\x00')
for i = 0; i < 8; i = i + 1 {
let v = self.state[i]
out[i * 4] = ((v >> 24) & 0xFFU).to_byte()
out[i * 4 + 1] = ((v >> 16) & 0xFFU).to_byte()
out[i * 4 + 2] = ((v >> 8) & 0xFFU).to_byte()
out[i * 4 + 3] = (v & 0xFFU).to_byte()
}
Bytes::from_array(out)
}
///|
/// Computes the 32-byte SHA-256 digest of `data`.
pub fn sha256(data : Bytes) -> Bytes {
let h = Sha256::new()
h.update(data)
h.finalize()
}
+80
View File
@@ -0,0 +1,80 @@
///|
fn rotl64(x : UInt64, n : Int32) -> UInt64 {
(x << n) | (x >> (64 - n))
}
///|
fn read_u64_le(data : Bytes, offset : Int32) -> UInt64 {
data[offset].to_uint64() |
(data[offset + 1].to_uint64() << 8) |
(data[offset + 2].to_uint64() << 16) |
(data[offset + 3].to_uint64() << 24) |
(data[offset + 4].to_uint64() << 32) |
(data[offset + 5].to_uint64() << 40) |
(data[offset + 6].to_uint64() << 48) |
(data[offset + 7].to_uint64() << 56)
}
///|
/// Computes SipHash-2-4 (used by NTCP2 for frame length obfuscation).
/// `key` must be 16 bytes.
pub fn siphash_2_4(key : Bytes, data : Bytes) -> UInt64 raise CryptoError {
if key.length() != 16 {
raise InvalidKeyLength(
"SipHash-2-4 requires a 16-byte key, got \{key.length()}",
)
}
let k0 = read_u64_le(key, 0)
let k1 = read_u64_le(key, 8)
let mut v0 = 0x736f6d6570736575UL ^ k0
let mut v1 = 0x646f72616e646f6dUL ^ k1
let mut v2 = 0x6c7967656e657261UL ^ k0
let mut v3 = 0x7465646279746573UL ^ k1
let sipround = fn() {
v0 = v0 + v1
v1 = rotl64(v1, 13)
v1 = v1 ^ v0
v0 = rotl64(v0, 32)
v2 = v2 + v3
v3 = rotl64(v3, 16)
v3 = v3 ^ v2
v0 = v0 + v3
v3 = rotl64(v3, 21)
v3 = v3 ^ v0
v2 = v2 + v1
v1 = rotl64(v1, 17)
v1 = v1 ^ v2
v2 = rotl64(v2, 32)
}
let len = data.length()
let full_blocks = len / 8
for i = 0; i < full_blocks; i = i + 1 {
let m = read_u64_le(data, i * 8)
v3 = v3 ^ m
sipround()
sipround()
v0 = v0 ^ m
}
let mut b = (len.to_uint64() & 0xFFUL) << 56
let rem = len % 8
let base = full_blocks * 8
for i = 0; i < rem; i = i + 1 {
b = b | (data[base + i].to_uint64() << (i * 8))
}
v3 = v3 ^ b
sipround()
sipround()
v0 = v0 ^ b
v2 = v2 ^ 0xFFUL
sipround()
sipround()
sipround()
sipround()
v0 ^ v1 ^ v2 ^ v3
}
+214
View File
@@ -0,0 +1,214 @@
///|
/// Pure-MoonBit RFC 7748 X25519 Elliptic Curve Diffie-Hellman on Curve25519.
/// Field elements mod 2^255 - 19 are represented as 16 signed 64-bit limbs (16 bits per limb).
///|
fn gf_zero() -> FixedArray[Int64] {
FixedArray::make(16, 0L)
}
///|
fn gf_one() -> FixedArray[Int64] {
let r = FixedArray::make(16, 0L)
r[0] = 1L
r
}
///|
fn gf_copy(src : FixedArray[Int64]) -> FixedArray[Int64] {
let dst = FixedArray::make(16, 0L)
for i = 0; i < 16; i = i + 1 {
dst[i] = src[i]
}
dst
}
///|
fn gf_carry(o : FixedArray[Int64]) -> Unit {
for i = 0; i < 16; i = i + 1 {
o[i] = o[i] + 65536L
let c = o[i] >> 16
if i < 15 {
o[i + 1] = o[i + 1] + c - 1L
} else {
o[0] = o[0] + (c - 1L) * 38L
}
o[i] = o[i] - (c << 16)
}
}
///|
fn gf_cswap(p : FixedArray[Int64], q : FixedArray[Int64], b : Int64) -> Unit {
let mask = -b
for i = 0; i < 16; i = i + 1 {
let t = mask & (p[i] ^ q[i])
p[i] = p[i] ^ t
q[i] = q[i] ^ t
}
}
///|
fn gf_unpack(n : Bytes) -> FixedArray[Int64] {
let o = FixedArray::make(16, 0L)
for i = 0; i < 16; i = i + 1 {
o[i] = n[2 * i].to_int64() + (n[2 * i + 1].to_int64() << 8)
}
o[15] = o[15] & 0x7fffL
o
}
///|
fn gf_pack(n : FixedArray[Int64]) -> Bytes {
let t = gf_copy(n)
let m = FixedArray::make(16, 0L)
gf_carry(t)
gf_carry(t)
gf_carry(t)
for _j = 0; _j < 2; _j = _j + 1 {
m[0] = t[0] - 0xffedL
for i = 1; i < 15; i = i + 1 {
m[i] = t[i] - 0xffffL - ((m[i - 1] >> 16) & 1L)
m[i - 1] = m[i - 1] & 0xffffL
}
m[15] = t[15] - 0x7fffL - ((m[14] >> 16) & 1L)
let b = (m[15] >> 16) & 1L
m[14] = m[14] & 0xffffL
gf_cswap(t, m, 1L - b)
}
let out = FixedArray::make(32, b'\x00')
for i = 0; i < 16; i = i + 1 {
out[2 * i] = (t[i] & 0xffL).to_byte()
out[2 * i + 1] = ((t[i] >> 8) & 0xffL).to_byte()
}
Bytes::from_array(out)
}
///|
fn gf_add(a : FixedArray[Int64], b : FixedArray[Int64]) -> FixedArray[Int64] {
let o = FixedArray::make(16, 0L)
for i = 0; i < 16; i = i + 1 {
o[i] = a[i] + b[i]
}
o
}
///|
fn gf_sub(a : FixedArray[Int64], b : FixedArray[Int64]) -> FixedArray[Int64] {
let o = FixedArray::make(16, 0L)
for i = 0; i < 16; i = i + 1 {
o[i] = a[i] - b[i]
}
o
}
///|
fn gf_mul(a : FixedArray[Int64], b : FixedArray[Int64]) -> FixedArray[Int64] {
let t = FixedArray::make(31, 0L)
for i = 0; i < 16; i = i + 1 {
for j = 0; j < 16; j = j + 1 {
t[i + j] = t[i + j] + a[i] * b[j]
}
}
for i = 0; i < 15; i = i + 1 {
t[i] = t[i] + 38L * t[i + 16]
}
let o = FixedArray::make(16, 0L)
for i = 0; i < 16; i = i + 1 {
o[i] = t[i]
}
gf_carry(o)
gf_carry(o)
o
}
///|
fn gf_sq(a : FixedArray[Int64]) -> FixedArray[Int64] {
gf_mul(a, a)
}
///|
fn gf_inv(a : FixedArray[Int64]) -> FixedArray[Int64] {
let mut c = gf_copy(a)
for i = 253; i >= 0; i = i - 1 {
c = gf_sq(c)
if i != 2 && i != 4 {
c = gf_mul(c, a)
}
}
c
}
///|
/// Computes the X25519 scalar multiplication `scalar * u_coord` (RFC 7748 Section 5).
/// Both `scalar` and `u_coord` must be 32 bytes.
pub fn x25519(scalar : Bytes, u_coord : Bytes) -> Bytes raise CryptoError {
if scalar.length() != 32 {
raise InvalidKeyLength(
"X25519 scalar must be 32 bytes, got \{scalar.length()}",
)
}
if u_coord.length() != 32 {
raise InvalidKeyLength(
"X25519 u-coordinate must be 32 bytes, got \{u_coord.length()}",
)
}
let z = FixedArray::make(32, 0)
for i = 0; i < 32; i = i + 1 {
z[i] = scalar[i].to_int()
}
// Clamp scalar per RFC 7748
z[0] = z[0] & 248
z[31] = (z[31] & 127) | 64
let x = gf_unpack(u_coord)
let mut a = gf_one()
let mut b = gf_copy(x)
let mut c = gf_zero()
let mut d = gf_one()
let a24 = gf_zero()
a24[0] = 0xdb41L
a24[1] = 1L
for i = 254; i >= 0; i = i - 1 {
let r = ((z[i >> 3] >> (i & 7)) & 1).to_int64()
gf_cswap(a, b, r)
gf_cswap(c, d, r)
let e = gf_add(a, c)
let a1 = gf_sub(a, c)
let c1 = gf_add(b, d)
let b1 = gf_sub(b, d)
let d1 = gf_sq(e)
let f = gf_sq(a1)
let a2 = gf_mul(c1, a1)
let c2 = gf_mul(b1, e)
let e2 = gf_add(a2, c2)
let a3 = gf_sub(a2, c2)
let b2 = gf_sq(a3)
let c3 = gf_sub(d1, f)
let a4 = gf_mul(c3, a24)
let a5 = gf_add(a4, d1)
let c4 = gf_mul(c3, a5)
let a6 = gf_mul(d1, f)
let d2 = gf_mul(b2, x)
let b3 = gf_sq(e2)
a = a6
b = b3
c = c4
d = d2
gf_cswap(a, b, r)
gf_cswap(c, d, r)
}
let inv_c = gf_inv(c)
let res = gf_mul(a, inv_c)
gf_pack(res)
}
///|
/// Computes the 32-byte X25519 public key from a 32-byte private scalar.
pub fn x25519_public_key(private_key : Bytes) -> Bytes raise CryptoError {
let basepoint = FixedArray::make(32, b'\x00')
basepoint[0] = b'\x09'
x25519(private_key, Bytes::from_array(basepoint))
}