From dff69dfac68c18aa4d3a58e060dbeec0d3d5f9d0 Mon Sep 17 00:00:00 2001 From: nandi <78769380+codegod100@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:21:57 +0000 Subject: [PATCH] feat: add pure-MoonBit SHA-512, Ed25519, AES-256-CBC, and signed RouterInfo/LeaseSet2 --- common/common_test.mbt | 93 +++++++++ common/pkg.generated.mbti | 10 + common/router_info.mbt | 121 ++++++++++- common/types.mbt | 1 + crypto/aes.mbt | 415 ++++++++++++++++++++++++++++++++++++++ crypto/crypto_test.mbt | 121 +++++++++++ crypto/ed25519.mbt | 373 ++++++++++++++++++++++++++++++++++ crypto/pkg.generated.mbti | 27 +++ crypto/sha512.mbt | 173 ++++++++++++++++ 9 files changed, 1330 insertions(+), 4 deletions(-) create mode 100644 crypto/aes.mbt create mode 100644 crypto/ed25519.mbt create mode 100644 crypto/sha512.mbt diff --git a/common/common_test.mbt b/common/common_test.mbt index 45c7083..e0374ef 100644 --- a/common/common_test.mbt +++ b/common/common_test.mbt @@ -107,3 +107,96 @@ test "LeaseSet2 encode and decode round-trip" { let decoded = @common.LeaseSet2::decode(@encoding.Reader::new(w.to_bytes())) assert_eq(decoded, ls2) } + +///| +test "RouterInfo Ed25519 sign, encode/decode round-trip, and verify" { + let ed_seed = @encoding.hex_decode( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + ) + let ed_pub = @crypto.ed25519_public_key(ed_seed) + let x_priv = @encoding.hex_decode( + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + ) + let x_pub = @crypto.x25519_public_key(x_priv) + let ri_id = @common.RouterIdentity::new_x25519_ed25519(x_pub, ed_pub) + let addr_opts = @common.Mapping::from_entries([ + ("host", "127.0.0.1"), + ("port", "14567"), + ("v", "2"), + ]) + let ri : @common.RouterInfo = { + identity: ri_id, + published: 1700000000000UL, + addresses: [@common.RouterAddress::new(b'\x03', "NTCP2", addr_opts)], + options: @common.Mapping::from_entries([ + ("caps", "LR"), + ("netId", "2"), + ("router.version", "0.9.64"), + ]), + signature: b"", + } + let signed = ri.sign_ed25519(ed_seed) + assert_eq(signed.signature.length(), 64) + assert_eq(signed.verify_signature(), true) + + // Wire round-trip preserves valid signature + let raw = signed.to_bytes() + let decoded = @common.RouterInfo::decode(@encoding.Reader::new(raw)) + assert_eq(decoded, signed) + assert_eq(decoded.verify_signature(), true) + + // Tampering with published timestamp invalidates signature + let tampered : @common.RouterInfo = { + identity: decoded.identity, + published: decoded.published + 1UL, + addresses: decoded.addresses, + options: decoded.options, + signature: decoded.signature, + } + assert_eq(tampered.verify_signature(), false) +} + +///| +test "LeaseSet2 Ed25519 sign, encode/decode round-trip, and verify" { + let ed_seed = @encoding.hex_decode( + "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", + ) + let ed_pub = @crypto.ed25519_public_key(ed_seed) + let x_priv = @encoding.hex_decode( + "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb", + ) + let x_pub = @crypto.x25519_public_key(x_priv) + let dest = @common.Destination::new_x25519_ed25519(x_pub, ed_pub) + let gw = @common.Hash::sha256(b"gateway-router") + let ls2 : @common.LeaseSet2 = { + destination: dest, + published_sec: 1700000000U, + expires_offset: 600U, + flags: 0U, + options: @common.Mapping::new(), + encryption_keys: [{ key_type: X25519, key_data: x_pub, }], + leases: [{ tunnel_gw: gw, tunnel_id: 777U, end_date_sec: 1700000600U, }], + signature: b"", + } + let signed = ls2.sign_ed25519(ed_seed) + assert_eq(signed.signature.length(), 64) + assert_eq(signed.verify_signature(), true) + assert_eq(signed.signing_bytes()[0], b'\x03') + + let raw = signed.to_bytes() + let decoded = @common.LeaseSet2::decode(@encoding.Reader::new(raw)) + assert_eq(decoded, signed) + assert_eq(decoded.verify_signature(), true) + + let tampered : @common.LeaseSet2 = { + destination: decoded.destination, + published_sec: decoded.published_sec + 1U, + expires_offset: decoded.expires_offset, + flags: decoded.flags, + options: decoded.options, + encryption_keys: decoded.encryption_keys, + leases: decoded.leases, + signature: decoded.signature, + } + assert_eq(tampered.verify_signature(), false) +} diff --git a/common/pkg.generated.mbti b/common/pkg.generated.mbti index c488395..41e3199 100644 --- a/common/pkg.generated.mbti +++ b/common/pkg.generated.mbti @@ -2,6 +2,7 @@ package "experiments/moon_i2p/common" import { + "experiments/moon_i2p/crypto", "experiments/moon_i2p/encoding", "moonbitlang/core/debug", } @@ -12,6 +13,7 @@ import { #derive(Eq, @debug.Debug) pub suberror CommonError { Encoding(@encoding.EncodingError) + Crypto(@crypto.CryptoError) InvalidLength(String) InvalidFormat(String) } @@ -126,6 +128,11 @@ pub(all) struct LeaseSet2 { } pub fn LeaseSet2::decode(@encoding.Reader) -> Self raise CommonError pub fn LeaseSet2::encode(Self, @encoding.Writer) -> Unit raise CommonError +pub fn LeaseSet2::sign_ed25519(Self, Bytes) -> Self raise CommonError +pub fn LeaseSet2::signing_bytes(Self) -> Bytes raise CommonError +pub fn LeaseSet2::to_bytes(Self) -> Bytes raise CommonError +pub fn LeaseSet2::unsigned_bytes(Self) -> Bytes raise CommonError +pub fn LeaseSet2::verify_signature(Self) -> Bool #derive(Eq, @debug.Debug) pub(all) struct LeaseSet2EncryptionKey { @@ -181,7 +188,10 @@ pub(all) struct RouterInfo { } pub fn RouterInfo::decode(@encoding.Reader) -> Self raise CommonError pub fn RouterInfo::encode(Self, @encoding.Writer) -> Unit raise CommonError +pub fn RouterInfo::sign_ed25519(Self, Bytes) -> Self raise CommonError +pub fn RouterInfo::to_bytes(Self) -> Bytes raise CommonError pub fn RouterInfo::unsigned_bytes(Self) -> Bytes raise CommonError +pub fn RouterInfo::verify_signature(Self) -> Bool #derive(Eq, @debug.Debug) pub struct SessionKey { diff --git a/common/router_info.mbt b/common/router_info.mbt index f072998..208ceb0 100644 --- a/common/router_info.mbt +++ b/common/router_info.mbt @@ -78,6 +78,52 @@ pub fn RouterInfo::encode( w.write_bytes(self.signature) } +///| +pub fn RouterInfo::to_bytes(self : RouterInfo) -> Bytes raise CommonError { + let w = @encoding.Writer::new(capacity=600) + self.encode(w) + w.to_bytes() +} + +///| +/// Signs the `RouterInfo` using an Ed25519 32-byte private `seed` and returns +/// a new `RouterInfo` with `signature` populated. +pub fn RouterInfo::sign_ed25519( + self : RouterInfo, + seed : Bytes, +) -> RouterInfo raise CommonError { + if self.identity.signing_type() != EdDsaSha512Ed25519 { + raise InvalidFormat( + "RouterInfo identity signing type must be EdDsaSha512Ed25519", + ) + } + let body = self.unsigned_bytes() + let signature = @crypto.ed25519_sign(seed, body) catch { + e => raise Crypto(e) + } + { + identity: self.identity, + published: self.published, + addresses: self.addresses, + options: self.options, + signature, + } +} + +///| +/// Verifies the `RouterInfo` Ed25519 signature against `self.identity.signing_public_key()`. +pub fn RouterInfo::verify_signature(self : RouterInfo) -> Bool { + if self.identity.signing_type() != EdDsaSha512Ed25519 { + return false + } + let body = self.unsigned_bytes() catch { _ => return false } + @crypto.ed25519_verify( + self.identity.signing_public_key(), + body, + self.signature, + ) +} + ///| pub fn RouterInfo::decode(r : @encoding.Reader) -> RouterInfo raise CommonError { let identity = RouterIdentity::decode(r) @@ -175,10 +221,9 @@ pub(all) struct LeaseSet2 { } ///| -pub fn LeaseSet2::encode( - self : LeaseSet2, - w : @encoding.Writer, -) -> Unit raise CommonError { +/// Encodes the unsigned body of LeaseSet2 (everything before `signature`). +pub fn LeaseSet2::unsigned_bytes(self : LeaseSet2) -> Bytes raise CommonError { + let w = @encoding.Writer::new(capacity=512) self.destination.encode(w) w.write_u32_be(self.published_sec) w.write_u16_be(self.expires_offset) @@ -194,9 +239,77 @@ pub fn LeaseSet2::encode( for lease in self.leases { lease.encode(w) } + w.to_bytes() +} + +///| +/// Returns the exact bytes covered by the LeaseSet2 signature: +/// single-byte DatabaseStore type `0x03` prepended to `unsigned_bytes()` (Proposal 123). +pub fn LeaseSet2::signing_bytes(self : LeaseSet2) -> Bytes raise CommonError { + let body = self.unsigned_bytes() + let w = @encoding.Writer::new(capacity=1 + body.length()) + w.write_u8(b'\x03') + w.write_bytes(body) + w.to_bytes() +} + +///| +pub fn LeaseSet2::encode( + self : LeaseSet2, + w : @encoding.Writer, +) -> Unit raise CommonError { + w.write_bytes(self.unsigned_bytes()) w.write_bytes(self.signature) } +///| +pub fn LeaseSet2::to_bytes(self : LeaseSet2) -> Bytes raise CommonError { + let w = @encoding.Writer::new(capacity=600) + self.encode(w) + w.to_bytes() +} + +///| +/// Signs the `LeaseSet2` using an Ed25519 32-byte private `seed` (over `0x03 || unsigned_bytes`). +pub fn LeaseSet2::sign_ed25519( + self : LeaseSet2, + seed : Bytes, +) -> LeaseSet2 raise CommonError { + if self.destination.inner.signing_type() != EdDsaSha512Ed25519 { + raise InvalidFormat( + "LeaseSet2 destination signing type must be EdDsaSha512Ed25519", + ) + } + let to_sign = self.signing_bytes() + let signature = @crypto.ed25519_sign(seed, to_sign) catch { + e => raise Crypto(e) + } + { + destination: self.destination, + published_sec: self.published_sec, + expires_offset: self.expires_offset, + flags: self.flags, + options: self.options, + encryption_keys: self.encryption_keys, + leases: self.leases, + signature, + } +} + +///| +/// Verifies the `LeaseSet2` Ed25519 signature against `self.destination.inner.signing_public_key()`. +pub fn LeaseSet2::verify_signature(self : LeaseSet2) -> Bool { + if self.destination.inner.signing_type() != EdDsaSha512Ed25519 { + return false + } + let to_sign = self.signing_bytes() catch { _ => return false } + @crypto.ed25519_verify( + self.destination.inner.signing_public_key(), + to_sign, + self.signature, + ) +} + ///| pub fn LeaseSet2::decode(r : @encoding.Reader) -> LeaseSet2 raise CommonError { let destination = Destination::decode(r) diff --git a/common/types.mbt b/common/types.mbt index 9bc0310..a3dd68c 100644 --- a/common/types.mbt +++ b/common/types.mbt @@ -3,6 +3,7 @@ #derive(Eq, Debug) pub suberror CommonError { Encoding(@encoding.EncodingError) + Crypto(@crypto.CryptoError) InvalidLength(String) InvalidFormat(String) } diff --git a/crypto/aes.mbt b/crypto/aes.mbt new file mode 100644 index 0000000..98884dd --- /dev/null +++ b/crypto/aes.mbt @@ -0,0 +1,415 @@ +///| +/// Pure-MoonBit AES-256 (FIPS-197) and AES-256-CBC (NIST SP 800-38A). +/// Used for NTCP2 ephemeral key obfuscation and I2P tunnel layer encryption. + +///| +let aes_sbox : FixedArray[Byte] = [ + b'\x63', b'\x7c', b'\x77', b'\x7b', b'\xf2', b'\x6b', b'\x6f', b'\xc5', b'\x30', + b'\x01', b'\x67', b'\x2b', b'\xfe', b'\xd7', b'\xab', b'\x76', b'\xca', b'\x82', + b'\xc9', b'\x7d', b'\xfa', b'\x59', b'\x47', b'\xf0', b'\xad', b'\xd4', b'\xa2', + b'\xaf', b'\x9c', b'\xa4', b'\x72', b'\xc0', b'\xb7', b'\xfd', b'\x93', b'\x26', + b'\x36', b'\x3f', b'\xf7', b'\xcc', b'\x34', b'\xa5', b'\xe5', b'\xf1', b'\x71', + b'\xd8', b'\x31', b'\x15', b'\x04', b'\xc7', b'\x23', b'\xc3', b'\x18', b'\x96', + b'\x05', b'\x9a', b'\x07', b'\x12', b'\x80', b'\xe2', b'\xeb', b'\x27', b'\xb2', + b'\x75', b'\x09', b'\x83', b'\x2c', b'\x1a', b'\x1b', b'\x6e', b'\x5a', b'\xa0', + b'\x52', b'\x3b', b'\xd6', b'\xb3', b'\x29', b'\xe3', b'\x2f', b'\x84', b'\x53', + b'\xd1', b'\x00', b'\xed', b'\x20', b'\xfc', b'\xb1', b'\x5b', b'\x6a', b'\xcb', + b'\xbe', b'\x39', b'\x4a', b'\x4c', b'\x58', b'\xcf', b'\xd0', b'\xef', b'\xaa', + b'\xfb', b'\x43', b'\x4d', b'\x33', b'\x85', b'\x45', b'\xf9', b'\x02', b'\x7f', + b'\x50', b'\x3c', b'\x9f', b'\xa8', b'\x51', b'\xa3', b'\x40', b'\x8f', b'\x92', + b'\x9d', b'\x38', b'\xf5', b'\xbc', b'\xb6', b'\xda', b'\x21', b'\x10', b'\xff', + b'\xf3', b'\xd2', b'\xcd', b'\x0c', b'\x13', b'\xec', b'\x5f', b'\x97', b'\x44', + b'\x17', b'\xc4', b'\xa7', b'\x7e', b'\x3d', b'\x64', b'\x5d', b'\x19', b'\x73', + b'\x60', b'\x81', b'\x4f', b'\xdc', b'\x22', b'\x2a', b'\x90', b'\x88', b'\x46', + b'\xee', b'\xb8', b'\x14', b'\xde', b'\x5e', b'\x0b', b'\xdb', b'\xe0', b'\x32', + b'\x3a', b'\x0a', b'\x49', b'\x06', b'\x24', b'\x5c', b'\xc2', b'\xd3', b'\xac', + b'\x62', b'\x91', b'\x95', b'\xe4', b'\x79', b'\xe7', b'\xc8', b'\x37', b'\x6d', + b'\x8d', b'\xd5', b'\x4e', b'\xa9', b'\x6c', b'\x56', b'\xf4', b'\xea', b'\x65', + b'\x7a', b'\xae', b'\x08', b'\xba', b'\x78', b'\x25', b'\x2e', b'\x1c', b'\xa6', + b'\xb4', b'\xc6', b'\xe8', b'\xdd', b'\x74', b'\x1f', b'\x4b', b'\xbd', b'\x8b', + b'\x8a', b'\x70', b'\x3e', b'\xb5', b'\x66', b'\x48', b'\x03', b'\xf6', b'\x0e', + b'\x61', b'\x35', b'\x57', b'\xb9', b'\x86', b'\xc1', b'\x1d', b'\x9e', b'\xe1', + b'\xf8', b'\x98', b'\x11', b'\x69', b'\xd9', b'\x8e', b'\x94', b'\x9b', b'\x1e', + b'\x87', b'\xe9', b'\xce', b'\x55', b'\x28', b'\xdf', b'\x8c', b'\xa1', b'\x89', + b'\x0d', b'\xbf', b'\xe6', b'\x42', b'\x68', b'\x41', b'\x99', b'\x2d', b'\x0f', + b'\xb0', b'\x54', b'\xbb', b'\x16', +] + +///| +let aes_inv_sbox : FixedArray[Byte] = [ + b'\x52', b'\x09', b'\x6a', b'\xd5', b'\x30', b'\x36', b'\xa5', b'\x38', b'\xbf', + b'\x40', b'\xa3', b'\x9e', b'\x81', b'\xf3', b'\xd7', b'\xfb', b'\x7c', b'\xe3', + b'\x39', b'\x82', b'\x9b', b'\x2f', b'\xff', b'\x87', b'\x34', b'\x8e', b'\x43', + b'\x44', b'\xc4', b'\xde', b'\xe9', b'\xcb', b'\x54', b'\x7b', b'\x94', b'\x32', + b'\xa6', b'\xc2', b'\x23', b'\x3d', b'\xee', b'\x4c', b'\x95', b'\x0b', b'\x42', + b'\xfa', b'\xc3', b'\x4e', b'\x08', b'\x2e', b'\xa1', b'\x66', b'\x28', b'\xd9', + b'\x24', b'\xb2', b'\x76', b'\x5b', b'\xa2', b'\x49', b'\x6d', b'\x8b', b'\xd1', + b'\x25', b'\x72', b'\xf8', b'\xf6', b'\x64', b'\x86', b'\x68', b'\x98', b'\x16', + b'\xd4', b'\xa4', b'\x5c', b'\xcc', b'\x5d', b'\x65', b'\xb6', b'\x92', b'\x6c', + b'\x70', b'\x48', b'\x50', b'\xfd', b'\xed', b'\xb9', b'\xda', b'\x5e', b'\x15', + b'\x46', b'\x57', b'\xa7', b'\x8d', b'\x9d', b'\x84', b'\x90', b'\xd8', b'\xab', + b'\x00', b'\x8c', b'\xbc', b'\xd3', b'\x0a', b'\xf7', b'\xe4', b'\x58', b'\x05', + b'\xb8', b'\xb3', b'\x45', b'\x06', b'\xd0', b'\x2c', b'\x1e', b'\x8f', b'\xca', + b'\x3f', b'\x0f', b'\x02', b'\xc1', b'\xaf', b'\xbd', b'\x03', b'\x01', b'\x13', + b'\x8a', b'\x6b', b'\x3a', b'\x91', b'\x11', b'\x41', b'\x4f', b'\x67', b'\xdc', + b'\xea', b'\x97', b'\xf2', b'\xcf', b'\xce', b'\xf0', b'\xb4', b'\xe6', b'\x73', + b'\x96', b'\xac', b'\x74', b'\x22', b'\xe7', b'\xad', b'\x35', b'\x85', b'\xe2', + b'\xf9', b'\x37', b'\xe8', b'\x1c', b'\x75', b'\xdf', b'\x6e', b'\x47', b'\xf1', + b'\x1a', b'\x71', b'\x1d', b'\x29', b'\xc5', b'\x89', b'\x6f', b'\xb7', b'\x62', + b'\x0e', b'\xaa', b'\x18', b'\xbe', b'\x1b', b'\xfc', b'\x56', b'\x3e', b'\x4b', + b'\xc6', b'\xd2', b'\x79', b'\x20', b'\x9a', b'\xdb', b'\xc0', b'\xfe', b'\x78', + b'\xcd', b'\x5a', b'\xf4', b'\x1f', b'\xdd', b'\xa8', b'\x33', b'\x88', b'\x07', + b'\xc7', b'\x31', b'\xb1', b'\x12', b'\x10', b'\x59', b'\x27', b'\x80', b'\xec', + b'\x5f', b'\x60', b'\x51', b'\x7f', b'\xa9', b'\x19', b'\xb5', b'\x4a', b'\x0d', + b'\x2d', b'\xe5', b'\x7a', b'\x9f', b'\x93', b'\xc9', b'\x9c', b'\xef', b'\xa0', + b'\xe0', b'\x3b', b'\x4d', b'\xae', b'\x2a', b'\xf5', b'\xb0', b'\xc8', b'\xeb', + b'\xbb', b'\x3c', b'\x83', b'\x53', b'\x99', b'\x61', b'\x17', b'\x2b', b'\x04', + b'\x7e', b'\xba', b'\x77', b'\xd6', b'\x26', b'\xe1', b'\x69', b'\x14', b'\x63', + b'\x55', b'\x21', b'\x0c', b'\x7d', +] + +///| +let aes_rcon : FixedArray[UInt32] = [ + 0x00000000U, 0x01000000U, 0x02000000U, 0x04000000U, 0x08000000U, 0x10000000U, 0x20000000U, + 0x40000000U, +] + +///| +fn aes_sub_word(w : UInt32) -> UInt32 { + let b0 = aes_sbox[((w >> 24) & 0xFFU).reinterpret_as_int()].to_uint() + let b1 = aes_sbox[((w >> 16) & 0xFFU).reinterpret_as_int()].to_uint() + let b2 = aes_sbox[((w >> 8) & 0xFFU).reinterpret_as_int()].to_uint() + let b3 = aes_sbox[(w & 0xFFU).reinterpret_as_int()].to_uint() + (b0 << 24) | (b1 << 16) | (b2 << 8) | b3 +} + +///| +fn aes_rot_word(w : UInt32) -> UInt32 { + (w << 8) | (w >> 24) +} + +///| +/// Expands a 32-byte AES-256 key into 60 32-bit round key words (240 bytes). +fn aes256_expand_key(key : Bytes) -> FixedArray[Byte] { + let w = FixedArray::make(60, 0U) + for i = 0; i < 8; i = i + 1 { + w[i] = (key[4 * i].to_uint() << 24) | + (key[4 * i + 1].to_uint() << 16) | + (key[4 * i + 2].to_uint() << 8) | + key[4 * i + 3].to_uint() + } + for i = 8; i < 60; i = i + 1 { + let mut temp = w[i - 1] + if i % 8 == 0 { + temp = aes_sub_word(aes_rot_word(temp)) ^ aes_rcon[i / 8] + } else if i % 8 == 4 { + temp = aes_sub_word(temp) + } + w[i] = w[i - 8] ^ temp + } + let rk = FixedArray::make(240, b'\x00') + for i = 0; i < 60; i = i + 1 { + rk[4 * i] = ((w[i] >> 24) & 0xFFU).to_byte() + rk[4 * i + 1] = ((w[i] >> 16) & 0xFFU).to_byte() + rk[4 * i + 2] = ((w[i] >> 8) & 0xFFU).to_byte() + rk[4 * i + 3] = (w[i] & 0xFFU).to_byte() + } + rk +} + +///| +fn aes_xtime(a : Int32) -> Int32 { + let hi = a & 0x80 + let shifted = (a << 1) & 0xFF + if hi != 0 { + shifted ^ 0x1b + } else { + shifted + } +} + +///| +fn aes_gf_mul(a : Int32, b : Int32) -> Int32 { + let mut x = a & 0xFF + let mut y = b & 0xFF + let mut p = 0 + for _i = 0; _i < 8; _i = _i + 1 { + if (y & 1) != 0 { + p = p ^ x + } + x = aes_xtime(x) + y = y >> 1 + } + p +} + +///| +fn aes_add_round_key( + state : FixedArray[Byte], + rk : FixedArray[Byte], + round : Int32, +) -> Unit { + let off = round * 16 + for i = 0; i < 16; i = i + 1 { + state[i] = (state[i].to_int() ^ rk[off + i].to_int()).to_byte() + } +} + +///| +fn aes_sub_bytes(state : FixedArray[Byte]) -> Unit { + for i = 0; i < 16; i = i + 1 { + state[i] = aes_sbox[state[i].to_int()] + } +} + +///| +fn aes_inv_sub_bytes(state : FixedArray[Byte]) -> Unit { + for i = 0; i < 16; i = i + 1 { + state[i] = aes_inv_sbox[state[i].to_int()] + } +} + +///| +fn aes_shift_rows(s : FixedArray[Byte]) -> Unit { + // Row 1: left shift by 1 (indices 1, 5, 9, 13) + let t1 = s[1] + s[1] = s[5] + s[5] = s[9] + s[9] = s[13] + s[13] = t1 + // Row 2: left shift by 2 (indices 2, 6, 10, 14) + let t2 = s[2] + let t6 = s[6] + s[2] = s[10] + s[6] = s[14] + s[10] = t2 + s[14] = t6 + // Row 3: left shift by 3 (indices 3, 7, 11, 15) + let t15 = s[15] + s[15] = s[11] + s[11] = s[7] + s[7] = s[3] + s[3] = t15 +} + +///| +fn aes_inv_shift_rows(s : FixedArray[Byte]) -> Unit { + // Row 1: right shift by 1 (indices 1, 5, 9, 13) + let t13 = s[13] + s[13] = s[9] + s[9] = s[5] + s[5] = s[1] + s[1] = t13 + // Row 2: right shift by 2 (indices 2, 6, 10, 14) + let t2 = s[2] + let t6 = s[6] + s[2] = s[10] + s[6] = s[14] + s[10] = t2 + s[14] = t6 + // Row 3: right shift by 3 (indices 3, 7, 11, 15) + let t3 = s[3] + s[3] = s[7] + s[7] = s[11] + s[11] = s[15] + s[15] = t3 +} + +///| +fn aes_mix_columns(s : FixedArray[Byte]) -> Unit { + for c = 0; c < 4; c = c + 1 { + let i = c * 4 + let a0 = s[i].to_int() + let a1 = s[i + 1].to_int() + let a2 = s[i + 2].to_int() + let a3 = s[i + 3].to_int() + let t = a0 ^ a1 ^ a2 ^ a3 + s[i] = (a0 ^ t ^ aes_xtime(a0 ^ a1)).to_byte() + s[i + 1] = (a1 ^ t ^ aes_xtime(a1 ^ a2)).to_byte() + s[i + 2] = (a2 ^ t ^ aes_xtime(a2 ^ a3)).to_byte() + s[i + 3] = (a3 ^ t ^ aes_xtime(a3 ^ a0)).to_byte() + } +} + +///| +fn aes_inv_mix_columns(s : FixedArray[Byte]) -> Unit { + for c = 0; c < 4; c = c + 1 { + let i = c * 4 + let a0 = s[i].to_int() + let a1 = s[i + 1].to_int() + let a2 = s[i + 2].to_int() + let a3 = s[i + 3].to_int() + s[i] = (aes_gf_mul(a0, 14) ^ + aes_gf_mul(a1, 11) ^ + aes_gf_mul(a2, 13) ^ + aes_gf_mul(a3, 9)).to_byte() + s[i + 1] = (aes_gf_mul(a0, 9) ^ + aes_gf_mul(a1, 14) ^ + aes_gf_mul(a2, 11) ^ + aes_gf_mul(a3, 13)).to_byte() + s[i + 2] = (aes_gf_mul(a0, 13) ^ + aes_gf_mul(a1, 9) ^ + aes_gf_mul(a2, 14) ^ + aes_gf_mul(a3, 11)).to_byte() + s[i + 3] = (aes_gf_mul(a0, 11) ^ + aes_gf_mul(a1, 13) ^ + aes_gf_mul(a2, 9) ^ + aes_gf_mul(a3, 14)).to_byte() + } +} + +///| +fn aes256_encrypt_block_with_rk( + rk : FixedArray[Byte], + state : FixedArray[Byte], +) -> Unit { + aes_add_round_key(state, rk, 0) + for round = 1; round < 14; round = round + 1 { + aes_sub_bytes(state) + aes_shift_rows(state) + aes_mix_columns(state) + aes_add_round_key(state, rk, round) + } + aes_sub_bytes(state) + aes_shift_rows(state) + aes_add_round_key(state, rk, 14) +} + +///| +fn aes256_decrypt_block_with_rk( + rk : FixedArray[Byte], + state : FixedArray[Byte], +) -> Unit { + aes_add_round_key(state, rk, 14) + for round = 13; round >= 1; round = round - 1 { + aes_inv_shift_rows(state) + aes_inv_sub_bytes(state) + aes_add_round_key(state, rk, round) + aes_inv_mix_columns(state) + } + aes_inv_shift_rows(state) + aes_inv_sub_bytes(state) + aes_add_round_key(state, rk, 0) +} + +///| +/// Encrypts a single 16-byte block with AES-256 (ECB). +pub fn aes256_encrypt_block( + key : Bytes, + block : Bytes, +) -> Bytes raise CryptoError { + if key.length() != 32 { + raise InvalidKeyLength("AES-256 key must be 32 bytes, got \{key.length()}") + } + if block.length() != 16 { + raise InvalidLength("AES block must be 16 bytes, got \{block.length()}") + } + let rk = aes256_expand_key(key) + let state = FixedArray::make(16, b'\x00') + for i = 0; i < 16; i = i + 1 { + state[i] = block[i] + } + aes256_encrypt_block_with_rk(rk, state) + Bytes::from_array(state) +} + +///| +/// Decrypts a single 16-byte block with AES-256 (ECB). +pub fn aes256_decrypt_block( + key : Bytes, + block : Bytes, +) -> Bytes raise CryptoError { + if key.length() != 32 { + raise InvalidKeyLength("AES-256 key must be 32 bytes, got \{key.length()}") + } + if block.length() != 16 { + raise InvalidLength("AES block must be 16 bytes, got \{block.length()}") + } + let rk = aes256_expand_key(key) + let state = FixedArray::make(16, b'\x00') + for i = 0; i < 16; i = i + 1 { + state[i] = block[i] + } + aes256_decrypt_block_with_rk(rk, state) + Bytes::from_array(state) +} + +///| +/// Encrypts `data` (length must be a multiple of 16 bytes) using AES-256-CBC (no padding). +pub fn aes256_cbc_encrypt( + key : Bytes, + iv : Bytes, + data : Bytes, +) -> Bytes raise CryptoError { + if key.length() != 32 { + raise InvalidKeyLength("AES-256 key must be 32 bytes, got \{key.length()}") + } + if iv.length() != 16 { + raise InvalidNonceLength("AES-CBC IV must be 16 bytes, got \{iv.length()}") + } + if data.length() % 16 != 0 { + raise InvalidLength( + "AES-CBC input must be a multiple of 16 bytes, got \{data.length()}", + ) + } + let rk = aes256_expand_key(key) + let out = FixedArray::make(data.length(), b'\x00') + let prev = FixedArray::make(16, b'\x00') + for i = 0; i < 16; i = i + 1 { + prev[i] = iv[i] + } + let state = FixedArray::make(16, b'\x00') + let mut off = 0 + while off < data.length() { + for i = 0; i < 16; i = i + 1 { + state[i] = (data[off + i].to_int() ^ prev[i].to_int()).to_byte() + } + aes256_encrypt_block_with_rk(rk, state) + for i = 0; i < 16; i = i + 1 { + out[off + i] = state[i] + prev[i] = state[i] + } + off += 16 + } + Bytes::from_array(out) +} + +///| +/// Decrypts `data` (length must be a multiple of 16 bytes) using AES-256-CBC (no padding). +pub fn aes256_cbc_decrypt( + key : Bytes, + iv : Bytes, + data : Bytes, +) -> Bytes raise CryptoError { + if key.length() != 32 { + raise InvalidKeyLength("AES-256 key must be 32 bytes, got \{key.length()}") + } + if iv.length() != 16 { + raise InvalidNonceLength("AES-CBC IV must be 16 bytes, got \{iv.length()}") + } + if data.length() % 16 != 0 { + raise InvalidLength( + "AES-CBC input must be a multiple of 16 bytes, got \{data.length()}", + ) + } + let rk = aes256_expand_key(key) + let out = FixedArray::make(data.length(), b'\x00') + let prev = FixedArray::make(16, b'\x00') + for i = 0; i < 16; i = i + 1 { + prev[i] = iv[i] + } + let state = FixedArray::make(16, b'\x00') + let mut off = 0 + while off < data.length() { + for i = 0; i < 16; i = i + 1 { + state[i] = data[off + i] + } + aes256_decrypt_block_with_rk(rk, state) + for i = 0; i < 16; i = i + 1 { + out[off + i] = (state[i].to_int() ^ prev[i].to_int()).to_byte() + prev[i] = data[off + i] + } + off += 16 + } + Bytes::from_array(out) +} diff --git a/crypto/crypto_test.mbt b/crypto/crypto_test.mbt index 4f45d89..ef6db74 100644 --- a/crypto/crypto_test.mbt +++ b/crypto/crypto_test.mbt @@ -117,3 +117,124 @@ test "siphash_2_4 official test vector" { let msg = @encoding.hex_decode("000102030405060708090a0b0c0d0e") assert_eq(@crypto.siphash_2_4(key, msg), 0xa129ca6149be45e5UL) } + +///| +test "sha512 FIPS 180-4 test vectors" { + assert_eq( + @encoding.hex_encode(@crypto.sha512(b"")), + "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", + ) + assert_eq( + @encoding.hex_encode(@crypto.sha512(b"abc")), + "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", + ) + assert_eq( + @encoding.hex_encode( + @crypto.sha512( + b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", + ), + ), + "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909", + ) +} + +///| +test "ed25519 RFC 8032 Section 7.1 test vectors 1, 2, 3" { + // TEST 1: empty message + let seed1 = @encoding.hex_decode( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + ) + let pub1 = @crypto.ed25519_public_key(seed1) + assert_eq( + @encoding.hex_encode(pub1), + "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", + ) + let sig1 = @crypto.ed25519_sign(seed1, b"") + assert_eq( + @encoding.hex_encode(sig1), + "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", + ) + assert_eq(@crypto.ed25519_verify(pub1, b"", sig1), true) + assert_eq(@crypto.ed25519_verify(pub1, b"x", sig1), false) + + // TEST 2: 1-byte message 0x72 + let seed2 = @encoding.hex_decode( + "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", + ) + let pub2 = @crypto.ed25519_public_key(seed2) + assert_eq( + @encoding.hex_encode(pub2), + "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", + ) + let msg2 = @encoding.hex_decode("72") + let sig2 = @crypto.ed25519_sign(seed2, msg2) + assert_eq( + @encoding.hex_encode(sig2), + "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00", + ) + assert_eq(@crypto.ed25519_verify(pub2, msg2, sig2), true) + + // TEST 3: 2-byte message 0xaf82 + let seed3 = @encoding.hex_decode( + "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", + ) + let pub3 = @crypto.ed25519_public_key(seed3) + assert_eq( + @encoding.hex_encode(pub3), + "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", + ) + let msg3 = @encoding.hex_decode("af82") + let sig3 = @crypto.ed25519_sign(seed3, msg3) + assert_eq( + @encoding.hex_encode(sig3), + "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a", + ) + assert_eq(@crypto.ed25519_verify(pub3, msg3, sig3), true) + // Tampered signature byte must fail + let bad_sig = FixedArray::make(64, b'\x00') + for i = 0; i < 64; i = i + 1 { + bad_sig[i] = sig3[i] + } + bad_sig[63] = (bad_sig[63].to_int() ^ 0x01).to_byte() + assert_eq( + @crypto.ed25519_verify(pub3, msg3, Bytes::from_array(bad_sig)), + false, + ) + // Non-canonical S >= L must fail + let non_canon = FixedArray::make(64, b'\x00') + for i = 0; i < 32; i = i + 1 { + non_canon[i] = sig3[i] + } + non_canon[63] = b'\xff' + assert_eq( + @crypto.ed25519_verify(pub3, msg3, Bytes::from_array(non_canon)), + false, + ) +} + +///| +test "aes256 FIPS-197 Appendix C.3 and SP 800-38A CBC vectors" { + // FIPS-197 Appendix C.3 AES-256 single block + let key1 = @encoding.hex_decode( + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + ) + let pt1 = @encoding.hex_decode("00112233445566778899aabbccddeeff") + let ct1 = @crypto.aes256_encrypt_block(key1, pt1) + assert_eq(@encoding.hex_encode(ct1), "8ea2b7ca516745bfeafc49904b496089") + assert_eq(@crypto.aes256_decrypt_block(key1, ct1), pt1) + + // NIST SP 800-38A F.2.5 / F.2.6 CBC-AES256 + let key2 = @encoding.hex_decode( + "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", + ) + let iv2 = @encoding.hex_decode("000102030405060708090a0b0c0d0e0f") + let pt2 = @encoding.hex_decode( + "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710", + ) + let expected_ct2 = @encoding.hex_decode( + "f58c4c04d6e5f1ba779eabfb5f7bfbd69cfc4e967edb808d679f777bc6702c7d39f23369a9d9bacfa530e26304231461b2eb05e2c39be9fcda6c19078c6a9d1b", + ) + let ct2 = @crypto.aes256_cbc_encrypt(key2, iv2, pt2) + assert_eq(ct2, expected_ct2) + assert_eq(@crypto.aes256_cbc_decrypt(key2, iv2, ct2), pt2) +} diff --git a/crypto/ed25519.mbt b/crypto/ed25519.mbt new file mode 100644 index 0000000..502c4c3 --- /dev/null +++ b/crypto/ed25519.mbt @@ -0,0 +1,373 @@ +///| +/// Pure-MoonBit RFC 8032 Ed25519 digital signatures (EdDSA over Edwards25519 with SHA-512). +/// Reuses 16-limb field arithmetic mod 2^255 - 19 from `x25519.mbt`. + +///| +/// Curve constant d = -121665 / 121666 mod p. +fn ed_d() -> FixedArray[Int64] { + [ + 0x78a3L, 0x1359L, 0x4dcaL, 0x75ebL, 0xd8abL, 0x4141L, 0x0a4dL, 0x0070L, 0xe898L, + 0x7779L, 0x4079L, 0x8cc7L, 0xfe73L, 0x2b6fL, 0x6ceeL, 0x5203L, + ] +} + +///| +/// 2 * d mod p (used in extended twisted Edwards point addition). +fn ed_2d() -> FixedArray[Int64] { + let d = ed_d() + let r = gf_add(d, d) + gf_carry(r) + r +} + +///| +/// Square root of -1 mod p: I = 2^((p - 1) / 4) mod p. +fn ed_sqrt_m1() -> FixedArray[Int64] { + [ + 0xa0b0L, 0x4a0eL, 0x1b27L, 0xc4eeL, 0xe478L, 0xad2fL, 0x1806L, 0x2f43L, 0xd7a7L, + 0x3dfbL, 0x0099L, 0x2b4dL, 0xdf0bL, 0x4fc1L, 0x2480L, 0x2b83L, + ] +} + +///| +/// Extended twisted Edwards point (X, Y, Z, T) where x = X/Z, y = Y/Z, xy = T/Z. +priv struct EdPoint { + x : FixedArray[Int64] + y : FixedArray[Int64] + z : FixedArray[Int64] + t : FixedArray[Int64] +} + +///| +fn ed_identity() -> EdPoint { + { x: gf_zero(), y: gf_one(), z: gf_one(), t: gf_zero(), } +} + +///| +fn ed_basepoint() -> EdPoint { + let bx : FixedArray[Int64] = [ + 0xd51aL, 0x8f25L, 0x2d60L, 0xc956L, 0xa7b2L, 0x9525L, 0xc760L, 0x692cL, 0xdc5cL, + 0xfdd6L, 0xe231L, 0xc0a4L, 0x53feL, 0xcd6eL, 0x36d3L, 0x2169L, + ] + let by : FixedArray[Int64] = [ + 0x6658L, 0x6666L, 0x6666L, 0x6666L, 0x6666L, 0x6666L, 0x6666L, 0x6666L, 0x6666L, + 0x6666L, 0x6666L, 0x6666L, 0x6666L, 0x6666L, 0x6666L, 0x6666L, + ] + { x: bx, y: by, z: gf_one(), t: gf_mul(bx, by), } +} + +///| +/// Unified, complete extended twisted Edwards point addition (a = -1). +fn ed_add(p : EdPoint, q : EdPoint) -> EdPoint { + let a = gf_mul(gf_sub(p.y, p.x), gf_sub(q.y, q.x)) + let b = gf_mul(gf_add(p.y, p.x), gf_add(q.y, q.x)) + let c = gf_mul(gf_mul(p.t, q.t), ed_2d()) + let dz = gf_mul(p.z, q.z) + let d = gf_add(dz, dz) + let e = gf_sub(b, a) + let f = gf_sub(d, c) + let g = gf_add(d, c) + let h = gf_add(b, a) + { x: gf_mul(e, f), y: gf_mul(g, h), z: gf_mul(f, g), t: gf_mul(e, h), } +} + +///| +fn ed_cswap(p : EdPoint, q : EdPoint, b : Int64) -> Unit { + gf_cswap(p.x, q.x, b) + gf_cswap(p.y, q.y, b) + gf_cswap(p.z, q.z, b) + gf_cswap(p.t, q.t, b) +} + +///| +/// Constant-time scalar multiplication [s]P for a 32-byte little-endian scalar `s`. +fn ed_scalarmult(p : EdPoint, s : Bytes) -> EdPoint { + let mut r = ed_identity() + let mut q = { + x: gf_copy(p.x), + y: gf_copy(p.y), + z: gf_copy(p.z), + t: gf_copy(p.t), + } + for i = 255; i >= 0; i = i - 1 { + let bit = ((s[i >> 3].to_int() >> (i & 7)) & 1).to_int64() + ed_cswap(r, q, bit) + q = ed_add(q, r) + r = ed_add(r, r) + ed_cswap(r, q, bit) + } + r +} + +///| +/// Encodes an EdPoint to its 32-byte RFC 8032 compressed representation. +fn ed_pack(p : EdPoint) -> Bytes { + let zi = gf_inv(p.z) + let tx = gf_mul(p.x, zi) + let ty = gf_mul(p.y, zi) + let xb = gf_pack(tx) + let yb = gf_pack(ty) + let out = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + out[i] = yb[i] + } + out[31] = (out[31].to_int() | ((xb[0].to_int() & 1) << 7)).to_byte() + Bytes::from_array(out) +} + +///| +/// Computes z^((p - 5) / 8) = z^(2^252 - 3) mod p. +fn gf_pow2523(z : FixedArray[Int64]) -> FixedArray[Int64] { + let mut c = gf_copy(z) + for i = 250; i >= 0; i = i - 1 { + c = gf_sq(c) + if i != 1 { + c = gf_mul(c, z) + } + } + c +} + +///| +fn is_zero_bytes(b : Bytes) -> Bool { + let mut acc = 0 + for i = 0; i < b.length(); i = i + 1 { + acc = acc | b[i].to_int() + } + acc == 0 +} + +///| +/// Decodes a 32-byte RFC 8032 compressed point, validating canonical y < p and curve equation. +fn ed_unpack(s : Bytes) -> EdPoint? { + if s.length() != 32 { + return None + } + let sign = (s[31].to_int() >> 7) & 1 + let masked = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + masked[i] = s[i] + } + masked[31] = (masked[31].to_int() & 0x7f).to_byte() + let y = gf_unpack(s) + // Reject non-canonical y >= p + if !ct_eq(gf_pack(y), Bytes::from_array(masked)) { + return None + } + let y2 = gf_sq(y) + let u = gf_sub(y2, gf_one()) + let v = gf_add(gf_mul(ed_d(), y2), gf_one()) + let v3 = gf_mul(gf_sq(v), v) + let v7 = gf_mul(gf_sq(v3), v) + let uv3 = gf_mul(u, v3) + let uv7 = gf_mul(u, v7) + let mut x = gf_mul(uv3, gf_pow2523(uv7)) + let vx2 = gf_pack(gf_mul(v, gf_sq(x))) + let u_packed = gf_pack(u) + if !ct_eq(vx2, u_packed) { + let neg_u = gf_pack(gf_sub(gf_zero(), u)) + if ct_eq(vx2, neg_u) { + x = gf_mul(x, ed_sqrt_m1()) + } else { + return None + } + } + let x_packed = gf_pack(x) + if is_zero_bytes(x_packed) { + if sign == 1 { + return None + } + } else if (x_packed[0].to_int() & 1) != sign { + x = gf_sub(gf_zero(), x) + } + Some({ x, y, z: gf_one(), t: gf_mul(x, y), }) +} + +///| +/// Group order L = 2^252 + 27742317777372353535851937790883648493 (little-endian bytes). +let ed_l : FixedArray[Int64] = [ + 0xedL, 0xd3L, 0xf5L, 0x5cL, 0x1aL, 0x63L, 0x12L, 0x58L, 0xd6L, 0x9cL, 0xf7L, 0xa2L, + 0xdeL, 0xf9L, 0xdeL, 0x14L, 0x00L, 0x00L, 0x00L, 0x00L, 0x00L, 0x00L, 0x00L, 0x00L, + 0x00L, 0x00L, 0x00L, 0x00L, 0x00L, 0x00L, 0x00L, 0x10L, +] + +///| +/// Reduces a 64-element little-endian byte-limb array modulo L into a 32-byte scalar. +fn mod_l(x : FixedArray[Int64]) -> Bytes { + for i = 63; i >= 32; i = i - 1 { + let mut carry = 0L + let mut j = i - 32 + let k = i - 12 + while j < k { + x[j] = x[j] + carry - 16L * x[i] * ed_l[j - (i - 32)] + carry = (x[j] + 128L) >> 8 + x[j] = x[j] - (carry << 8) + j += 1 + } + x[j] = x[j] + carry + x[i] = 0L + } + let mut carry = 0L + for j = 0; j < 32; j = j + 1 { + x[j] = x[j] + carry - (x[31] >> 4) * ed_l[j] + carry = x[j] >> 8 + x[j] = x[j] & 255L + } + for j = 0; j < 32; j = j + 1 { + x[j] = x[j] - carry * ed_l[j] + } + let r = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + if i < 31 { + x[i + 1] = x[i + 1] + (x[i] >> 8) + } + r[i] = (x[i] & 255L).to_byte() + } + Bytes::from_array(r) +} + +///| +fn reduce_64_mod_l(h : Bytes) -> Bytes { + let x = FixedArray::make(64, 0L) + for i = 0; i < 64; i = i + 1 { + x[i] = h[i].to_int64() + } + mod_l(x) +} + +///| +/// Checks that a 32-byte little-endian scalar `s` is strictly less than L. +fn scalar_is_canonical(s : Bytes) -> Bool { + for i = 31; i >= 0; i = i - 1 { + let sb = s[i].to_int64() + let lb = ed_l[i] + if sb < lb { + return true + } + if sb > lb { + return false + } + } + false +} + +///| +fn clamp_ed25519_scalar(h : Bytes) -> Bytes { + let a = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + a[i] = h[i] + } + a[0] = (a[0].to_int() & 248).to_byte() + a[31] = ((a[31].to_int() & 127) | 64).to_byte() + Bytes::from_array(a) +} + +///| +/// Derives the 32-byte Ed25519 public key from a 32-byte private seed (RFC 8032 Section 5.1.5). +pub fn ed25519_public_key(seed : Bytes) -> Bytes raise CryptoError { + if seed.length() != 32 { + raise InvalidKeyLength( + "Ed25519 seed must be 32 bytes, got \{seed.length()}", + ) + } + let h = sha512(seed) + let a = clamp_ed25519_scalar(h) + ed_pack(ed_scalarmult(ed_basepoint(), a)) +} + +///| +/// Signs `message` with a 32-byte Ed25519 private `seed`, returning a 64-byte signature +/// (RFC 8032 Section 5.1.6). +pub fn ed25519_sign(seed : Bytes, message : Bytes) -> Bytes raise CryptoError { + if seed.length() != 32 { + raise InvalidKeyLength( + "Ed25519 seed must be 32 bytes, got \{seed.length()}", + ) + } + let h = sha512(seed) + let a = clamp_ed25519_scalar(h) + let prefix = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + prefix[i] = h[32 + i] + } + let pub_key = ed_pack(ed_scalarmult(ed_basepoint(), a)) + + // r = SHA-512(prefix || message) mod L + let r_hasher = Sha512::new() + r_hasher.update(Bytes::from_array(prefix)) + r_hasher.update(message) + let r = reduce_64_mod_l(r_hasher.finalize()) + + // R = [r]B + let r_enc = ed_pack(ed_scalarmult(ed_basepoint(), r)) + + // k = SHA-512(R || A || message) mod L + let k_hasher = Sha512::new() + k_hasher.update(r_enc) + k_hasher.update(pub_key) + k_hasher.update(message) + let k = reduce_64_mod_l(k_hasher.finalize()) + + // S = (r + k * a) mod L + let x = FixedArray::make(64, 0L) + for i = 0; i < 32; i = i + 1 { + x[i] = r[i].to_int64() + } + for i = 0; i < 32; i = i + 1 { + let ki = k[i].to_int64() + for j = 0; j < 32; j = j + 1 { + x[i + j] = x[i + j] + ki * a[j].to_int64() + } + } + let s_enc = mod_l(x) + + let sig = FixedArray::make(64, b'\x00') + for i = 0; i < 32; i = i + 1 { + sig[i] = r_enc[i] + sig[32 + i] = s_enc[i] + } + Bytes::from_array(sig) +} + +///| +/// Verifies a 64-byte Ed25519 signature over `message` against a 32-byte `public_key` +/// (RFC 8032 Section 5.1.7). Returns `false` on any malformed key, signature, or mismatch. +pub fn ed25519_verify( + public_key : Bytes, + message : Bytes, + signature : Bytes, +) -> Bool { + if public_key.length() != 32 || signature.length() != 64 { + return false + } + let a_point = match ed_unpack(public_key) { + Some(pt) => pt + None => return false + } + let r_bytes = FixedArray::make(32, b'\x00') + let s_bytes = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + r_bytes[i] = signature[i] + s_bytes[i] = signature[32 + i] + } + let r_enc = Bytes::from_array(r_bytes) + let s_enc = Bytes::from_array(s_bytes) + if !scalar_is_canonical(s_enc) { + return false + } + let r_point = match ed_unpack(r_enc) { + Some(pt) => pt + None => return false + } + // k = SHA-512(R || A || message) mod L + let k_hasher = Sha512::new() + k_hasher.update(r_enc) + k_hasher.update(public_key) + k_hasher.update(message) + let k = reduce_64_mod_l(k_hasher.finalize()) + + // Check [S]B == R + [k]A + let lhs = ed_pack(ed_scalarmult(ed_basepoint(), s_enc)) + let rhs = ed_pack(ed_add(r_point, ed_scalarmult(a_point, k))) + ct_eq(lhs, rhs) +} diff --git a/crypto/pkg.generated.mbti b/crypto/pkg.generated.mbti index d91164c..7cbdaf9 100644 --- a/crypto/pkg.generated.mbti +++ b/crypto/pkg.generated.mbti @@ -10,12 +10,26 @@ pub fn aead_chacha20_poly1305_decrypt(Bytes, Bytes, Bytes, Bytes) -> Bytes raise pub fn aead_chacha20_poly1305_encrypt(Bytes, Bytes, Bytes, Bytes) -> Bytes raise CryptoError +pub fn aes256_cbc_decrypt(Bytes, Bytes, Bytes) -> Bytes raise CryptoError + +pub fn aes256_cbc_encrypt(Bytes, Bytes, Bytes) -> Bytes raise CryptoError + +pub fn aes256_decrypt_block(Bytes, Bytes) -> Bytes raise CryptoError + +pub fn aes256_encrypt_block(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 ed25519_public_key(Bytes) -> Bytes raise CryptoError + +pub fn ed25519_sign(Bytes, Bytes) -> Bytes raise CryptoError + +pub fn ed25519_verify(Bytes, Bytes, Bytes) -> Bool + pub fn hkdf(Bytes, Bytes, Bytes, Int32) -> Bytes raise CryptoError pub fn hkdf_expand(Bytes, Bytes, Int32) -> Bytes raise CryptoError @@ -28,6 +42,8 @@ pub fn poly1305_mac(Bytes, Bytes) -> Bytes raise CryptoError pub fn sha256(Bytes) -> Bytes +pub fn sha512(Bytes) -> Bytes + pub fn siphash_2_4(Bytes, Bytes) -> UInt64 raise CryptoError pub fn x25519(Bytes, Bytes) -> Bytes raise CryptoError @@ -54,6 +70,17 @@ pub fn Sha256::finalize(Self) -> Bytes pub fn Sha256::new() -> Self pub fn Sha256::update(Self, Bytes) -> Unit +pub struct Sha512 { + state : FixedArray[UInt64] + block : FixedArray[Byte] + mut block_len : Int32 + mut total_len_lo : UInt64 + mut total_len_hi : UInt64 +} +pub fn Sha512::finalize(Self) -> Bytes +pub fn Sha512::new() -> Self +pub fn Sha512::update(Self, Bytes) -> Unit + // Type aliases // Traits diff --git a/crypto/sha512.mbt b/crypto/sha512.mbt new file mode 100644 index 0000000..f89e2e1 --- /dev/null +++ b/crypto/sha512.mbt @@ -0,0 +1,173 @@ +///| +/// Pure-MoonBit SHA-512 (FIPS 180-4). + +///| +let sha512_k : FixedArray[UInt64] = [ + 0x428a2f98d728ae22UL, 0x7137449123ef65cdUL, 0xb5c0fbcfec4d3b2fUL, 0xe9b5dba58189dbbcUL, + 0x3956c25bf348b538UL, 0x59f111f1b605d019UL, 0x923f82a4af194f9bUL, 0xab1c5ed5da6d8118UL, + 0xd807aa98a3030242UL, 0x12835b0145706fbeUL, 0x243185be4ee4b28cUL, 0x550c7dc3d5ffb4e2UL, + 0x72be5d74f27b896fUL, 0x80deb1fe3b1696b1UL, 0x9bdc06a725c71235UL, 0xc19bf174cf692694UL, + 0xe49b69c19ef14ad2UL, 0xefbe4786384f25e3UL, 0x0fc19dc68b8cd5b5UL, 0x240ca1cc77ac9c65UL, + 0x2de92c6f592b0275UL, 0x4a7484aa6ea6e483UL, 0x5cb0a9dcbd41fbd4UL, 0x76f988da831153b5UL, + 0x983e5152ee66dfabUL, 0xa831c66d2db43210UL, 0xb00327c898fb213fUL, 0xbf597fc7beef0ee4UL, + 0xc6e00bf33da88fc2UL, 0xd5a79147930aa725UL, 0x06ca6351e003826fUL, 0x142929670a0e6e70UL, + 0x27b70a8546d22ffcUL, 0x2e1b21385c26c926UL, 0x4d2c6dfc5ac42aedUL, 0x53380d139d95b3dfUL, + 0x650a73548baf63deUL, 0x766a0abb3c77b2a8UL, 0x81c2c92e47edaee6UL, 0x92722c851482353bUL, + 0xa2bfe8a14cf10364UL, 0xa81a664bbc423001UL, 0xc24b8b70d0f89791UL, 0xc76c51a30654be30UL, + 0xd192e819d6ef5218UL, 0xd69906245565a910UL, 0xf40e35855771202aUL, 0x106aa07032bbd1b8UL, + 0x19a4c116b8d2d0c8UL, 0x1e376c085141ab53UL, 0x2748774cdf8eeb99UL, 0x34b0bcb5e19b48a8UL, + 0x391c0cb3c5c95a63UL, 0x4ed8aa4ae3418acbUL, 0x5b9cca4f7763e373UL, 0x682e6ff3d6b2b8a3UL, + 0x748f82ee5defb2fcUL, 0x78a5636f43172f60UL, 0x84c87814a1f0ab72UL, 0x8cc702081a6439ecUL, + 0x90befffa23631e28UL, 0xa4506cebde82bde9UL, 0xbef9a3f7b2c67915UL, 0xc67178f2e372532bUL, + 0xca273eceea26619cUL, 0xd186b8c721c0c207UL, 0xeada7dd6cde0eb1eUL, 0xf57d4f7fee6ed178UL, + 0x06f067aa72176fbaUL, 0x0a637dc5a2c898a6UL, 0x113f9804bef90daeUL, 0x1b710b35131c471bUL, + 0x28db77f523047d84UL, 0x32caab7b40c72493UL, 0x3c9ebe0a15c9bebcUL, 0x431d67c49c100d4cUL, + 0x4cc5d4becb3e42b6UL, 0x597f299cfc657e2aUL, 0x5fcb6fab3ad6faecUL, 0x6c44198c4a475817UL, +] + +///| +fn rotr64(x : UInt64, n : Int32) -> UInt64 { + (x >> n) | (x << (64 - n)) +} + +///| +/// Incremental SHA-512 hasher (FIPS 180-4). +pub struct Sha512 { + state : FixedArray[UInt64] + block : FixedArray[Byte] + mut block_len : Int32 + mut total_len_lo : UInt64 + mut total_len_hi : UInt64 +} + +///| +pub fn Sha512::new() -> Sha512 { + { + state: [ + 0x6a09e667f3bcc908UL, 0xbb67ae8584caa73bUL, 0x3c6ef372fe94f82bUL, 0xa54ff53a5f1d36f1UL, + 0x510e527fade682d1UL, 0x9b05688c2b3e6c1fUL, 0x1f83d9abfb41bd6bUL, 0x5be0cd19137e2179UL, + ], + block: FixedArray::make(128, b'\x00'), + block_len: 0, + total_len_lo: 0UL, + total_len_hi: 0UL, + } +} + +///| +fn Sha512::compress(self : Sha512) -> Unit { + let w = FixedArray::make(80, 0UL) + for i = 0; i < 16; i = i + 1 { + let j = i * 8 + w[i] = (self.block[j].to_uint64() << 56) | + (self.block[j + 1].to_uint64() << 48) | + (self.block[j + 2].to_uint64() << 40) | + (self.block[j + 3].to_uint64() << 32) | + (self.block[j + 4].to_uint64() << 24) | + (self.block[j + 5].to_uint64() << 16) | + (self.block[j + 6].to_uint64() << 8) | + self.block[j + 7].to_uint64() + } + for i = 16; i < 80; i = i + 1 { + let s0 = rotr64(w[i - 15], 1) ^ rotr64(w[i - 15], 8) ^ (w[i - 15] >> 7) + let s1 = rotr64(w[i - 2], 19) ^ rotr64(w[i - 2], 61) ^ (w[i - 2] >> 6) + 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 < 80; i = i + 1 { + let s1 = rotr64(e, 14) ^ rotr64(e, 18) ^ rotr64(e, 41) + let ch = (e & f) ^ (e.lnot() & g) + let temp1 = h + s1 + ch + sha512_k[i] + w[i] + let s0 = rotr64(a, 28) ^ rotr64(a, 34) ^ rotr64(a, 39) + 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 Sha512::update(self : Sha512, data : Bytes) -> Unit { + let len = data.length() + let add = len.to_uint64() + let prev = self.total_len_lo + self.total_len_lo = self.total_len_lo + add + if self.total_len_lo < prev { + self.total_len_hi = self.total_len_hi + 1UL + } + for i = 0; i < len; i = i + 1 { + self.block[self.block_len] = data[i] + self.block_len += 1 + if self.block_len == 128 { + self.compress() + self.block_len = 0 + } + } +} + +///| +pub fn Sha512::finalize(self : Sha512) -> Bytes { + let bit_lo = self.total_len_lo << 3 + let bit_hi = (self.total_len_hi << 3) | (self.total_len_lo >> 61) + self.block[self.block_len] = b'\x80' + self.block_len += 1 + if self.block_len > 112 { + while self.block_len < 128 { + self.block[self.block_len] = b'\x00' + self.block_len += 1 + } + self.compress() + self.block_len = 0 + } + while self.block_len < 112 { + self.block[self.block_len] = b'\x00' + self.block_len += 1 + } + for i = 0; i < 8; i = i + 1 { + self.block[112 + i] = ((bit_hi >> (56 - i * 8)) & 0xFFUL).to_byte() + self.block[120 + i] = ((bit_lo >> (56 - i * 8)) & 0xFFUL).to_byte() + } + self.compress() + let out = FixedArray::make(64, b'\x00') + for i = 0; i < 8; i = i + 1 { + let v = self.state[i] + out[i * 8] = ((v >> 56) & 0xFFUL).to_byte() + out[i * 8 + 1] = ((v >> 48) & 0xFFUL).to_byte() + out[i * 8 + 2] = ((v >> 40) & 0xFFUL).to_byte() + out[i * 8 + 3] = ((v >> 32) & 0xFFUL).to_byte() + out[i * 8 + 4] = ((v >> 24) & 0xFFUL).to_byte() + out[i * 8 + 5] = ((v >> 16) & 0xFFUL).to_byte() + out[i * 8 + 6] = ((v >> 8) & 0xFFUL).to_byte() + out[i * 8 + 7] = (v & 0xFFUL).to_byte() + } + Bytes::from_array(out) +} + +///| +/// Computes the 64-byte SHA-512 digest of `data`. +pub fn sha512(data : Bytes) -> Bytes { + let h = Sha512::new() + h.update(data) + h.finalize() +}