experimental_crypto

    EXPERIMENTAL — pure-MoonBit cryptography / PKI / JOSE building blocks. Educational reference, not production-grade. No warranty.

    crypto
    cryptography
    pki
    jose
    experimental
    Download zip
    Author
    Version
    0.0.1
    License
    Apache-2.0
    Last updated
    5 months ago
    Downloads
    14K

    #experimental_crypto

    Status: experimental — not for production. This workspace exists to fill gaps in the MoonBit ecosystem so other people writing MoonBit code have something to read and reuse. None of the modules have been independently audited. Constant-time discipline, side-channel resistance, and on-wire format edge cases are documented but not certified.

    If you use any of this code in a real system, you are responsible for reviewing the source first and confirming it meets your security requirements. The author disclaims all liability for use. Prefer a vetted library (RustCrypto, dalek, BoringSSL, etc.) wherever one exists for your protocol.

    Pure MoonBit building blocks for crypto, PKI, JOSE, and signing formats. Everything lives in a single MoonBit module, mizchi/experimental_crypto, with each library/protocol shipped as a sub-package you import by path (for example mizchi/experimental_crypto/asn1, aliased @asn1). It currently has 35 library/protocol sub-packages plus the proofs and leakage_harness sidecars. The implementations stay on top of moonbitlang/core, a small moonbitlang/x dependency for platform hooks, and the other sub-packages in this module.

    The constant-time properties of the field arithmetic are not yet up to the bar of dalek or RustCrypto; the file headers call out exactly where the gaps are.

    #Module map

    For API-level detail, see docs/MODULES.md and docs/ARCHITECTURE.md.

    AreaModulesNotes
    Encoding and foundationsasn1, cbor, crypto_bigint, getrandomStrict DER/CBOR codecs, fixed-limb unsigned integers, and platform CSPRNG bridge.
    Hashes, AEAD, and KDFshash, aead, hkdf, pbkdf2, scrypt, argon2SHA-1/2, RIPEMD-160, HMAC-SHA-2, BLAKE2b/3, ChaCha20/XChaCha20-Poly1305, AES-GCM/CBC, and password KDFs.
    Key and certificate containerspem, pkcs8, pkix, pkix_verify, ocsp, crl, cmsPEM, PKCS#8/PBES2, X.509 parsing, chain verification, revocation formats, and CMS SignedData.
    Signature and key-exchange primitivesed25519, x25519, p256, p384, p521, secp256k1, rsaEd/X25519, NIST ECDSA, secp256k1, and RSA PKCS#1 v1.5/PSS.
    JOSE, COSE, SSH, PGP, and git formatsjwt, jwe, jwk, cose, ssh, pgp, git_objectStrict parsers/verifiers for compact JOSE, COSE_Sign1, SSHSIG-style signatures, OpenPGP detached signatures, and git signed-object bytes.
    Wallet, box, and OTP protocolsbip39, bip32, hpke, naclbox, totpBIP mnemonic/HD wallet helpers, HPKE base mode, libsodium-style box, and HOTP/TOTP.
    File encryptionage_formatage v1 file decryption + deterministic encryption for X25519 recipients (X25519 + HKDF + ChaCha20-Poly1305 STREAM + Bech32); verified against the C2SP/CCTV age vectors.
    Passwordless authwebauthnWebAuthn / FIDO2 verification — assertion + attestation (packed/fido-u2f/none) with rpId/UP/UV policy enforcement, authenticatorData/COSE_Key parsing (EC2 P-256/384, Ed25519, RSA RS/PS256/384/512), clientDataJSON binding; composes cbor + p256/p384/ed25519/rsa + pkix_verify. Verified against Yubico fido2 vectors.
    Secure channelnoiseNoise Protocol Framework (25519 + ChaChaPoly + SHA256) handshake state machine — patterns NN/NK/XX/IK; verified against the flynn/noise vectors. Basis of WireGuard / Signal X3DH.
    Transporttls13TLS 1.3 (RFC 8446) client 1-RTT handshake building blocks — key schedule, record layer, handshake/message codecs, ClientHello builder, and server authentication (CertificateVerify + Finished) — wired by a one-shot client driver; verified end-to-end against RFC 8448 §3. Live ECDHE/record glue WIP.
    Sidecar toolingproofs, leakage_harnessSMT proof leaves and native sparse-vs-dense leakage measurement harnesses.

    moon test from the module root runs the full suite across every sub-package.

    #Cross-implementation interop

    The test suites include vectors borrowed from other implementations so the parsers and codecs aren't only validated against bytes we produced ourselves:

    • pkix parses the live Let's Encrypt R10 intermediate CA (PEM embedded in pkix/fixtures_test.mbt) and round-trips it byte-stable.
    • pkcs8 parses the Ed25519 PKCS#8 v1 + v2 PEM fixtures from RustCrypto/formats, including the v2 "Curdle Chairs" attribute from RFC 8410 §10.3.
    • aead, ed25519, x25519, p256, p384, p521, secp256k1, and rsa include Wycheproof or Wycheproof-derived vectors where the workspace has matching algorithm support.
    • jwt, jwe, cose, pkcs8, pbkdf2, scrypt, and hash include reference or platform-oracle tests against external implementations.
    • pkix_verify replays in-scope subsets of the C2SP/x509-limbo and Netflix BetterTLS certificate-path-validation suites (testdata/x509-limbo, testdata/bettertls, generated by scripts/gen_x509_limbo.py); the harness fails if any chain that should be rejected verifies.

    #Git commit signing

    Git's three gpg.format families are covered as verify-side building blocks:

    gpg.formatFormatModules
    sshSSHSIG-style armorgit_object + ssh + key primitives
    openpgpOpenPGP detached signature armorgit_object + pgp + hash
    x509CMS SignedData detached signaturegit_object + cms + pkix_verify

    The usual flow is:

    1. Read git cat-file commit <rev> bytes.
    2. Parse the object with @git_object.parse_signed_commit.
    3. Verify signed.signature_armor over signed.signed_content with @ssh, @pgp, or @cms.

    SSH is intentionally a conservative SSHSIG-style subset, not an OpenSSH compatibility claim. See docs/GIT-SIGNING.md for allowed_signers, OpenPGP, and X.509/CMS examples.

    #Build

    moon test # all sub-packages moon test --target all # wasm-gc + wasm + native moon test -p mizchi/experimental_crypto/asn1 # single sub-package moon bench --release -p mizchi/experimental_crypto/x25519 moon check --target all

    The native backend uses a small C stub (getrandom/getrandom_native.c) that selects arc4random_buf on macOS / *BSD, getrandom(2) on Linux, and BCryptGenRandom on Windows.

    #Performance baselines

    Run on wasm-gc, release mode, on the author's machine (moon 0.1.20260522). Reproduce with moon bench --release -pmizchi/<module>:

    OperationTimeNotes
    asn1 encode flat SEQUENCE x100~3.1 usdepth benchmarks use the enforced MAX_DEPTH=32
    asn1 decode flat SEQUENCE x100~2.2 us
    crypto_bigint 256-bit pow_mod~108-109 ussparse and dense exponent classes
    crypto_bigint 256-bit inv_mod~109-112 ussparse and dense input classes
    aead ChaCha20-Poly1305 seal 1 KiB~5.3 us
    aead AES-128-GCM seal 1 KiB~9.2 usportable 4-bit Shoup GHASH; no hardware CLMUL
    x25519 ECDH~85 us10-limb Montgomery ladder
    p256 sign~2.0 msfixed-iteration sign-side scalar path
    p384 sign~5.2 msfixed-iteration sign-side scalar path
    secp256k1 sign~2.0 msfixed-iteration sign-side scalar path
    pbkdf2 HMAC-SHA256 c=1k dkLen=32~542 us
    pbkdf2 HMAC-SHA256 c=10k dkLen=32~5.9 ms

    For comparison, dalek / RustCrypto numbers are roughly an order of magnitude faster than what's here today. The path to closing that gap is documented per-module in the file headers (mostly: avoid per-op FixedArray::make allocations, move to 5-limb radix-2^51 once MoonBit exposes a 64×64 → 128 multiply primitive, and add SIMD on the native backend where possible).

    #Known limitations

    These are intentional and called out in the source where they apply:

    • Not constant-time end-to-end. crypto_bigint, RSA private modexp, and ECDSA sign-side scalar multiplication mostly use fixed-limb / fixed-iteration paths, Linux-native leakage smoke gates, and loose JS / wasm-gc / wasm backend smoke checks, but this is still not a constant-clock proof. P-521 sign-side paths are wired into the leakage harness but still need repeated calibrated evidence before a measured-candidate claim. See docs/CONSTANT_TIME.md.
    • Partial protocol coverage. TLS 1.3, PKCS#12, Ed448 / X448, ML-KEM / ML-DSA, AES-GCM-SIV / AES-SIV, age, and EIP-712 / EIP-191 are not implemented.
    • Revocation scope is conservative. OCSP and CRL parsing / verification exist, but unsupported delta / indirect / distribution-point semantics are rejected fail-closed rather than silently applied.
    • No GHASH carryless-multiplication intrinsic. The gcm module uses a portable 4-bit Shoup table, not hardware CLMUL / SIMD.

    #License

    Apache-2.0. Some sub-package directories still carry their own LICENSE file (a leftover from when each was a separate moon new module); the module as a whole is Apache-2.0.

    #Layout

    . ├── moon.mod # single module manifest (mizchi/experimental_crypto) ├── README.md # this file ├── .gitignore └── <subpkg>/ ├── moon.pkg # package imports, native stubs, target maps ├── <subpkg>.mbt # main source ├── <subpkg>_test.mbt # blackbox tests ├── <subpkg>_wbtest.mbt # whitebox tests (where useful) └── pkg.generated.mbti # public API snapshot, regenerated by `moon info`

    Sub-packages depend on each other by path in their moon.pkg (import { "mizchi/experimental_crypto/<dep>" }); the import alias is the last path segment, so @asn1, @pkix, … keep working unchanged. Because everything is one module, there are no per-package moon.mod version pins anymore — only the one external dependency (moonbitlang/x) is declared, in the root moon.mod.

    #Security Disclaimer ⚠️

    This implementation of these cryptographic algorithms is provided without any security endorsement or professional certification. The experimental_crypto project should be considered:

    • An educational reference implementation
    • Experimental cryptography software
    • Not reviewed by third-party security experts

    #What review has happened

    This is internal review only — it does not substitute for a professional audit:

    • Negative test corpus. Each parser / verifier ships ATTACK … tests that pin reject behaviour (signature forgery, DER parser confusion, JWT algorithm confusion, CMS content-swap, padding edge cases). The X.509 path verifier is swept against the x509-limbo corpus (scripts/gen_x509_limbo.py in CI, scripts/audit_x509_limbo.py for the full ~2200-case one-shot) and every accepted reject case is documented as out-of-scope-by-design, with zero known false positives.
    • Verification-bypass review. RSA PKCS#1 v1.5 verify is encode-then-compare (no DigestInfo parser to fool); ECDSA rejects r,s ∉ [1,n-1]; Ed25519 enforces canonical S; JWT binds alg to the key type and has no alg=none path; the PKIX chain validator is fail-closed (every failure raises, the only success is falling through the whole pipeline). AEAD tags are compared in constant time and plaintext is withheld until the tag verifies.

    #Before you use any of this in a real system

    1. Read the source for the specific module and confirm it meets your threat model — side-channel / timing resistance is not certified (see Known limitations and docs/CONSTANT_TIME.md).
    2. Prefer a vetted library (RustCrypto, dalek, BoringSSL, …) wherever one exists for your protocol.
    3. Commission an independent audit before depending on it for anything that protects keys, identities, or user data.