From 30208e790d593df612bc8423c8559adf91a77af2 Mon Sep 17 00:00:00 2001 From: Jamie Newton <33573418+newtsjamie@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:40:27 +0000 Subject: [PATCH 1/7] Add ProofA P-384 v2 variant for leaves signed with ecdsa-with-SHA384 cert_binding gains walk_tbs, read_p256_spki, assert_sig_alg and SHA-384/SHA-512 TBS hashing (zkpassport/sha512 v0.1.1, already a transitive dependency of noir_rsa). bind_leaf_cert is unchanged, so the existing v2 circuits compile to identical bytecode. proof_a_ecdsa_p384_sha384_v2 hashes the leaf TBS with SHA-384 in-circuit, requires the TBS signature algorithm to be ecdsa-with-SHA384, and keeps the 52-value public layout of proof_a_ecdsa_p384_v2. Tests use a synthetic P-384/SHA-384 chain, with tampered-key, tampered-date and wrong-algorithm negatives. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + cert_binding/Nargo.toml | 4 +- cert_binding/src/lib.nr | 158 ++- cert_binding/src/synthetic_vectors.nr | 17 + proof_a_ecdsa_p384_sha384_v2/Nargo.toml | 16 + .../src/crypto/mod.nr | 1 + .../noir_bigcurve_vendor/VENDORED_FROM.md | 21 + .../crypto/noir_bigcurve_vendor/curve_jac.nr | 717 +++++++++++ .../crypto/noir_bigcurve_vendor/curves/mod.nr | 1 + .../noir_bigcurve_vendor/curves/secp384r1.nr | 142 +++ .../src/crypto/noir_bigcurve_vendor/mod.nr | 1087 +++++++++++++++++ .../noir_bigcurve_vendor/scalar_field.nr | 416 +++++++ .../src/crypto/noir_bigcurve_vendor/utils.nr | 2 + .../utils/derive_offset_generators.nr | 169 +++ .../utils/hash_to_curve.nr | 90 ++ .../src/crypto_utils.nr | 61 + .../src/hash_chain.nr | 549 +++++++++ proof_a_ecdsa_p384_sha384_v2/src/main.nr | 582 +++++++++ 18 files changed, 4032 insertions(+), 2 deletions(-) create mode 100644 cert_binding/src/synthetic_vectors.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/Nargo.toml create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/mod.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/VENDORED_FROM.md create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curve_jac.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curves/mod.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curves/secp384r1.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/mod.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/scalar_field.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils/derive_offset_generators.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils/hash_to_curve.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/crypto_utils.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/hash_chain.nr create mode 100644 proof_a_ecdsa_p384_sha384_v2/src/main.nr diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 31ccaec..79e3828 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,7 @@ jobs: - cert_binding - proof_a_ecdsa_p256_v2 - proof_a_ecdsa_p384_v2 + - proof_a_ecdsa_p384_sha384_v2 - proof_b_es256_v2_core - proof_b_es256_v2 - proof_b_es256_v2_large diff --git a/cert_binding/Nargo.toml b/cert_binding/Nargo.toml index 8eedeaf..fd2dce9 100644 --- a/cert_binding/Nargo.toml +++ b/cert_binding/Nargo.toml @@ -3,7 +3,9 @@ name = "cert_binding" type = "lib" authors = ["Apertrue"] compiler_version = ">=1.0.0" -description = "Binds a leaf P-256 key and validity dates to the SHA-256 of a DER TBSCertificate" +description = "Binds a leaf key and validity dates to the hash (SHA-256/384/512) of a DER TBSCertificate" [dependencies] sha256 = { tag = "v0.3.0", git = "https://github.com/noir-lang/sha256" } +# SHA-384 / SHA-512 for issuers that sign with ecdsa-with-SHA384/512 +sha512 = { tag = "v0.1.1", git = "https://github.com/zkpassport/sha512" } diff --git a/cert_binding/src/lib.nr b/cert_binding/src/lib.nr index 6e9a58e..df857d0 100644 --- a/cert_binding/src/lib.nr +++ b/cert_binding/src/lib.nr @@ -29,8 +29,10 @@ /// - Dates before 1970-01-01 are rejected (unix time is unsigned here). use dep::sha256::sha256_var; +use dep::sha512::{sha384::sha384_var, sha512::sha512_var}; pub mod test_vectors; +pub mod synthetic_vectors; /// Uncompressed P-256 SubjectPublicKeyInfo header (27 bytes), followed by /// X (32 bytes) and Y (32 bytes). @@ -132,7 +134,135 @@ fn read_time(tbs: [u8; N], tbs_len: u32, p: u32) -> (u64, u32) { (days * 86400 + hour * 3600 + minute * 60 + second, end) } +/// Field locations found by walking a DER TBSCertificate from offset 0. +/// All offsets are derived from the DER; none are prover-supplied. +pub struct TbsWalk { + /// Content of the TBS `signature` AlgorithmIdentifier: [sig_alg_start, sig_alg_end) + pub sig_alg_start: u32, + pub sig_alg_end: u32, + /// First byte of subjectPublicKeyInfo + pub spki_start: u32, + pub not_before: u64, + pub not_after: u64, +} + +/// Walk a DER TBSCertificate from offset 0 up to subjectPublicKeyInfo. +/// Does not hash; the caller must hash tbs[0..tbs_len] and use that digest +/// as the message of the issuer signature check. +pub fn walk_tbs(tbs: [u8; N], tbs_len: u32) -> TbsWalk { + assert(tbs_len <= N, "tbs_len exceeds buffer"); + + // Outer SEQUENCE must cover exactly tbs_len bytes. + let (body, outer_end) = read_tlv(tbs, tbs_len, 0, 0x30); + assert(outer_end == tbs_len, "DER: TBS SEQUENCE does not span tbs_len"); + + // Optional [0] EXPLICIT version. + let mut p = body; + if tbs[p] == 0xa0 { + let (_, e) = read_tlv(tbs, tbs_len, p, 0xa0); + p = e; + } + // serialNumber, signature AlgorithmIdentifier, issuer + let (_, e1) = read_tlv(tbs, tbs_len, p, 0x02); + let (sig_alg_start, e2) = read_tlv(tbs, tbs_len, e1, 0x30); + let (_, e3) = read_tlv(tbs, tbs_len, e2, 0x30); + + // validity + let (vs, ve) = read_tlv(tbs, tbs_len, e3, 0x30); + let (not_before, t1) = read_time(tbs, tbs_len, vs); + let (not_after, t2) = read_time(tbs, tbs_len, t1); + assert(t2 == ve, "DER: Validity length mismatch"); + + // subject + let (_, e5) = read_tlv(tbs, tbs_len, ve, 0x30); + + TbsWalk { sig_alg_start, sig_alg_end: e2, spki_start: e5, not_before, not_after } +} + +/// Read an uncompressed P-256 SubjectPublicKeyInfo at spki_start. +pub fn read_p256_spki(tbs: [u8; N], tbs_len: u32, spki_start: u32) -> ([u8; 32], [u8; 32]) { + assert(spki_start + 91 <= tbs_len, "SPKI exceeds tbs_len"); + for i in 0..27 { + assert(tbs[spki_start + i] == SPKI_P256_PREFIX[i], "SPKI is not uncompressed P-256"); + } + let mut pubkey_x: [u8; 32] = [0; 32]; + let mut pubkey_y: [u8; 32] = [0; 32]; + for i in 0..32 { + pubkey_x[i] = tbs[spki_start + 27 + i]; + pubkey_y[i] = tbs[spki_start + 59 + i]; + } + (pubkey_x, pubkey_y) +} + +/// Assert that the TBS `signature` AlgorithmIdentifier content is exactly +/// `expected` (the DER bytes inside the AlgorithmIdentifier SEQUENCE). +pub fn assert_sig_alg(tbs: [u8; N], w: TbsWalk, expected: [u8; K]) { + assert(w.sig_alg_end - w.sig_alg_start == K, "TBS signature algorithm mismatch"); + for i in 0..K { + assert(tbs[w.sig_alg_start + i] == expected[i], "TBS signature algorithm mismatch"); + } +} + +/// DER content of AlgorithmIdentifier for ecdsa-with-SHA256/384/512 +/// (OID 1.2.840.10045.4.3.2/3/4, parameters absent). +pub global ALG_ECDSA_SHA256: [u8; 10] = [0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02]; +pub global ALG_ECDSA_SHA384: [u8; 10] = [0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03]; +pub global ALG_ECDSA_SHA512: [u8; 10] = [0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x04]; + +/// SHA-384 of tbs[0..tbs_len]. Bytes past tbs_len are zeroed by +/// BoundedVec::from_parts, so prover padding cannot affect the digest. +pub fn tbs_sha384(tbs: [u8; N], tbs_len: u32) -> [u8; 48] { + sha384_var(BoundedVec::from_parts(tbs, tbs_len)) +} + +/// SHA-512 of tbs[0..tbs_len] (same padding rule as tbs_sha384). +pub fn tbs_sha512(tbs: [u8; N], tbs_len: u32) -> [u8; 64] { + sha512_var(BoundedVec::from_parts(tbs, tbs_len)) +} + +/// A P-256 leaf whose issuer signed with ecdsa-with-SHA384. +pub struct LeafCertSha384 { + pub sha384: [u8; 48], + pub pubkey_x: [u8; 32], + pub pubkey_y: [u8; 32], + pub not_before: u64, + pub not_after: u64, +} + +/// A P-256 leaf whose issuer signed with ecdsa-with-SHA512. +pub struct LeafCertSha512 { + pub sha512: [u8; 64], + pub pubkey_x: [u8; 32], + pub pubkey_y: [u8; 32], + pub not_before: u64, + pub not_after: u64, +} + +/// Hash (SHA-384) and parse a DER TBSCertificate whose subject key is P-256 +/// and whose TBS signature algorithm is ecdsa-with-SHA384. +pub fn bind_leaf_cert_sha384(tbs: [u8; N], tbs_len: u32) -> LeafCertSha384 { + assert(tbs_len <= N, "tbs_len exceeds buffer"); + let sha384 = tbs_sha384(tbs, tbs_len); + let w = walk_tbs(tbs, tbs_len); + assert_sig_alg(tbs, w, ALG_ECDSA_SHA384); + let (pubkey_x, pubkey_y) = read_p256_spki(tbs, tbs_len, w.spki_start); + LeafCertSha384 { sha384, pubkey_x, pubkey_y, not_before: w.not_before, not_after: w.not_after } +} + +/// Hash (SHA-512) and parse a DER TBSCertificate whose subject key is P-256 +/// and whose TBS signature algorithm is ecdsa-with-SHA512. +pub fn bind_leaf_cert_sha512(tbs: [u8; N], tbs_len: u32) -> LeafCertSha512 { + assert(tbs_len <= N, "tbs_len exceeds buffer"); + let sha512 = tbs_sha512(tbs, tbs_len); + let w = walk_tbs(tbs, tbs_len); + assert_sig_alg(tbs, w, ALG_ECDSA_SHA512); + let (pubkey_x, pubkey_y) = read_p256_spki(tbs, tbs_len, w.spki_start); + LeafCertSha512 { sha512, pubkey_x, pubkey_y, not_before: w.not_before, not_after: w.not_after } +} + /// Hash and parse a DER TBSCertificate whose subject key is P-256. +/// This body is kept as originally written (rather than calling walk_tbs) +/// so the compiled v2 circuits, and their verification keys, do not change. pub fn bind_leaf_cert(tbs: [u8; N], tbs_len: u32) -> LeafCert { assert(tbs_len <= N, "tbs_len exceeds buffer"); let sha256: [u8; 32] = sha256_var(tbs, tbs_len); @@ -181,8 +311,9 @@ pub fn bind_leaf_cert(tbs: [u8; N], tbs_len: u32) -> LeafCert { // ==================================================================== mod tests { - use super::{bind_leaf_cert, days_from_civil, LeafCert}; + use super::{bind_leaf_cert, bind_leaf_cert_sha384, days_from_civil, LeafCert}; use super::test_vectors as tv; + use super::synthetic_vectors as sv; global BUF: u32 = 1280; @@ -361,4 +492,29 @@ mod tests { t[off + 22] = 0x22; let _ = bind_leaf_cert(t, tv::SAMSUNG_LEAF_TBS_LEN); } + + #[test] + fn test_sha384_leaf_binds() { + let c = bind_leaf_cert_sha384(pad(sv::SYN_P384_SHA384_LEAF_TBS), sv::SYN_P384_SHA384_LEAF_TBS_LEN); + assert(c.sha384 == sv::SYN_P384_SHA384_LEAF_SHA384, "sha384 mismatch"); + assert(c.pubkey_x == sv::SYN_P384_SHA384_LEAF_PUB_X); + assert(c.pubkey_y == sv::SYN_P384_SHA384_LEAF_PUB_Y); + assert(c.not_before == sv::SYN_P384_SHA384_LEAF_NOT_BEFORE); + assert(c.not_after == sv::SYN_P384_SHA384_LEAF_NOT_AFTER); + } + + #[test] + fn test_sha384_padding_does_not_affect_hash() { + let mut t = pad(sv::SYN_P384_SHA384_LEAF_TBS); + t[sv::SYN_P384_SHA384_LEAF_TBS_LEN] = 0xff; + t[1279] = 0x01; + let c = bind_leaf_cert_sha384(t, sv::SYN_P384_SHA384_LEAF_TBS_LEN); + assert(c.sha384 == sv::SYN_P384_SHA384_LEAF_SHA384); + } + + #[test(should_fail_with = "TBS signature algorithm mismatch")] + fn test_sha384_rejects_sha256_signed_leaf() { + // Samsung leaf is signed ecdsa-with-SHA256; the SHA-384 path must refuse it. + let _ = bind_leaf_cert_sha384(pad(tv::SAMSUNG_LEAF_TBS), tv::SAMSUNG_LEAF_TBS_LEN); + } } diff --git a/cert_binding/src/synthetic_vectors.nr b/cert_binding/src/synthetic_vectors.nr new file mode 100644 index 0000000..3ddf755 --- /dev/null +++ b/cert_binding/src/synthetic_vectors.nr @@ -0,0 +1,17 @@ +// Synthetic test certificates (not from real devices), generated with the +// Python cryptography package for algorithm paths that have no public C2PA +// sample here. Keys were random and discarded. + +// O=Apertrue Test, CN=Test P-256 Leaf; issuer CN=Test P-384 SHA-384 CA; +// signed ecdsa-with-SHA384. +pub global SYN_P384_SHA384_LEAF_TBS_LEN: u32 = 282; +pub global SYN_P384_SHA384_LEAF_TBS: [u8; 282] = [0x30, 0x82, 0x01, 0x16, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03, 0x30, 0x38, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0d, 0x41, 0x70, 0x65, 0x72, 0x74, 0x72, 0x75, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x31, 0x1e, 0x30, 0x1c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x15, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x2d, 0x33, 0x38, 0x34, 0x20, 0x53, 0x48, 0x41, 0x2d, 0x33, 0x38, 0x34, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x35, 0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x30, 0x34, 0x30, 0x35, 0x5a, 0x17, 0x0d, 0x33, 0x35, 0x30, 0x36, 0x30, 0x37, 0x30, 0x38, 0x30, 0x39, 0x31, 0x30, 0x5a, 0x30, 0x32, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0d, 0x41, 0x70, 0x65, 0x72, 0x74, 0x72, 0x75, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x31, 0x18, 0x30, 0x16, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0f, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x2d, 0x32, 0x35, 0x36, 0x20, 0x4c, 0x65, 0x61, 0x66, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x5c, 0xfe, 0xbd, 0xa2, 0x26, 0x0b, 0xaa, 0x14, 0xb0, 0xd3, 0xbf, 0x29, 0xa7, 0xee, 0xa1, 0xee, 0x5b, 0x37, 0x17, 0x69, 0x1a, 0x03, 0x46, 0x21, 0xbe, 0x87, 0x63, 0xbf, 0xcd, 0x65, 0xf3, 0x77, 0x34, 0x15, 0x9a, 0x82, 0x0e, 0x6e, 0x94, 0x1a, 0xaf, 0xac, 0x2a, 0xe7, 0x0d, 0x0b, 0x4e, 0xfd, 0x9e, 0x94, 0x7b, 0xfe, 0xc1, 0xbf, 0x8c, 0x2f, 0x2f, 0xf4, 0x29, 0x6c, 0x77, 0xb0, 0x08, 0xeb, 0xa3, 0x10, 0x30, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00]; +pub global SYN_P384_SHA384_LEAF_SHA384: [u8; 48] = [0x9e, 0x12, 0x55, 0x3c, 0x32, 0x91, 0xb3, 0xfc, 0x1e, 0x0d, 0x0a, 0xc8, 0x03, 0x9f, 0x2a, 0xa2, 0x2a, 0xb8, 0xfd, 0x8e, 0x85, 0xde, 0xab, 0xf1, 0x39, 0x43, 0x1d, 0x68, 0x54, 0x41, 0x74, 0x5c, 0x20, 0xdb, 0xc6, 0xba, 0xfc, 0x48, 0x23, 0x74, 0x89, 0x51, 0x2e, 0x48, 0xf6, 0x9a, 0xb9, 0x0c]; +pub global SYN_P384_SHA384_LEAF_NOT_BEFORE: u64 = 1735787045; +pub global SYN_P384_SHA384_LEAF_NOT_AFTER: u64 = 2064816550; +pub global SYN_P384_SHA384_LEAF_PUB_X: [u8; 32] = [0x5c, 0xfe, 0xbd, 0xa2, 0x26, 0x0b, 0xaa, 0x14, 0xb0, 0xd3, 0xbf, 0x29, 0xa7, 0xee, 0xa1, 0xee, 0x5b, 0x37, 0x17, 0x69, 0x1a, 0x03, 0x46, 0x21, 0xbe, 0x87, 0x63, 0xbf, 0xcd, 0x65, 0xf3, 0x77]; +pub global SYN_P384_SHA384_LEAF_PUB_Y: [u8; 32] = [0x34, 0x15, 0x9a, 0x82, 0x0e, 0x6e, 0x94, 0x1a, 0xaf, 0xac, 0x2a, 0xe7, 0x0d, 0x0b, 0x4e, 0xfd, 0x9e, 0x94, 0x7b, 0xfe, 0xc1, 0xbf, 0x8c, 0x2f, 0x2f, 0xf4, 0x29, 0x6c, 0x77, 0xb0, 0x08, 0xeb]; +pub global SYN_P384_SHA384_LEAF_ISSUER_X: [u8; 48] = [0xda, 0x99, 0x90, 0x1b, 0xfa, 0x6e, 0x93, 0x28, 0xfc, 0x77, 0xcf, 0x9d, 0xf5, 0x32, 0x65, 0x1d, 0x68, 0x59, 0x3a, 0xe7, 0x39, 0x69, 0x55, 0x52, 0x00, 0x43, 0x02, 0xbd, 0xf6, 0x29, 0x33, 0xa7, 0xb6, 0xf3, 0x99, 0x52, 0xa1, 0x41, 0x8f, 0x19, 0xf4, 0x9d, 0x72, 0xca, 0x34, 0xbc, 0x11, 0xe7]; +pub global SYN_P384_SHA384_LEAF_ISSUER_Y: [u8; 48] = [0x78, 0x27, 0x2c, 0xff, 0x78, 0x34, 0x02, 0x87, 0xe4, 0xea, 0x5d, 0x86, 0x4c, 0x4b, 0xc3, 0x12, 0xe4, 0x41, 0xaf, 0xb8, 0x53, 0x48, 0x5a, 0x1a, 0xdc, 0x11, 0x92, 0x21, 0xf7, 0x07, 0x06, 0xc0, 0xfb, 0xf3, 0x4f, 0xff, 0xf0, 0x45, 0x03, 0x6f, 0xc4, 0x9a, 0x61, 0xf0, 0x9f, 0x6b, 0xc9, 0x3c]; +pub global SYN_P384_SHA384_LEAF_SIG_R: [u8; 48] = [0x16, 0x22, 0xce, 0xce, 0xcb, 0xd3, 0x67, 0x9e, 0x3c, 0xd8, 0x10, 0xc3, 0x64, 0x9b, 0xdc, 0x43, 0x07, 0x79, 0x3a, 0xf0, 0x3c, 0x9c, 0x62, 0xe0, 0xd2, 0x80, 0x22, 0x75, 0xf4, 0xf3, 0xa0, 0xdf, 0x83, 0xdf, 0xfa, 0xc5, 0x21, 0x99, 0xa2, 0xbf, 0x7f, 0x65, 0x04, 0x39, 0x0c, 0x6d, 0xd7, 0x60]; +pub global SYN_P384_SHA384_LEAF_SIG_S: [u8; 48] = [0x47, 0x10, 0x9e, 0x2f, 0x2b, 0x3f, 0x6b, 0x6f, 0xb0, 0x10, 0x98, 0x4e, 0xb0, 0xe7, 0x3a, 0xf3, 0xc5, 0x7c, 0xb3, 0xf0, 0x1d, 0xa1, 0x20, 0xe0, 0x5d, 0x13, 0x0f, 0xf8, 0x8f, 0xcc, 0x24, 0x2c, 0xd2, 0xdf, 0x3a, 0xd7, 0x4d, 0x2d, 0x9a, 0xf7, 0xa3, 0xda, 0xc5, 0xc0, 0xd9, 0x0f, 0x05, 0x17]; diff --git a/proof_a_ecdsa_p384_sha384_v2/Nargo.toml b/proof_a_ecdsa_p384_sha384_v2/Nargo.toml new file mode 100644 index 0000000..5459c2a --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/Nargo.toml @@ -0,0 +1,16 @@ +[package] +name = "apertrue_proof_a_ecdsa_p384_sha384_v2" +type = "bin" +authors = ["Apertrue"] +compiler_version = ">=1.0.0" +description = "ProofA ECDSA P-384 SHA-384 v2: P-256 leaf key and validity bound to the TBS signed (ecdsa-with-SHA384) by a P-384 intermediate" + +[dependencies] +# Leaf TBSCertificate hashing and DER walk +cert_binding = { path = "../cert_binding" } +# P-384 uses bignum for field operations (via vendored noir_bigcurve) +bignum = { tag = "v0.9.2", git = "https://github.com/noir-lang/noir-bignum" } +# SHA-256 for hash chain verification +sha256 = { tag = "v0.3.0", git = "https://github.com/noir-lang/sha256" } +# Poseidon for commitment schemes +poseidon = { tag = "v0.1.1", git = "https://github.com/noir-lang/poseidon" } diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/mod.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto/mod.nr new file mode 100644 index 0000000..8808c8b --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/mod.nr @@ -0,0 +1 @@ +pub mod noir_bigcurve_vendor; diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/VENDORED_FROM.md b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/VENDORED_FROM.md new file mode 100644 index 0000000..3cf56b5 --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/VENDORED_FROM.md @@ -0,0 +1,21 @@ +# Vendored Library: noir_bigcurve + +## Source +- **Repository**: https://github.com/noir-lang/noir_bigcurve +- **Tag**: v0.12.0 +- **Commit**: 99ec9b0e2acf81e36bbc8362c9cf94ddb028bb55 +- **Date Vendored**: 2026-01-15 + +## License +MIT License (see original repository) + +## Purpose +Provides generic elliptic curve arithmetic (point add, double, scalar mul) for ECDSA verification on arbitrary curves including secp384r1 (P-384). + +## Modifications +- Extracted core files only (lib.nr, curve_jac.nr, scalar_field.nr) +- Added P-384 curve parameters in p384.nr +- Removed test_data.nr (large file not needed for production) + +## Dependencies +- noir-bignum v0.8.2 (compatible with project's existing noir-bignum@v0.8.0) diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curve_jac.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curve_jac.nr new file mode 100644 index 0000000..d1ed91d --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curve_jac.nr @@ -0,0 +1,717 @@ +use dep::bignum::BigNum; + +use crate::crypto::noir_bigcurve_vendor::scalar_field::ScalarField; +use super::BigCurve; + +/// CurveJ represents a Short Weierstrass elliptic curve using Jacobian coordinates. +/// +/// # Representation +/// - **Jacobian form:** (X, Y, Z) +/// - **Affine form:** (x, y) +/// - **Relation:** x = X / Z^2, y = Y / Z^3 +/// +/// # Purpose +/// This class is designed to speed up witness generation when optimally constraining elliptic curve operations. +/// +/// # Motivation +/// - Constraints are best constructed in affine coordinates due to fewer field multiplications (3 vs ~14 for Jacobian). +/// - However, affine coordinates require one modular inverse per group operation, which is expensive over a non-native field (~2D multiplications, where D is the field bit-width). +/// +/// # Solution +/// - Perform all computations in unconstrained functions using Jacobian coordinates (no inverses required). +/// - Record each ECC operation in a `JTranscript` object. +/// - Use a Montgomery Batch Inverse to compute all required inverses at once when evaluating with affine arithmetic. +/// - This reduces the number of modular inverses from ~256 or 320 (depending on the curve) to just one. +/// +/// # Note +/// This approach is complex but necessary due to the high cost of generating modular inverses for witness generation. +pub struct CurveJ { + pub(crate) x: B, + pub(crate) y: B, + pub(crate) z: B, + pub(crate) is_infinity: bool, +} + +/// A transcript of a group operation in Jacobian coordinates. +/// +/// # Fields +/// - `x3`, `y3`, `z3`: The output coordinates of the group operation in Jacobian form. +/// - `lambda_numerator`: The numerator of the `lambda` term used in the group operation. +/// (The denominator is assumed to be `z3`.) +pub struct JTranscript { + pub(crate) lambda_numerator: B, + pub(crate) x3: B, + pub(crate) y3: B, + pub(crate) z3: B, +} + +impl JTranscript +where + B: BigNum, +{ + unconstrained fn new() -> Self { + JTranscript { lambda_numerator: B::zero(), x3: B::zero(), y3: B::zero(), z3: B::zero() } + } +} + +/// A transcript of a group operation in Affine coordinates. +/// +/// # Fields +/// - `x3`, `y3`: The output coordinates of the group operation. +/// - `lambda`: The gradient of the line that passes through the input points of the group operation. +/// +/// # Details +/// - For addition: `lambda = (y2 - y1) / (x2 - x1)` +/// - For doubling: `lambda = (3 * x1 * x1) / (2 * y1)` +/// +/// # Optimization +/// If you have an array of `JTranscript` objects, you can convert them into `AffineTranscript` objects using only one modular inverse. +pub struct AffineTranscript { + pub(crate) lambda: B, + pub(crate) x3: B, + pub(crate) y3: B, +} + +impl AffineTranscript +where + B: BigNum, +{ + pub(crate) fn new() -> Self { + AffineTranscript { lambda: B::zero(), x3: B::zero(), y3: B::zero() } + } + + pub(crate) unconstrained fn from_j(j_tx: JTranscript) -> Self { + AffineTranscript::from_jacobian_transcript([j_tx])[0] + } + + pub unconstrained fn from_j_with_hint(j_tx: JTranscript, inverse: B) -> AffineTranscript { + let z_inv = inverse; + let zz = z_inv.__mul(z_inv); + let zzz = zz.__mul(z_inv); + let lambda = j_tx.lambda_numerator.__mul(z_inv); + let x3 = j_tx.x3.__mul(zz); + let y3 = j_tx.y3.__mul(zzz); + AffineTranscript { x3, y3, lambda } + } + + unconstrained fn from_jacobian_transcript( + j_tx: [JTranscript; NumEntries], + ) -> [AffineTranscript; NumEntries] { + let mut result: [AffineTranscript; NumEntries] = [AffineTranscript::new(); NumEntries]; + + let mut inverses: [B; NumEntries] = [B::zero(); NumEntries]; + for i in 0..j_tx.len() { + inverses[i] = j_tx[i].z3; + } + + // tadaa + let inverses: [B; NumEntries] = dep::bignum::bignum::batch_invert(inverses); + + for i in 0..j_tx.len() { + let z_inv = inverses[i]; + let zz = z_inv.__mul(z_inv); + let zzz = zz.__mul(z_inv); + let lambda = j_tx[i].lambda_numerator.__mul(z_inv); + let x3 = j_tx[i].x3.__mul(zz); + let y3 = j_tx[i].y3.__mul(zzz); + result[i] = AffineTranscript { lambda, x3, y3 }; + } + result + } +} + +/// A lookup table used for scalar multiplications using windowed non-adjacent form (WNAF). +/// +/// The scalar multiplier is sliced into 4-bit chunks, each represented in WNAF (values in the range [-15, -13, ..., 15]). +/// A table `T` is computed containing point multiples corresponding to these 4-bit WNAF values: `T = ([-15[P], -13[P], ..., 15[P]])`. +/// +/// The accumulator is initialized with `T[most significant WNAF slice]`. +/// For each remaining slice (starting from the most significant), the accumulator is doubled 4 times, +/// then `T[slice[i]]` is added to the accumulator. +/// +/// For small multiscalar multiplications (fewer than 512 points), this approach minimizes the number of addition operations. +pub struct PointTable { + x: [B; 16], + y: [B; 16], + z: [B; 16], + pub(crate) transcript: [JTranscript; 8], +} + +impl PointTable +where + B: BigNum, +{ + pub(crate) fn empty() -> Self { + PointTable { + x: [B::zero(); 16], + y: [B::zero(); 16], + z: [B::zero(); 16], + // Safety: efficient transcript init + transcript: [unsafe { JTranscript::new() }; 8], + } + } + /** + * @brief make a new PointTable from an input point + * @description we use "windowed non-adjacent form" representation + * to reduce the number of group operations required for the table + * [-15P, -13P, ..., 15P] requires 8 group operations + * [0, P, ..., 15P] requires 14 group operations. + * group operations are expensive! + **/ + pub(crate) unconstrained fn new(P: CurveJ) -> Self + where + Curve: BigCurve, + { + let mut result = PointTable { + x: [B::zero(); 16], + y: [B::zero(); 16], + z: [B::zero(); 16], + transcript: [JTranscript::new(); 8], + }; + let op = P.dbl(); + let D2 = op.0; + + result.transcript[0] = op.1; + result.x[7] = P.x; + result.y[7] = P.y.__neg(); + result.z[7] = P.z; + result.x[8] = P.x; + result.y[8] = P.y; + result.z[8] = P.z; + let mut A = P; + for i in 1..8 { + let op = D2.incomplete_add(A); + A = op.0; + result.transcript[i] = op.1; + result.x[8 + i] = A.x; + result.y[8 + i] = A.y; + result.z[8 + i] = A.z; + result.x[7 - i] = A.x; + result.y[7 - i] = A.y.__neg(); + result.z[7 - i] = A.z; + } + + result + } + + /** + * @brief get a value out of the lookup table + **/ + pub(crate) unconstrained fn get(self, idx: u32) -> CurveJ { + CurveJ { x: self.x[idx], y: self.y[idx], z: self.z[idx], is_infinity: false } + } +} + +/** + * @brief construct from BigCurve + **/ +impl std::convert::From for CurveJ +where + B: BigNum, + Curve: BigCurve, +{ + fn from(affine_point: Curve) -> Self { + CurveJ { + x: affine_point.x(), + y: affine_point.y(), + z: B::one(), + is_infinity: affine_point.is_infinity(), + } + } +} + +/** + * @brief are two Jacobian points equal? + * @description only really used in tests for now. + **/ +impl std::cmp::Eq for CurveJ +where + B: BigNum, + Curve: BigCurve, +{ + fn eq(self, other: Self) -> bool { + // if x == y then (X1 / Z1 * Z1 = X2 / Z2 * Z2) + // and (Y1 / Z1 * Z1 * Z1 = Y2 / Z2 * Z2 * Z2) + let mut points_equal = false; + // Safety: efficient comparison + unsafe { + // we can check this by validating that: + // X1 * Z2 * Z2 == X2 * Z1 * Z1 + // Y1 * Z2 * Z2 * Z2 == Y2 * Z1 * Z1 * Z1 + let z1 = self.z; + let z2 = other.z; + let z1z1 = z1.__mul(z1); + let z1z1z1 = z1z1.__mul(z1); + let z2z2 = z2.__mul(z2); + let z2z2z2 = z2z2.__mul(z2); + + let x_lhs = self.x.__mul(z2z2); + let x_rhs = other.x.__mul(z1z1); + let y_lhs = self.y.__mul(z2z2z2); + let y_rhs = other.y.__mul(z1z1z1); + let lhs_infinity = self.is_infinity; + let rhs_infinity = other.is_infinity; + let both_not_infinity = !(lhs_infinity & rhs_infinity); + let both_infinity = !both_not_infinity; + + points_equal = (x_lhs.eq(x_rhs) & y_lhs.eq(y_rhs)) & both_not_infinity; + points_equal = points_equal | both_infinity; + } + points_equal + } +} + +impl CurveJ +where + B: BigNum, + Curve: BigCurve, +{ + /** + * @brief negate a point + **/ + pub(crate) fn neg(self) -> Self { + CurveJ { x: self.x, y: self.y.neg(), z: self.z, is_infinity: self.is_infinity } + } + + pub(crate) unconstrained fn new() -> Self { + CurveJ { x: B::zero(), y: B::zero(), z: B::zero(), is_infinity: false } + } + + pub(crate) unconstrained fn point_at_infinity() -> Self { + CurveJ { x: B::zero(), y: B::zero(), z: B::zero(), is_infinity: true } + } + + pub(crate) unconstrained fn sub(self, p2: Self) -> (Self, JTranscript) { + self.add(p2.neg()) + } + + pub(crate) unconstrained fn add(self, p2: Self) -> (Self, JTranscript) { + let X1 = self.x; + let X2 = p2.x; + let Y1 = self.y; + let Y2 = p2.y; + let Z1 = self.z; + let Z2 = p2.z; + let Z2Z2 = Z2.__mul(Z2); + let Z1Z1 = Z1.__mul(Z1); + let Z2Z2Z2 = Z2Z2.__mul(Z2); + let Z1Z1Z1 = Z1Z1.__mul(Z1); + let U1 = X1.__mul(Z2Z2); + let U2 = X2.__mul(Z1Z1); + let S1 = Y1.__mul(Z2Z2Z2); + let S2 = Y2.__mul(Z1Z1Z1); + // let R = S2.__submod(S1); + // x1*z2*z2 == x2*z1*z1 => U2 == U2 + let x_equal_predicate = U2.eq(U1); + let y_equal_predicate = S2.eq(S1); + let lhs_infinity = self.is_infinity; + let rhs_infinity = p2.is_infinity; + + let double_predicate = + x_equal_predicate & y_equal_predicate & !lhs_infinity & !rhs_infinity; + let add_predicate = !x_equal_predicate & !lhs_infinity & !rhs_infinity; + let infinity_predicate = + (x_equal_predicate & !y_equal_predicate) | (lhs_infinity & rhs_infinity); + let mut result: (Self, JTranscript) = (CurveJ::new(), JTranscript::new()); + if (double_predicate) { + result = self.dbl(); + } else if (add_predicate) { + result = self.incomplete_add(p2); + } else if (infinity_predicate) { + result = (CurveJ::point_at_infinity(), JTranscript::new()); + } else if (lhs_infinity & !rhs_infinity) { + let new_transcript = + JTranscript { x3: p2.x, y3: p2.y, z3: p2.z, lambda_numerator: B::zero() }; + result = (p2, new_transcript); + } else if (rhs_infinity & !lhs_infinity) { + let new_transcript = + JTranscript { x3: self.x, y3: self.y, z3: self.z, lambda_numerator: B::zero() }; + result = (self, new_transcript); + } + result + // let (_, PP): (B, B ) = B::compute_quadratic_expression([[U2, U1]], [[false, true]], [[U2, U1]], [[false, true]], [], []); + // let (_, X3): (B, B ) = B::compute_quadratic_expression( + // [[B::zero(), PP], [R, B::zero()]], + // [[false, true], [false, false]], + // [[U1, U2], [R, B::zero()]], + // [[false, false], [false, false]], + // [], + // [] + // ); + // let (_, U1S2_minus_U2S1): (B, B ) = B::compute_quadratic_expression( + // [[U1], [U2]], + // [[false], [true]], + // [[S2], [S1]], + // [[false], [false]], + // [], + // [] + // ); + // let (_, Y3): (B, B ) = B::compute_quadratic_expression( + // [[PP], [X3]], + // [[false], [false]], + // [[U1S2_minus_U2S1], [R]], + // [[false], [true]], + // [], + // [] + // ); + // let Z1Z2 = Z1.__mulmod(Z2); + // let (_, Z3): (B, B ) = B::compute_quadratic_expression( + // [[Z1Z2, B::zero()]], + // [[false, false]], + // [[U2, U1]], + // [[false, true]], + // [], + // [] + // ); + // ( + // CurveJ { x: X3, y: Y3, z: Z3, is_infinity: false }, JTranscript { lambda_numerator: R, x3: X3, y3: Y3, z3: Z3 } + // ) + } + + /** + * @brief Add two points together. + * @description Only uses incomplete formulae. + * With our use of offset generators, we should never need to handle edge cases. + * (when constraining operations, we simply assert the input x-coordinates are not equal) + * @note This method minimizes the number of calls to `compute_quadratic_expression`, + * which is NOT the same as minimizing the number of multiplications. + **/ + pub(crate) unconstrained fn incomplete_add(self, p2: Self) -> (Self, JTranscript) { + let X1 = self.x; + let X2 = p2.x; + let Y1 = self.y; + let Y2 = p2.y; + let Z1 = self.z; + let Z2 = p2.z; + let Z2Z2 = Z2.__mul(Z2); + let Z1Z1 = Z1.__mul(Z1); + let Z2Z2Z2 = Z2Z2.__mul(Z2); + let Z1Z1Z1 = Z1Z1.__mul(Z1); + let U1 = X1.__mul(Z2Z2); + let U2 = X2.__mul(Z1Z1); + let S1 = Y1.__mul(Z2Z2Z2); + let S2 = Y2.__mul(Z1Z1Z1); + let R = S2.__sub(S1); + + let (_, PP): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[U2, U1]], + [[false, true]], + [[U2, U1]], + [[false, true]], + [], + [], + ); + let (_, X3): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[B::zero(), PP], [R, B::zero()]], + [[false, true], [false, false]], + [[U1, U2], [R, B::zero()]], + [[false, false], [false, false]], + [], + [], + ); + + let (_, U1S2_minus_U2S1): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[U1], [U2]], + [[false], [true]], + [[S2], [S1]], + [[false], [false]], + [], + [], + ); + let (_, Y3): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[PP], [X3]], + [[false], [false]], + [[U1S2_minus_U2S1], [R]], + [[false], [true]], + [], + [], + ); + let Z1Z2 = Z1.__mul(Z2); + let (_, Z3): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[Z1Z2, B::zero()]], + [[false, false]], + [[U2, U1]], + [[false, true]], + [], + [], + ); + ( + CurveJ { x: X3, y: Y3, z: Z3, is_infinity: false }, + JTranscript { lambda_numerator: R, x3: X3, y3: Y3, z3: Z3 }, + ) + } + + unconstrained fn conditional_incomplete_add( + self, + p2: Self, + predicate: bool, + ) -> (Self, JTranscript) { + let mut operand_output = self.incomplete_add(p2); + let result = if predicate { operand_output.0 } else { self }; + (result, operand_output.1) + } + /** + * @brief Double a point + * @note This method minimizes the number of calls to `compute_quadratic_expression`, + * which is NOT the same as minimizing the number of multiplications. + **/ + pub(crate) unconstrained fn dbl(self) -> (Self, JTranscript) { + let X1 = self.x; + let Y1 = self.y; + let Z1 = self.z; + let (_, YY_mul_2): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[Y1]], + [[false]], + [[Y1, Y1]], + [[false, false]], + [], + [], + ); + let mut (_, XX_mul_3): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[X1]], + [[false]], + [[X1, X1, X1]], + [[false, false, false]], + [], + [], + ); + + if (Curve::a().get_limb(0) != 0) { + let ZZ = Z1.__mul(Z1); + let AZZZZ = ZZ.__mul(ZZ).__mul(Curve::a()); + XX_mul_3 = XX_mul_3.__add(AZZZZ); + } + let (_, D): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[X1, X1]], + [[false, false]], + [[YY_mul_2]], + [[false]], + [], + [], + ); + let mut (_, X3): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[XX_mul_3]], + [[false]], + [[XX_mul_3]], + [[false]], + [D, D], + [true, true], + ); + let (_, Y3): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[XX_mul_3], [YY_mul_2]], + [[false], [true]], + [[D, X3], [YY_mul_2, YY_mul_2]], + [[false, true], [false, false]], + [], + [], + ); + // 3XX * (D - X3) - 8YYYY + let (_, Z3): (B, B) = dep::bignum::bignum::compute_quadratic_expression( + [[Y1]], + [[false]], + [[Z1, Z1]], + [[false, false]], + [], + [], + ); + ( + CurveJ { x: X3, y: Y3, z: Z3, is_infinity: false }, + JTranscript { lambda_numerator: XX_mul_3, x3: X3, y3: Y3, z3: Z3 }, + ) + } + + pub(crate) fn offset_generator() -> Self { + let result = Curve::offset_generator(); + Self { x: result.x(), y: result.y(), z: B::one(), is_infinity: false } + } + + pub(crate) fn offset_generator_final() -> Self { + let result = Curve::offset_generator_final(); + Self { x: result.x(), y: result.y(), z: B::one(), is_infinity: false } + } + + pub(crate) fn one() -> Self { + let result = Curve::one(); + Self { x: result.x(), y: result.y(), z: B::one(), is_infinity: false } + } + + /** + * @brief Perform an ecc scalar multiplication and output the generated AffineTranscript + **/ + pub(crate) unconstrained fn mul( + self, + scalar: ScalarField, + ) -> (Self, [AffineTranscript; 5 * NScalarSlices + 6]) { + let mut transcript: [JTranscript; NScalarSlices * 5 + 6] = + [JTranscript::new(); NScalarSlices * 5 + 6]; + + let (input, scalar) = if self.is_infinity { + (CurveJ::one(), ScalarField::zero()) + } else { + (self, scalar) + }; + let mut ptr: u32 = 0; + let T = PointTable::new(input); + for i in 0..8 { + transcript[ptr] = T.transcript[i]; + ptr += 1; + } + + let mut accumulator: Self = CurveJ::offset_generator(); + let op = accumulator.incomplete_add(T.get(scalar.base4_slices[0] as u32)); + transcript[ptr] = op.1; + ptr += 1; + accumulator = op.0; + for i in 1..NScalarSlices { + for _ in 0..4 { + let op = accumulator.dbl(); + accumulator = op.0; + transcript[ptr] = op.1; + ptr += 1; + } + let op = accumulator.incomplete_add(T.get(scalar.base4_slices[i] as u32)); + transcript[ptr] = op.1; + ptr += 1; + accumulator = op.0; + } + + let op = accumulator.conditional_incomplete_add(input.neg(), scalar.skew); + transcript[ptr] = op.1; + accumulator = op.0; + ptr += 1; + + let op = accumulator.sub(CurveJ::offset_generator_final()); + transcript[ptr] = op.1; + ptr += 1; + accumulator = op.0; + + let affine_transcript: [AffineTranscript; 5 * NScalarSlices + 6] = + AffineTranscript::from_jacobian_transcript(transcript); + + (accumulator, affine_transcript) + } + /** + * @brief Perform an ecc scalar multiplication and output the generated AffineTranscript + **/ + unconstrained fn msm_partial( + points: [Self; Size], + scalars: [ScalarField; Size], + ) -> (Self, [JTranscript; TranscriptEntries])/*(Self, [JTranscript; NScalarSlices * Size + NScalarSlices * 4 + Size * 9 - 3]) */ +{ + let mut transcript: [JTranscript; TranscriptEntries] = + [JTranscript::new(); TranscriptEntries]; + let mut tables: [PointTable; Size] = [PointTable::empty(); Size]; + + let mut _inputs: [Self; Size] = [CurveJ::new(); Size]; + let mut _scalars: [ScalarField; Size] = [ScalarField::zero(); Size]; + for i in 0..Size { + let (input, scalar) = if points[i].is_infinity { + (CurveJ::one(), ScalarField::zero()) + } else { + (points[i], scalars[i]) + }; + _inputs[i] = input; + _scalars[i] = scalar; + } + let points = _inputs; + let scalars = _scalars; + let mut ptr: u32 = 0; + for i in 0..Size { + tables[i] = PointTable::new(points[i]); + for j in 0..8 { + transcript[ptr] = tables[i].transcript[j]; + ptr += 1; + } + } + + let mut accumulator: Self = CurveJ::offset_generator(); + let op = accumulator.incomplete_add(tables[0].get(scalars[0].base4_slices[0] as u32)); + transcript[ptr] = op.1; + ptr += 1; + accumulator = op.0; + + for i in 1..Size { + let op = accumulator.incomplete_add(tables[i].get(scalars[i].base4_slices[0] as u32)); + transcript[ptr] = op.1; + ptr += 1; + accumulator = op.0; + } + for i in 1..NScalarSlices { + for _ in 0..4 { + let op = accumulator.dbl(); + accumulator = op.0; + transcript[ptr] = op.1; + ptr += 1; + } + for j in 0..Size { + let op = + accumulator.incomplete_add(tables[j].get(scalars[j].base4_slices[i] as u32)); + transcript[ptr] = op.1; + ptr += 1; + accumulator = op.0; + } + } + + for i in 0..Size { + let op = accumulator.conditional_incomplete_add(points[i].neg(), scalars[i].skew); + transcript[ptr] = op.1; + accumulator = op.0; + ptr += 1; + } + + (accumulator, transcript) + } + + /** + * @brief Perform an ecc scalar multiplication and output the generated AffineTranscript + **/ + pub(crate) unconstrained fn msm( + mut points: [Self; Size], + mut scalars: [ScalarField; Size], + ) -> (Self, [AffineTranscript; NScalarSlices * Size + NScalarSlices * 4 + Size * 9 - 3]) { + let mut (accumulator, transcript) + : (Self, [JTranscript; NScalarSlices * Size + NScalarSlices * 4 + Size * 9 - 3]) = + CurveJ::msm_partial(points, scalars); + let op = accumulator.sub(CurveJ::offset_generator_final()); + transcript[73 * Size + 252] = op.1; + accumulator = op.0; + let affine_transcript: [AffineTranscript; NScalarSlices * Size + NScalarSlices * 4 + Size * 9 - 3] = + AffineTranscript::from_jacobian_transcript(transcript); + + (accumulator, affine_transcript) + } + + pub(crate) unconstrained fn compute_linear_expression_transcript( + mut mul_points: [Curve; NMuls], + mut scalars: [ScalarField; NMuls], + mut add_points: [Curve; NAdds], + ) -> (Self, [AffineTranscript; NScalarSlices * NMuls + NScalarSlices * 4 + NMuls * 9 + NAdds - 3]) { + let mut mul_j: [CurveJ; NMuls] = [CurveJ::new(); NMuls]; + let mut add_j: [CurveJ; NAdds] = [CurveJ::new(); NAdds]; + for i in 0..NMuls { + mul_j[i] = CurveJ::::from(mul_points[i]); + } + for i in 0..NAdds { + add_j[i] = CurveJ::from(add_points[i]); + } + + let mut (accumulator, transcript) + : (Self, [JTranscript; NScalarSlices * NMuls + NScalarSlices * 4 + NMuls * 9 + NAdds - 3]) = + CurveJ::msm_partial(mul_j, scalars); + let mut transcript_ptr: u32 = NScalarSlices * NMuls + NScalarSlices * 4 + NMuls * 9 - 4; + for i in 0..NAdds { + let op = accumulator.conditional_incomplete_add(add_j[i], !add_j[i].is_infinity); + transcript[transcript_ptr] = op.1; + accumulator = op.0; + transcript_ptr += 1; + } + + let op = accumulator.sub(CurveJ::offset_generator_final()); + transcript[transcript_ptr] = op.1; + accumulator = op.0; + let affine_transcript: [AffineTranscript; NScalarSlices * NMuls + NScalarSlices * 4 + NMuls * 9 + NAdds - 3] = + AffineTranscript::from_jacobian_transcript(transcript); + + (accumulator, affine_transcript) + } +} diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curves/mod.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curves/mod.nr new file mode 100644 index 0000000..00c35cd --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curves/mod.nr @@ -0,0 +1 @@ +pub mod secp384r1; diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curves/secp384r1.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curves/secp384r1.nr new file mode 100644 index 0000000..08da3cc --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/curves/secp384r1.nr @@ -0,0 +1,142 @@ +use crate::crypto::noir_bigcurve_vendor::BigCurveParams; +use crate::crypto::noir_bigcurve_vendor::derive_curve_impl; +use crate::crypto::noir_bigcurve_vendor::scalar_field::ScalarField; +use dep::bignum::BigNum; +pub use dep::bignum::{Secp384r1_Fq, Secp384r1_Fr}; + +// Import BigCurve trait to bring methods like 'one', 'mul' into scope +use crate::crypto::noir_bigcurve_vendor::BigCurve; + +pub global SECP384r1_PARAM: BigCurveParams = BigCurveParams { + a: Secp384r1_Fq::from_limbs([ + 0xffffff0000000000000000fffffffc, + 0xfffffffffffffffffffffffffffeff, + 0xffffffffffffffffffffffffffffff, + 0xffffff, + ]), + b: Secp384r1_Fq::from_limbs([ + 0x56398d8a2ed19d2a85c8edd3ec2aef, + 0x9c6efe8141120314088f5013875ac6, + 0xa7e23ee7e4988e056be3f82d19181d, + 0xb3312f, + ]), + one: [ + Secp384r1_Fq::from_limbs([ + 0x02f25dbf55296c3a545e3872760ab7, + 0x3b628ba79b9859f741e082542a3855, + 0x22be8b05378eb1c71ef320ad746e1d, + 0xaa87ca, + ]), + Secp384r1_Fq::from_limbs([ + 0x60b1ce1d7e819d7a431d7c90ea0e5f, + 0x1dbd289a147ce9da3113b5f0b8c00a, + 0x4a96262c6f5d9e98bf9292dc29f8f4, + 0x3617de, + ]), + ], + offset_generator: [ + Secp384r1_Fq::from_limbs([ + 0xba62f5015d975e9c847349dc8a58f7, + 0xcfe0a3905b8dafff0226cbfddee8d3, + 0xce72424b249140226ac9b8afb0ab3c, + 0xffb219, + ]), + Secp384r1_Fq::from_limbs([ + 0x889e51064a7515c4b3a96a397501de, + 0xfe7bbfa55a3b86cf38c1e0bce169de, + 0xb19d05c22e1590952e5a956ddcb3bd, + 0x462005, + ]), + ], + offset_generator_final: [ + Secp384r1_Fq::from_limbs([ + 0xce701d9971f92d5e54d393c5e68585, + 0x7075dbe299c8708a1e0ec78c96a60f, + 0x393d1f969e37931c99fb298e53630d, + 0x364fe7, + ]), + Secp384r1_Fq::from_limbs([ + 0x8301c0d245c908e4f5c4e20c98a696, + 0xb48327458c410785bab4bd29b71040, + 0xe9536dfb1bd0b1c80c04e2e1ef404e, + 0x40d30a, + ]), + ], +}; + +pub global SECP384r1_SCALAR_SLICES: u32 = 97; +pub type Secp384r1Scalar = ScalarField; + +#[derive_curve_impl(quote { Secp384r1_Fq }, quote { SECP384r1_PARAM })] +pub struct Secp384r1 { + pub x: Secp384r1_Fq, + pub y: Secp384r1_Fq, + pub is_infinity: bool, +} + +mod test { + use bignum::{BigNum, Secp384r1_Fq, Secp384r1_Fr}; + use std::ops::Neg; + + use crate::crypto::noir_bigcurve_vendor::BigCurve; + use super::Secp384r1; + use super::SECP384r1_SCALAR_SLICES; + use super::Secp384r1Scalar; + + #[test] + fn check_num_scalar_slices_in_scalar_field() { + let x = Secp384r1_Fq::zero(); + let max_wnaf_bits: u32 = x.modulus_bits() + 1; + + let scalar_slices = (max_wnaf_bits / 4) + (max_wnaf_bits % 4 != 0) as u32; + assert(scalar_slices == SECP384r1_SCALAR_SLICES); + } + + #[test] + fn test_offset_generators() { + let one = Secp384r1::one(); + let negone = Secp384r1_Fr::one().neg(); + let scalar = Secp384r1Scalar::from_bignum(negone); + let final = BigCurve::mul(one, scalar); + + assert(final.eq(one.neg())); + } + + #[test] + fn test_hash_to_curve() { + let r = Secp384r1::hash_to_curve("hello world".as_bytes()); + + r.validate_on_curve(); + } + + #[test] + fn test_msm() { + let four = Secp384r1_Fr::from(4); + let p_minus_4_fr = Secp384r1_Fr::modulus() - four; + let p_minus_4 = Secp384r1Scalar::from_bignum(p_minus_4_fr); + let p_minus_5_fr = p_minus_4_fr - Secp384r1_Fr::one(); + let p_minus_5 = Secp384r1Scalar::from_bignum(p_minus_5_fr); + let mut scalars = [p_minus_4, p_minus_5]; + let a = Secp384r1::one(); + let b = a.neg(); + let mut points = [a, b]; + + let result = + Secp384r1::evaluate_linear_expression(points, scalars, [Secp384r1::one().neg()]); + + assert(result.is_infinity); + } + + // verify_offset_generators test removed -- body was commented out and + // #[test(should_fail)] on an empty fn causes CI failure (test passes + // when it should fail). The actual offset generator verification is + // not applicable for Secp384r1 (cofactor = 1). + + #[test] + unconstrained fn test_scalar_field_conversion(seed: [u8; 10]) { + let num: Secp384r1_Fr = Secp384r1_Fr::derive_from_seed(seed); + let scalar_field = Secp384r1Scalar::from_bignum(num); + let bignum = scalar_field.into_bignum(); + assert(bignum == num); + } +} diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/mod.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/mod.nr new file mode 100644 index 0000000..ab22d79 --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/mod.nr @@ -0,0 +1,1087 @@ +pub(crate) mod curve_jac; +pub mod scalar_field; +pub(crate) mod utils; +pub mod curves; + +use dep::bignum::BigNum; +use dep::bignum::bignum::evaluate_quadratic_expression; + +use crate::crypto::noir_bigcurve_vendor::curve_jac::AffineTranscript; +use crate::crypto::noir_bigcurve_vendor::scalar_field::ScalarField; +use std::ops::{Add, Neg, Sub}; +// mod benchmarks; + +/// Implements an elliptic curve over a prime field that is not the circuit's native field. + +pub struct BigCurveParams { + pub a: B, + pub b: B, + pub offset_generator: [B; 2], + pub offset_generator_final: [B; 2], + pub one: [B; 2], +} + +pub trait BigCurve: Eq + Add + Sub + Neg { + /// Returns the x-coordinate of the point. + fn x(self) -> B; + + /// Returns the y-coordinate of the point. + fn y(self) -> B; + + /// Returns the a-coordinate of the curve. + fn a() -> B; + + /// Returns the b-coordinate of the curve. + fn b() -> B; + + /// Creates a point from its coordinates. + fn from_coordinates(x: B, y: B, is_infinity: bool) -> Self; + + /// Returns the point at infinity (the identity element of the curve group). + fn point_at_infinity() -> Self; + + /// Returns true if the point is the point at infinity. + fn is_infinity(self) -> bool; + + /// Returns the canonical generator point of the curve. + fn one() -> Self; + + /// Returns a generator point offset by a fixed value (implementation-specific). + fn offset_generator() -> Self; + + /// Returns the final offset generator point (implementation-specific). + fn offset_generator_final() -> Self; + + /// Validates that the point lies on the curve. May panic or fail if invalid. + fn validate_on_curve(self); + + /// Multiplies the point by a scalar value, returning the resulting point. + fn mul(self, scalar: ScalarField) -> Self; + + /// Hashes the provided `seed` to a point on the curve. + fn hash_to_curve(seed: [u8; N]) -> Self; + + /// Evaluates a linear expression involving multiple points and scalars, returning the resulting point. + fn evaluate_linear_expression( + mul_points: [Self; NMuls], + mul_scalars: [ScalarField; NMuls], + add_points: [Self; NAdds], + ) -> Self; +} + +pub comptime fn derive_curve_impl( + struct_def: TypeDefinition, + field_type: Quoted, + params: Quoted, +) -> Quoted { + let typ = struct_def.as_type(); + let CurveJ = quote { $crate::crypto::noir_bigcurve_vendor::curve_jac::CurveJ }; + let AffineTranscript = quote { $crate::crypto::noir_bigcurve_vendor::curve_jac::AffineTranscript }; + + quote { + impl $crate::crypto::noir_bigcurve_vendor::BigCurve<$field_type> for $typ { + fn x(self) -> $field_type { + self.x + } + + fn y(self) -> $field_type { + self.y + } + + fn a() -> $field_type { + $params.a + } + + fn b() -> $field_type { + $params.b + } + + fn is_infinity(self) -> bool { + self.is_infinity + } + + fn from_coordinates(x: $field_type, y: $field_type, is_infinity: bool) -> Self { + Self { x, y, is_infinity } + } + + fn point_at_infinity() -> Self { + Self { + x: $field_type::zero(), + y: $field_type::zero(), + is_infinity: true + } + } + + fn offset_generator() -> Self { + let result: [$field_type; 2] = $params.offset_generator; + Self { + x: result[0], + y: result[1], + is_infinity: false + } + } + + fn offset_generator_final() -> Self { + let result: [$field_type; 2] = $params.offset_generator_final; + Self { + x: result[0], + y: result[1], + is_infinity: false + } + } + + fn one() -> Self { + let result: [$field_type; 2] = $params.one; + Self { + x: result[0], + y: result[1], + is_infinity: false + } + } + + fn validate_on_curve(self) { + // if is point at infinity, we're on the curve. + // In this case just sub in a valid point for the x/y coordinates we are about to test + let one: Self = Self::one(); + let x: $field_type = if self.is_infinity { one.x } else { self.x }; + let y: $field_type = if self.is_infinity { one.y } else { self.y }; + let xx = std::ops::Mul::mul(x, x); + // xxx - yy + ax + b = 0 + // (xx + a) * x - y*y + b = 0 + // validate the provided value of `y3` is correct + $crate::crypto::noir_bigcurve_vendor::evaluate_quadratic_expression( + [[xx, $params.a], [y, $field_type::zero()]], + [[false, false], [false, false]], + [[x], [y]], + [[false], [true]], + [$params.b], + [false], + ); + } + + fn mul(self, scalar: ScalarField) -> Self { + let transcript: [$AffineTranscript<$field_type>; (NScalarSlices * 5) + 6] = + // Safety: efficient mul transcript + unsafe { $crate::crypto::noir_bigcurve_vendor::get_mul_transcript::(self, scalar) }; + $crate::crypto::noir_bigcurve_vendor::mul_with_hint::(self, scalar, transcript) + } + + fn hash_to_curve(seed: [u8; N]) -> Self { + let r = $crate::crypto::noir_bigcurve_vendor::utils::hash_to_curve::hash_to_curve::<$field_type, N>(seed, $params.a, $params.b); + Self { x: r.0, y: r.1, is_infinity: false } + } + + fn evaluate_linear_expression( + mul_points: [Self; NMuls], + mul_scalars: [ScalarField; NMuls], + add_points: [Self; NAdds], + ) -> Self { + $crate::crypto::noir_bigcurve_vendor::evaluate_linear_expression::<$field_type,$typ, _, _, _>(mul_points, mul_scalars, add_points) + }} + + // Expensive witness generation! Avoid if possible + impl std::ops::Add for $typ { + fn add(self, other: Self) -> Self { + let lhsJ = $crate::crypto::noir_bigcurve_vendor::curve_jac::CurveJ::<$field_type, $typ>::from(self); + let rhsJ = $crate::crypto::noir_bigcurve_vendor::curve_jac::CurveJ::<$field_type, $typ>::from(other); + // Safety: efficient transcript add + let (result_jac, j_transcript) = unsafe { lhsJ.add(rhsJ) }; + // Safety: efficient transcript conversion + let transcript = unsafe { $crate::crypto::noir_bigcurve_vendor::curve_jac::AffineTranscript::from_j(j_transcript) }; + if std::runtime::is_unconstrained() { + $typ::from_coordinates(transcript.x3, transcript.y3, result_jac.is_infinity) + + } else { + $crate::crypto::noir_bigcurve_vendor::add_with_hint::<$field_type, $typ>(self, other, transcript) + } + } + } + + impl std::cmp::Eq for $typ { + fn eq(self, other: Self) -> bool { + let coords_equal = + self.x.eq(other.x) & self.y.eq(other.y) & !self.is_infinity & !other.is_infinity; + let infinity = self.is_infinity & other.is_infinity; + coords_equal | infinity + } + } + + impl std::ops::Sub for $typ { + fn sub(self, other: Self) -> Self { + let lhsJ = $crate::crypto::noir_bigcurve_vendor::curve_jac::CurveJ::<$field_type, $typ>::from(self); + let rhsJ = $crate::crypto::noir_bigcurve_vendor::curve_jac::CurveJ::<$field_type, $typ>::from(other); + // Safety: efficient transcript sub + let (result_jac, j_transcript) = unsafe { lhsJ.sub(rhsJ) }; + + // Convert back to affine coordinates using the transcript + // Safety: efficient transcript conversion + let transcript = unsafe { $crate::crypto::noir_bigcurve_vendor::curve_jac::AffineTranscript::from_j(j_transcript) }; + if std::runtime::is_unconstrained() { + $typ::from_coordinates(transcript.x3, transcript.y3, result_jac.is_infinity) + } else { + $crate::crypto::noir_bigcurve_vendor::sub_with_hint::<$field_type, $typ>(self, other, transcript) + } + } + } + + impl std::ops::Neg for $typ { + fn neg(self) -> Self { + Self { + x: self.x, + y: std::ops::Neg::neg(self.y), + is_infinity: self.is_infinity + } + } + } + } +} + +/// Doubles a point using an `AffineTranscript` that contains inverses and output witnesses. +/// +/// This method is optimized to minimize the number of calls to `evaluate_quadratic_expression`, +/// which is not necessarily the same as minimizing the number of multiplications. +pub(crate) fn double_with_hint>( + point: P, + transcript: AffineTranscript, +) -> P { + let x1 = point.x(); + let y1 = point.y(); + let lambda = transcript.lambda; + let x3 = transcript.x3; + let y3 = transcript.y3; + + // we pulled x3, y3, lambda out of the ether - we need to make sure they are well-formed B objects! + x3.validate_in_range(); + y3.validate_in_range(); + lambda.validate_in_range(); + + // -lambda * 2y + 3*x*x + a = 0 + // validate the provided value of `lambda` is correct + // n.b. if CurveParams::a() == 0, its inclusion shouldn't cost extra constraints...I thnk + evaluate_quadratic_expression( + [[x1, x1, x1], [y1, y1, B::zero()]], + [[false, false, false], [false, false, false]], + [[x1], [lambda]], + [[false], [true]], + [P::a()], + [false], + ); + + // validate the provided value of `x3` is correct + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[lambda]], + [[false]], + [x3, x1, x1], + [true, true, true], + ); + + // validate the provided value of `y3` is correct + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[x3, x1]], + [[false, true]], + [y3, y1], + [false, false], + ); + + P::from_coordinates(x3, y3, false) +} + +/// Adds two points together using an `AffineTranscript` that contains inverses and output witnesses. +/// +/// Only incomplete formulae are used. With the use of offset generators, an honest prover should never +/// need to handle edge cases. Therefore, completeness is sacrificed for cheap soundness: instead of +/// handling edge cases, the function asserts that they do not exist by validating `x2 != x1`. +/// +/// This method minimizes the number of calls to `evaluate_quadratic_expression`, which is not the same +/// as minimizing the number of multiplications. The expensive operation in `BigNum` is the modular +/// reduction. For example, `(a * b + c * d = e mod p)` is not much more expensive than `(a * b = c mod p)`. +pub(crate) fn incomplete_add_with_hint>( + point: P, + other: P, + transcript: AffineTranscript, +) -> P { + let x1: B = point.x(); + let y1: B = point.y(); + let x2: B = other.x(); + let y2: B = other.y(); + let lambda: B = transcript.lambda; + let x3: B = transcript.x3; + let y3: B = transcript.y3; + + // we pulled x3, y3, lambda out of the ether - we need to make sure they are well-formed B objects! + x3.validate_in_range(); + y3.validate_in_range(); + lambda.validate_in_range(); + + // no incomplete Weierstrass shenanigans here + x1.assert_is_not_equal(x2); + + // validate the provided value of `lambda` is correct + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[x2, x1]], + [[false, true]], + [y2, y1], + [true, false], + ); + + // validate the provided value of `x3` is correct + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[lambda]], + [[false]], + [x3, x2, x1], + [true, true, true], + ); + + // validate the provided value of `y3` is correct + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[x3, x1]], + [[false, true]], + [y3, y1], + [false, false], + ); + + P::from_coordinates(x3, y3, false) +} + +/// Multiplies a point by a scalar field value, returning the resulting point. +pub fn msm, B: BigNum, let NScalarSlices: u32, let NMuls: u32>( + mul_points: [P; NMuls], + mul_scalars: [ScalarField; NMuls], +) -> P { + let add_points: [P; 0] = []; + P::evaluate_linear_expression(mul_points, mul_scalars, add_points) +} + +// TODO: offset generators +// conditional subtract, conditional add +// +/** + * @brief Perform an ecc scalar multiplication, given an [AffineTranscript] generated via unconstrained functions + **/ +fn msm_with_hint_internal>( + mut points: [P; Size], + mut scalars: [ScalarField; Size], + transcript: [AffineTranscript; NTranscriptSlices], +) -> P { + // Compute a 4-bit lookup table of multiples of P + let mut _inputs: [P; Size] = [P::one(); Size]; + let mut _scalars: [ScalarField; Size] = [ScalarField::zero(); Size]; + for i in 0..Size { + let (input, scalar) = if points[i].is_infinity() { + (P::one(), ScalarField::zero()) + } else { + (points[i], scalars[i]) + }; + _inputs[i] = input; + _scalars[i] = scalar; + } + points = _inputs; + scalars = _scalars; + + let mut tables: [PointTable; Size] = [PointTable::empty(); Size]; + for i in 0..Size { + let mut table_transcript: [AffineTranscript; 8] = [AffineTranscript::new(); 8]; + for j in 0..8 { + table_transcript[j] = transcript[i * 8 + j]; + } + tables[i] = PointTable::new_with_hint::

(points[i], table_transcript); + } + + // Init the accumulator from the most significant scalar slice + let mut accumulator: P = P::offset_generator(); +// Internal function calls - removing 'crate::' which refers to package root, using local scope +// or fully qualified path if needed. Since these are in 'mod.nr', they are local to the module (or siblings). +// But wait, 'incomplete_add_with_hint' is defined in this file. So we can just call it directly. + + // Init the accumulator from the most significant scalar slice + let mut accumulator: P = P::offset_generator(); + let mut accumulator = incomplete_add_with_hint::( + accumulator, + tables[0].get::

(scalars[0].base4_slices[0] as u32), + transcript[8 * Size], + ); + + for i in 1..Size { + accumulator = incomplete_add_with_hint::( + accumulator, + tables[i].get::

(scalars[i].base4_slices[0] as u32), + transcript[8 * Size + i], + ); + } + + // Perform the "double and add" algorithm + for i in 1..NScalarSlices { + accumulator = + double_with_hint::(accumulator, transcript[9 * Size + (4 + Size) * (i - 1)]); + accumulator = + double_with_hint::(accumulator, transcript[9 * Size + (4 + Size) * (i - 1) + 1]); + accumulator = + double_with_hint::(accumulator, transcript[9 * Size + (4 + Size) * (i - 1) + 2]); + accumulator = + double_with_hint::(accumulator, transcript[9 * Size + (4 + Size) * (i - 1) + 3]); + + for j in 0..Size { + accumulator = incomplete_add_with_hint::( + accumulator, + tables[j].get::

(scalars[j].base4_slices[i] as u32), + transcript[9 * Size + (4 + Size) * (i - 1) + 4 + j], + ); + } + } + + // Windowed NAF fixup + for i in 0..Size { + accumulator = conditional_incomplete_subtract_with_hint::( + accumulator, + points[i], + scalars[i].skew, + transcript[9 * Size + (4 + Size) * (NScalarSlices - 1) + i], + ); + } + + accumulator +} + +// ... (other functions) + +// Fixing sub_with_hint calls (Line 868 and 886) +// Wait, 'sub_with_hint' is defined in this file. So just call 'sub_with_hint'. +// But in the macro (lines 197, 222), it might be expanded in a different context. +// The macro uses '$crate::crypto::noir_bigcurve_vendor::sub_with_hint' which is correct. +// But the functions 'msm_with_hint_internal' etc are regular functions in the module. +// They should call siblings without 'crate::'. + +pub(crate) fn conditional_incomplete_add_with_hint>( + point: P, + other: P, + predicate: bool, + transcript: AffineTranscript, +) -> P { + let operand_output = incomplete_add_with_hint::(point, other, transcript); + if predicate { + operand_output + } else { + point + } +} + +fn conditional_incomplete_subtract_with_hint>( + point: P, + other: P, + predicate: bool, + transcript: AffineTranscript, +) -> P { + let operand_output = incomplete_subtract_with_hint::(point, other, transcript); + if predicate { + operand_output + } else { + point + } +} + +fn incomplete_subtract_with_hint>( + point: P, + other: P, + transcript: AffineTranscript, +) -> P { + let x1: B = point.x(); + let y1: B = point.y(); + let x2: B = other.x(); + let y2: B = other.y(); + let lambda: B = transcript.lambda; + let x3: B = transcript.x3; + let y3: B = transcript.y3; + + // we pulled x3, y3, lambda out of the ether - we need to make sure they are well-formed BigNum objects! + x3.validate_in_range(); + y3.validate_in_range(); + lambda.validate_in_range(); + + // no incomplete Weierstrass shenanigans here + x1.assert_is_not_equal(x2); + + // validate the provided value of `lambda` is correct + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[x2, x1]], + [[false, true]], + [y2, y1], + [false, false], + ); + + // validate the provided value of `x3` is correct + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[lambda]], + [[false]], + [x3, x2, x1], + [true, true, true], + ); + + // validate the provided value of `y3` is correct + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[x3, x1]], + [[false, true]], + [y3, y1], + [false, false], + ); + + P::from_coordinates(x3, y3, false) +} + +pub(crate) fn add_with_hint>( + point: P, + other: P, + transcript: AffineTranscript, +) -> P { + let x1: B = point.x(); + let y1: B = point.y(); + let x2: B = other.x(); + let y2: B = other.y(); + let lambda: B = transcript.lambda; + let x3: B = transcript.x3; + let y3: B = transcript.y3; + + // we pulled x3, y3, lambda out of the ether - we need to make sure they are well-formed B objects! + x3.validate_in_range(); + y3.validate_in_range(); + lambda.validate_in_range(); + + // TODO: we can probably optimize this boolean flag jenga mess + let x_equal_predicate = x2.eq(x1); + let y_equal_predicate = y2.eq(y1); + let double_predicate = x_equal_predicate | (point.is_infinity() | other.is_infinity()); // if x1 == x2, evaluate double operation. If y1 = -y2 then we set all input/output parameters to be 0 + let infinity_predicate = + (x_equal_predicate & !y_equal_predicate) | (point.is_infinity() & other.is_infinity()); + let evaluate_group_operation_predicate: bool = + !infinity_predicate & !point.is_infinity() & !other.is_infinity(); + + // If we are skipping the evaluation of a group operation (x2 == x1, y2 == -y1 OR any input points are at infinity), + // set input operands to 0! + let (x1, y1, x2, y2, x3, y3) = if evaluate_group_operation_predicate { + (x1, y1, x2, y2, x3, y3) + } else { + (B::zero(), B::zero(), B::zero(), B::zero(), B::zero(), B::zero()) + }; + + // lambda * 2y - 3x * x = 0 + // or + // lambda * (x2 - x1) - (y2 - y1) = 0 + let product_1_rhs_t0 = if double_predicate { y1 } else { x2 }; + let product_1_rhs_t1 = if double_predicate { y1 } else { x1.neg() }; + let product_2_lhs_t0 = if double_predicate { x1 } else { B::one() }; + let product_2_rhs_t0 = if double_predicate { x1 } else { y2 }; + let product_2_rhs_t1 = if double_predicate { x1 } else { y1.neg() }; + let product_2_rhs_t2 = if double_predicate { x1 } else { B::zero() }; + + // validate the provided value of `lambda` is correct + // if double: lambda * (y1 + y1) + x1 * (-x1 -x1 -x1) - a = 0 => lambda * 2y - 3x*x = 0 + // if add: lambda * (x2 - x1) + 1 * (-y2 + y1) = 0 => lambda * (x2 - x1) - (y2 - y1) = 0 + let mut a_term = if x_equal_predicate + & y_equal_predicate + & !point.is_infinity() + & !other.is_infinity() { + P::a() + } else { + B::zero() + }; + + evaluate_quadratic_expression( + [[lambda], [product_2_lhs_t0]], + [[false], [false]], + [ + [product_1_rhs_t0, product_1_rhs_t1, B::zero()], + [product_2_rhs_t0, product_2_rhs_t1, product_2_rhs_t2], + ], + [[false, false, false], [true, true, true]], + [a_term], + [true], + ); + + // x3 = lambda * lambda - x2 - x1 + // if double, then x2 = x1 so we good + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[lambda]], + [[false]], + [x3, x2, x1], + [true, true, true], + ); + + // y3 = lambda * (x1 - x3) - y1 + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[x3, x1]], + [[false, true]], + [y3, y1], + [false, false], + ); + + let output_is_lhs = other.is_infinity() & !point.is_infinity(); + let output_is_rhs = point.is_infinity() & !other.is_infinity(); + let mut x_out = if evaluate_group_operation_predicate { + x3 + } else { + x1 + }; + x_out = if output_is_lhs { point.x() } else { x_out }; + x_out = if output_is_rhs { other.x() } else { x_out }; + x_out = if infinity_predicate { B::zero() } else { x_out }; + let mut y_out = if evaluate_group_operation_predicate { + y3 + } else { + y1 + }; + y_out = if output_is_lhs { point.y() } else { y_out }; + y_out = if output_is_rhs { other.y() } else { y_out }; + y_out = if infinity_predicate { B::zero() } else { y_out }; + + let mut infinity_out = !evaluate_group_operation_predicate; + infinity_out = if infinity_predicate { + true + } else { + infinity_out + }; + infinity_out = if output_is_lhs { + point.is_infinity() + } else { + infinity_out + }; + infinity_out = if output_is_rhs { + other.is_infinity() + } else { + infinity_out + }; + + let result: P = P::from_coordinates(x_out, y_out, infinity_out); + result +} + +pub(crate) fn sub_with_hint>( + point: P, + other: P, + transcript: AffineTranscript, +) -> P { + let x1: B = point.x(); + let y1: B = point.y(); + let x2: B = other.x(); + let y2: B = other.y(); + let lambda: B = transcript.lambda; + let x3: B = transcript.x3; + let y3: B = transcript.y3; + + // we pulled x3, y3, lambda out of the ether - we need to make sure they are well-formed B objects! + x3.validate_in_range(); + y3.validate_in_range(); + lambda.validate_in_range(); + + let x_equal_predicate = x2.eq(x1); + let y_equal_predicate = y2.eq(y1) == false; + let double_predicate = x_equal_predicate | (point.is_infinity() | other.is_infinity()); // if x1 == x2, evaluate double operation. If y1 = -y2 then we set all input/output parameters to be 0 + let infinity_predicate: bool = + (x_equal_predicate & !y_equal_predicate) | (point.is_infinity() & other.is_infinity()); + let evaluate_group_operation_predicate: bool = + !infinity_predicate & !point.is_infinity() & !other.is_infinity(); + + // If we are skipping the evaluation of a group operation (x2 == x1, y2 == -y1 OR any input points are at infinity), + // set input operands to 0! + let (x1, y1, x2, y2, x3, y3) = if evaluate_group_operation_predicate { + (x1, y1, x2, y2, x3, y3) + } else { + (B::zero(), B::zero(), B::zero(), B::zero(), B::zero(), B::zero()) + }; + + // lambda * 2y - 3x*x = 0 + // 3 x * x - lambda * 2y + // lambda * (x2 - x1) - (y2 - y1) = 0 + // y1 - (y2.neg()) - lambda * (x1 - x2) = 0 + // y1 + y2 - lambda * (x1 - x2) = 0 + // 3 * x * x - lambda * 2 * y + let product_1_rhs_t0 = if double_predicate { y1 } else { x2.neg() }; + let product_1_rhs_t1 = if double_predicate { y1 } else { x1 }; + let product_2_lhs_t0 = if double_predicate { x1 } else { B::one() }; + let product_2_rhs_t0 = if double_predicate { x1 } else { y2 }; + let product_2_rhs_t1 = if double_predicate { x1 } else { y1 }; + let product_2_rhs_t2 = if double_predicate { x1 } else { B::zero() }; + + // validate the provided value of `lambda` is correct + // if double: -lambda * (y1 + y1) + x1 * (x1 x1 x1) + a= 0 => lambda * 2y - 3x*x = 0 + // if add: -lambda * (x1 - x2) + 1 * (y2 + y1) = 0 => lambda * (x2 - x1) - (-y2 - y1) = 0 + let a_term = if x_equal_predicate + & y_equal_predicate + & !point.is_infinity() + & !other.is_infinity() { + P::a() + } else { + B::zero() + }; + + evaluate_quadratic_expression( + [[lambda], [product_2_lhs_t0]], + [[true], [false]], + [ + [product_1_rhs_t0, product_1_rhs_t1, B::zero()], + [product_2_rhs_t0, product_2_rhs_t1, product_2_rhs_t2], + ], + [[false, false, false], [false, false, false]], + [a_term], + [false], + ); + + // x3 = lambda * lambda - x2 - x1 + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[lambda]], + [[false]], + [x3, x2, x1], + [true, true, true], + ); + + // y3 = lambda * (x1 - x3) - y1 + evaluate_quadratic_expression( + [[lambda]], + [[false]], + [[x3, x1]], + [[false, true]], + [y3, y1], + [false, false], + ); + + let output_is_lhs = other.is_infinity() & !point.is_infinity(); + let output_is_rhs = point.is_infinity() & !other.is_infinity(); + let mut x_out = if evaluate_group_operation_predicate { + x3 + } else { + x1 + }; + x_out = if output_is_lhs { point.x() } else { x_out }; + x_out = if output_is_rhs { other.x() } else { x_out }; + x_out = if infinity_predicate { B::zero() } else { x_out }; + let mut y_out = if evaluate_group_operation_predicate { + y3 + } else { + y1 + }; + y_out = if output_is_lhs { point.y() } else { y_out }; + y_out = if output_is_rhs { + other.y().neg() + } else { + y_out + }; + y_out = if infinity_predicate { B::zero() } else { y_out }; + + let mut infinity_out = !evaluate_group_operation_predicate; + infinity_out = if infinity_predicate { + true + } else { + infinity_out + }; + infinity_out = if output_is_lhs { + point.is_infinity() + } else { + infinity_out + }; + infinity_out = if output_is_rhs { + other.is_infinity() + } else { + infinity_out + }; + + let result: P = P::from_coordinates(x_out, y_out, infinity_out); + result +} + +/// Performs an ECC scalar multiplication using an [AffineTranscript] generated via unconstrained functions. +/// +/// # Arguments +/// +/// * `transcript` - The affine transcript used for the operation. +/// * `scalar` - The scalar value to multiply with the elliptic curve point. +/// +/// # Returns +/// +/// The result of the scalar multiplication as an elliptic curve point. +/// +/// # Note +/// +/// This function assumes the transcript is generated using unconstrained functions. +pub(crate) fn mul_with_hint>( + point: P, + scalar: ScalarField, + transcript: [AffineTranscript; NTranscriptSlices], +) -> P { + // Compute a 4-bit lookup table of multiples of P + let (input, scalar) = if point.is_infinity() { + (P::one(), ScalarField::zero()) + } else { + (point, scalar) + }; + let T: PointTable = PointTable::new_with_hint::

( + input, + [ + transcript[0], + transcript[1], + transcript[2], + transcript[3], + transcript[4], + transcript[5], + transcript[6], + transcript[7], + ], + ); + + // Init the accumulator from the most significant scalar slice + let mut accumulator: P = P::offset_generator(); + let mut accumulator = incomplete_add_with_hint::( + accumulator, + T.get::

(scalar.base4_slices[0] as u32), + transcript[3 + 5], + ); + + // Perform the "double and add" algorithm but in steps of 4 bits, using the lookup table T to extract 4-bit multiples of P + for i in 1..NScalarSlices { + accumulator = double_with_hint::(accumulator, transcript[4 + 5 * i]); + accumulator = double_with_hint::(accumulator, transcript[5 + 5 * i]); + accumulator = double_with_hint::(accumulator, transcript[6 + 5 * i]); + accumulator = double_with_hint::(accumulator, transcript[7 + 5 * i]); + accumulator = incomplete_add_with_hint::( + accumulator, + T.get::

(scalar.base4_slices[i] as u32), + transcript[8 + 5 * i], + ); + } + + // windowed non-adjacent form can only represent odd scalar values. + // if value is even, the result will be off by one and we need to subtract the input point + accumulator = conditional_incomplete_subtract_with_hint::( + accumulator, + input, + scalar.skew, + transcript[4 + 5 * NScalarSlices], + ); + + accumulator = sub_with_hint::( + accumulator, + P::offset_generator_final(), + transcript[5 + 5 * NScalarSlices], + ); + accumulator +} + +fn msm_with_hint>( + mut points: [P; Size], + mut scalars: [ScalarField; Size], + transcript: [AffineTranscript; NTranscriptSlices], +) -> P { + let mut accumulator = msm_with_hint_internal::( + points, + scalars, + transcript, + ); + accumulator = sub_with_hint::( + P::offset_generator_final(), + accumulator, + transcript[10 * Size + (4 + Size) * (NScalarSlices - 1)], + ); + accumulator +} + +unconstrained fn get_mul_transcript>( + point: P, + scalar: ScalarField, +) -> [AffineTranscript; 6 + NScalarSlices * 5] { + let tmp: curve_jac::CurveJ = curve_jac::CurveJ::from(point); + let (_, transcript) = tmp.mul(scalar); + transcript +} + +fn evaluate_linear_expression, let NScalarSlices: u32, let NMuls: u32, let NAdds: u32>( + mul_points: [Curve; NMuls], + mul_scalars: [ScalarField; NMuls], + add_points: [Curve; NAdds], +) -> Curve { + let transcript: [AffineTranscript; NScalarSlices * NMuls + NScalarSlices * 4 + NMuls * 9 + NAdds - 3] = unsafe { + curve_jac::CurveJ::::compute_linear_expression_transcript( + mul_points, + mul_scalars, + add_points, + ) + .1 + }; + let mut _inputs: [Curve; NMuls] = [BigCurve::one(); NMuls]; + let mut _scalars: [scalar_field::ScalarField; NMuls] = + [scalar_field::ScalarField::zero(); NMuls]; + for i in 0..NMuls { + let (input, scalar) = if mul_points[i].is_infinity() { + (BigCurve::one(), ScalarField::zero()) + } else { + (mul_points[i], mul_scalars[i]) + }; + _inputs[i] = input; + _scalars[i] = scalar; + } + let msm_points = _inputs; + let scalars = _scalars; + + let mut tables: [PointTable; NMuls] = [PointTable::empty(); NMuls]; + for i in 0..NMuls { + let mut table_transcript: [AffineTranscript; 8] = [AffineTranscript::new(); 8]; + for j in 0..8 { + table_transcript[j] = transcript[i * 8 + j]; + } + tables[i] = PointTable::::new_with_hint::(msm_points[i], table_transcript); + } + + // Init the accumulator from the most significant scalar slice + let mut accumulator: Curve = BigCurve::offset_generator(); + let mut accumulator = incomplete_add_with_hint::( + accumulator, + tables[0].get::(scalars[0].base4_slices[0] as u32), + transcript[8 * NMuls], + ); + for i in 1..NMuls { + accumulator = incomplete_add_with_hint::( + accumulator, + tables[i].get::(scalars[i].base4_slices[0] as u32), + transcript[8 * NMuls + i], + ); + } + + // Perform the "double and add" algorithm but in steps of 4 bits, using the lookup table T to extract 4-bit multiples of P + for i in 1..NScalarSlices { + accumulator = double_with_hint::( + accumulator, + transcript[9 * NMuls + (4 + NMuls) * (i - 1)], + ); + accumulator = double_with_hint::( + accumulator, + transcript[9 * NMuls + (4 + NMuls) * (i - 1) + 1], + ); + accumulator = double_with_hint::( + accumulator, + transcript[9 * NMuls + (4 + NMuls) * (i - 1) + 2], + ); + accumulator = double_with_hint::( + accumulator, + transcript[9 * NMuls + (4 + NMuls) * (i - 1) + 3], + ); + for j in 0..NMuls { + accumulator = incomplete_add_with_hint::( + accumulator, + tables[j].get::(scalars[j].base4_slices[i] as u32), + transcript[9 * NMuls + (4 + NMuls) * (i - 1) + 4 + j], + ); + } + } + + // 9 * Size + (4 + Size) * (NScalarSlices - 1) - 1 + // 9 + 5 * NScalarSlices - 6 + // windowed non-adjacent form can only represent odd scalar values. + // if value is even, the result will be off by one and we need to subtract the input point + for i in 0..NMuls { + accumulator = conditional_incomplete_subtract_with_hint::( + accumulator, + msm_points[i], + scalars[i].skew, + transcript[9 * NMuls + (4 + NMuls) * (NScalarSlices - 1) + i], + ); + } + + for i in 0..NAdds { + accumulator = conditional_incomplete_add_with_hint::( + accumulator, + add_points[i], + !add_points[i].is_infinity(), + transcript[10 * NMuls + (4 + NMuls) * (NScalarSlices - 1) + i], + ); + } + + accumulator = sub_with_hint::( + accumulator, + BigCurve::offset_generator_final(), + transcript[NScalarSlices * NMuls + NScalarSlices * 4 + NMuls * 9 + NAdds - 4], + ); + + accumulator +} + +/// A lookup table used for scalar multiplications using windowed non-adjacent form (WNAF). +/// +/// The scalar multiplier is sliced into 4-bit chunks, each represented in WNAF (values in the range [-15, -13, ..., 15]). +/// A table `T` is computed containing point multiples corresponding to these 4-bit WNAF values: `T = ([-15[P], -13[P], ..., 15[P]])`. +/// +/// The accumulator is initialized with `T[most significant WNAF slice]`. +/// For each remaining slice (starting from the most significant), the accumulator is doubled 4 times, +/// then `T[slice[i]]` is added to the accumulator. +/// +/// For small multiscalar multiplications (fewer than 512 points), this approach minimizes the number of addition operations. +struct PointTable { + x: [B; 16], + y: [B; 16], +} + +impl PointTable { + pub(crate) fn empty() -> Self { + PointTable { x: [B::zero(); 16], y: [B::zero(); 16] } + } + + /// Constructs a `PointTable` from an input point and an `AffineTranscript` containing the required modular inverses. + /// + /// # Arguments + /// + /// * `point` - The input point to be used for constructing the table. + /// * `transcript` - An `AffineTranscript` object that holds the necessary modular inverses. + /// + /// # Details + /// + /// See [`CurveJ::mul`] for an example of how `AffineTranscript` objects are generated and used. + pub(crate) fn new_with_hint>( + point: P, + transcript: [AffineTranscript; 8], + ) -> Self { + let mut result = PointTable { x: [B::zero(); 16], y: [B::zero(); 16] }; + + let D2: P = double_with_hint::(point, transcript[0]); + + result.x[8] = point.x(); + result.y[8] = point.y(); + result.x[7] = point.x(); + result.y[7] = point.y().neg(); + + let mut A = point; + for i in 1..8 { + A = incomplete_add_with_hint::(A, D2, transcript[i]); + result.x[8 + i] = A.x(); + result.y[8 + i] = A.y(); + result.x[7 - i] = A.x(); + result.y[7 - i] = A.y().neg(); + } + result + } + + /// Retrieves a value from the lookup table. + /// + /// If the backend supports efficient memory lookups, this operation can be highly efficient. + /// For example, using the barretenberg backend, lookups on 256-bit curves may require only + /// around 12 constraints. + pub(crate) fn get>(self, idx: u32) -> P { + P::from_coordinates(self.x[idx], self.y[idx], false) + } +} diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/scalar_field.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/scalar_field.nr new file mode 100644 index 0000000..a52782a --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/scalar_field.nr @@ -0,0 +1,416 @@ +use dep::bignum::BigNum; + +/// Represents a scalar multiplier as a sequence of 4-bit slices. +/// +/// # Overview +/// `ScalarField` efficiently encodes scalars for twisted Edwards curve operations. Since these curves +/// typically have prime group orders that fit within a field element, scalars can often be reconstructed +/// from their 4-bit slices by summing the slices and verifying equality with the original scalar. +/// +/// For arbitrary field elements (scalars that may be multiples of the curve's group order), additional +/// validation is required. In these cases, the sum of the 4-bit slices, interpreted as an integer, +/// must be less than the field modulus. This check is computationally expensive and avoided when possible. +/// +/// The `ScalarField` type is flexible: +/// - `ScalarField<63>`: Efficient bitslice conversions for scalars less than 2^252. +/// - `ScalarField<64>`: Supports bitslice conversions for arbitrary field elements. +/// +/// **Note:** The bit values in `ScalarField` are not constrained to be less than the curve's group order. +/// This type is intended for use in scalar multiplication, where all operations are performed modulo the +/// curve order. +pub struct ScalarField { + pub(crate) base4_slices: [u8; N], + pub(crate) skew: bool, +} + +// 1, 2, 3, 4 +unconstrained fn get_wnaf_slices(x: Field) -> ScalarField { + let mut base4_slices: [u8; N] = [0; N]; + let bytes = x.to_le_bytes::<32>(); + let mut nibbles: [u8; N] = [0; N]; + nibbles = extract_nibbles_from_bytes(bytes); + + let skew: bool = nibbles[0] & 1 == 0; + nibbles[0] = nibbles[0] + (skew as u8); + base4_slices[N - 1] = (nibbles[0] + 15) / 2; + + for i in 1..N { + let mut nibble: u8 = nibbles[i]; + base4_slices[N - 1 - i] = (nibble + 15) / 2; + if (nibble & 1 == 0) { + base4_slices[N - 1 - i] += 1; + base4_slices[N - i] -= 8; + } + } + + ScalarField { base4_slices, skew } +} + +unconstrained fn get_wnaf_slices2(x: B) -> ScalarField +where + B: BigNum, +{ + let mut base4_slices: [u8; N] = [0; N]; + let mut nibbles: [[u8; 30]; (N / 30) + 1] = [[0; 30]; (N / 30) + 1]; + let x: [u128; _] = x.get_limbs(); + for i in 0..x.len() { + let bytes = (x[i] as Field).to_le_bytes::<30>(); + nibbles[i] = extract_nibbles_from_bytes(bytes); + } + + let skew: bool = nibbles[0][0] & 1 == 0; + nibbles[0][0] = nibbles[0][0] + (skew as u8); + base4_slices[N - 1] = (nibbles[0][0] + 15) / 2; + + for i in 1..N { + let major_index = i / 30; + let minor_index = i % 30; + let mut nibble: u8 = nibbles[major_index][minor_index]; + base4_slices[N - 1 - i] = (nibble + 15) / 2; + if (nibble & 1 == 0) { + base4_slices[N - 1 - i] += 1; + base4_slices[N - i] -= 8; + } + } + + ScalarField { base4_slices, skew } +} + +fn get_modulus_slices() -> [u8; N] { + let mut expected_slices: [u8; N] = [0; N]; + + if N == 64 { + let slice: [u8; 64] = [ + 9, 8, 3, 2, 2, 7, 3, 9, 7, 0, 9, 8, 13, 0, 1, 4, 13, 12, 2, 8, 2, 2, 13, 11, 4, 0, 12, + 0, 10, 12, 2, 14, 9, 4, 1, 9, 15, 4, 2, 4, 3, 12, 13, 12, 11, 8, 4, 8, 10, 1, 15, 0, 15, + 10, 12, 9, 15, 8, 0, 0, 0, 0, 0, 0, + ]; + for i in 0..N { + expected_slices[i] = slice[i]; + } + } else if N == 65 { + let slice: [u8; 65] = [ + 8, 1, 8, 3, 2, 2, 7, 3, 9, 7, 0, 9, 8, 13, 0, 1, 4, 13, 12, 2, 8, 2, 2, 13, 11, 4, 0, + 12, 0, 10, 12, 2, 14, 9, 4, 1, 9, 15, 4, 2, 4, 3, 12, 13, 12, 11, 8, 4, 8, 10, 1, 15, 0, + 15, 10, 12, 9, 15, 8, 0, 0, 0, 0, 0, 0, + ]; + for i in 0..N { + expected_slices[i] = slice[i]; + } + } else if N > 65 { + // For N > 65, we need to insert zeros at the beginning + let num_zeros = N - 65; + expected_slices[0] = 8; + for i in 1..num_zeros + 1 { + expected_slices[i] = 0; + } + let slice: [u8; 65] = [ + 8, 1, 8, 3, 2, 2, 7, 3, 9, 7, 0, 9, 8, 13, 0, 1, 4, 13, 12, 2, 8, 2, 2, 13, 11, 4, 0, + 12, 0, 10, 12, 2, 14, 9, 4, 1, 9, 15, 4, 2, 4, 3, 12, 13, 12, 11, 8, 4, 8, 10, 1, 15, 0, + 15, 10, 12, 9, 15, 8, 0, 0, 0, 0, 0, 0, + ]; + for i in num_zeros + 1..N { + expected_slices[i] = slice[i - num_zeros]; + } + } + expected_slices +} + +fn compare_scalar_field_to_bignum(result: ScalarField) { + let expected_slices: [u8; N] = get_modulus_slices::(); + + // Lexicographic comparison: stop when we find a strictly smaller number + let mut should_continue: bool = true; + for i in 0..N { + if should_continue { + if result.base4_slices[i] < expected_slices[i] { + // Found a strictly smaller number, we can stop - this is valid + should_continue = false; + } else if result.base4_slices[i] > expected_slices[i] { + // Found a strictly larger number, this is invalid + panic(f"Reconstructed number is greater than modulus"); + } + // If equal, continue to the next element (should_continue remains true) + } + } +} + +impl std::convert::From for ScalarField { + + /// Constructs an instance from a field element. + fn from(input: Field) -> Self { + // Safety: efficient wnaf slicing + let result = unsafe { get_wnaf_slices(input) }; + + if !std::runtime::is_unconstrained() { + // Enforce that limbs are all 4 bits. + for i in 0..N { + (result.base4_slices[i] as Field).assert_max_bit_size::<4>(); + } + + // Enforce consistency with `input`. + let reconstructed_input: Field = result.into(); + assert_eq(reconstructed_input, input); + if N >= 64 { + compare_scalar_field_to_bignum(result); + } + } + result + } +} + +impl std::convert::Into for ScalarField { + /** + * @brief construct from tuple of field elements + * @details use this method instead of `new` if you know x/y is on the curve + **/ + fn into(self: Self) -> Field { + // TODO: This is susceptible to overflow when N is large! + if !std::runtime::is_unconstrained() { + if N >= 64 { + compare_scalar_field_to_bignum(self); + } + } + let mut acc: Field = 0; + for i in 0..N { + acc = acc * 16; + acc = acc + (self.base4_slices[i] as Field) * 2 - 15; + } + acc -= self.skew as Field; + acc + } +} + +impl ScalarField { + pub fn len(_: Self) -> u32 { + N + } + + pub fn zero() -> Self { + let mut result: Self = ScalarField { base4_slices: [0; N], skew: true }; + result.base4_slices[0] = 8; // 8 = numeric value of 1, 0 = numeric value of -15 + result + } + + // Note: I can't propagate ModulusBits or NumLimbs from a generic that satisfies BigNum due to bugs, so we have to pass NumLimbs and Params in directly. disgusting! + pub fn from_bignum(x: B) -> Self + where + B: BigNum, + { + x.validate_in_field(); + // Safety: separate verification + let mut slices_result = unsafe { get_wnaf_slices2(x) }; + let mut slices = slices_result.base4_slices; + let skew = slices_result.skew; + for i in 0..N { + (slices[i] as Field).assert_max_bit_size::<4>(); + } + let mut result = B::zero(); + let mut count: u32 = 0; + { + let mut acc: u128 = 0; + let mut last_bits = (result.modulus_bits() % 120) as u64; + if (last_bits == 0) { + last_bits = 120; + } + let mut last_nibbles = (last_bits / 4) + 1 as u64; + for _ in 0..last_nibbles { + acc = acc * 16; + acc = acc + (slices[count] as u128) * 2 - 15; + count = count + 1; + } + result.set_limb(result.num_limbs() - 1, acc); + } + for i in 1..result.num_limbs() { + // Using a Field type to allow for negative numbers. + let mut acc: Field = 0; + for _ in 0..30 { + acc = acc * 16; + acc = acc + (slices[count] as Field) * 2 - 15; + count = count + 1; + } + // Handle overflow using helper function + let acc_u128 = handle_overflow::(acc, &mut result, i); + result.set_limb(result.num_limbs() - 1 - i, acc_u128); + } + result.set_limb(0, result.get_limb(0) - skew as u128); + assert(result == x); + Self { base4_slices: slices, skew } + } + + pub fn into_bignum(self) -> B + where + B: BigNum, + { + let mut result = B::zero(); + let mut count: u32 = 0; + { + let mut acc: u128 = 0; + let mut last_bits = (result.modulus_bits() % 120) as u64; + if (last_bits == 0) { + last_bits = 120; + } + let mut last_nibbles = (last_bits / 4) + 1 as u64; + for _ in 0..last_nibbles { + acc = acc * 16; + acc = acc + (self.base4_slices[count] as u128) * 2 - 15; + count = count + 1; + } + result.set_limb(result.num_limbs() - 1, acc); + } + for i in 1..result.num_limbs() { + // Using a Field type to allow for negative numbers. + let mut acc: Field = 0; + for _ in 0..30 { + acc = acc * 16; + acc = acc + (self.base4_slices[count] as Field) * 2 - 15; + count = count + 1; + } + // Handle overflow using helper function + let acc_u128 = handle_overflow::(acc, &mut result, i); + result.set_limb(result.num_limbs() - 1 - i, acc_u128); + } + result.set_limb(0, result.get_limb(0) - self.skew as u128); + result + } + + pub fn new() -> Self { + Self { base4_slices: [0; N], skew: false } + } + + pub fn get(self, idx: u32) -> u8 { + self.base4_slices[idx] + } +} + +pub(crate) unconstrained fn extract_nibbles_from_bytes( + bytes: [u8; M], +) -> [u8; N] { + let mut result: [u8; N] = [0; N]; + let mut nibble_idx = 0; + + for i in 0..M { + if nibble_idx >= N { + break; + } + // Extract low nibble (bits 0-3) + result[nibble_idx] = bytes[i] & 0x0F; + nibble_idx += 1; + + if nibble_idx >= N { + break; + } + // Extract high nibble (bits 4-7) + result[nibble_idx] = (bytes[i] >> 4); + nibble_idx += 1; + } + + result +} + +// Helper function to handle overflow in wNAF reconstruction +fn handle_overflow(acc: Field, result: &mut B, limb_index: u32) -> u128 { + let mut acc_u128: u128 = acc as u128; + + // Handle negative numbers. If the number is negative, it is greater than 2^120 in Field. + // All positive numbers are less than 2^120 in Field. + // For example, 42 is -6 + 3 * 2^4 with wnaf algorithm, but it should be 42 = 10 + 2 * 2^4 + // To get the actual number 10, we need to subtract the number 6 from 2^4. + if acc_u128 >= 0x1000000000000000000000000000000 { + // find the actual number needed to be subtracted. + let reverse = (acc * -1) as u128; + acc_u128 = (1 as u128 << 120) - reverse; + result.set_limb( + result.num_limbs() - limb_index, + result.get_limb(result.num_limbs() - limb_index) - 1, + ); + } + acc_u128 +} + +mod tests { + use crate::crypto::noir_bigcurve_vendor::scalar_field::get_modulus_slices; + use crate::crypto::noir_bigcurve_vendor::scalar_field::ScalarField; + #[test] + // test even number of nibbles + unconstrained fn fuzz_test_scalar_field_conversion(f: Field) { + let scalar_field: ScalarField<64> = ScalarField::from(f); + let scalar_field2 = scalar_field.into(); + assert(f == scalar_field2); + } + #[test] + // test odd number of nibbles + unconstrained fn fuzz_test_scalar_field_conversion2(f: u128) { + // 2^124 -1, 31 nibbles + let mask_124: u128 = 0x10000000000000000000000000000000 - 1; + let val: u128 = f & mask_124; + let scalar_field: ScalarField<31> = ScalarField::from(val as Field); + let scalar_field2 = scalar_field.into(); + assert(val as Field == scalar_field2); + } + #[test] + unconstrained fn test_get_modulus_slices() { + let modulus_slices: [u8; 64] = get_modulus_slices::<64>(); + assert( + modulus_slices + == [ + 9, 8, 3, 2, 2, 7, 3, 9, 7, 0, 9, 8, 13, 0, 1, 4, 13, 12, 2, 8, 2, 2, 13, 11, 4, + 0, 12, 0, 10, 12, 2, 14, 9, 4, 1, 9, 15, 4, 2, 4, 3, 12, 13, 12, 11, 8, 4, 8, + 10, 1, 15, 0, 15, 10, 12, 9, 15, 8, 0, 0, 0, 0, 0, 0, + ], + ); + let modulus_slices2: [u8; 65] = get_modulus_slices::<65>(); + assert( + modulus_slices2 + == [ + 8, 1, 8, 3, 2, 2, 7, 3, 9, 7, 0, 9, 8, 13, 0, 1, 4, 13, 12, 2, 8, 2, 2, 13, 11, + 4, 0, 12, 0, 10, 12, 2, 14, 9, 4, 1, 9, 15, 4, 2, 4, 3, 12, 13, 12, 11, 8, 4, 8, + 10, 1, 15, 0, 15, 10, 12, 9, 15, 8, 0, 0, 0, 0, 0, 0, + ], + ); + let modulus_slices3: [u8; 68] = get_modulus_slices::<68>(); + assert( + modulus_slices3 + == [ + 8, 0, 0, 0, 1, 8, 3, 2, 2, 7, 3, 9, 7, 0, 9, 8, 13, 0, 1, 4, 13, 12, 2, 8, 2, 2, + 13, 11, 4, 0, 12, 0, 10, 12, 2, 14, 9, 4, 1, 9, 15, 4, 2, 4, 3, 12, 13, 12, 11, + 8, 4, 8, 10, 1, 15, 0, 15, 10, 12, 9, 15, 8, 0, 0, 0, 0, 0, 0, + ], + ); + } + #[test(should_fail_with = "Reconstructed number is greater than modulus")] + fn test_get_modulus_slices_fail_64() { + //13th nibble is 14, which is greater than the modulus + let modulus_slices: [u8; 64] = [ + 9, 8, 3, 2, 2, 7, 3, 9, 7, 0, 9, 8, 14, 0, 1, 4, 13, 12, 2, 8, 2, 2, 13, 11, 4, 0, 12, + 0, 10, 12, 2, 14, 9, 4, 1, 9, 15, 4, 2, 4, 3, 12, 13, 12, 11, 8, 4, 8, 10, 1, 15, 0, 15, + 10, 12, 9, 15, 8, 0, 0, 0, 0, 0, 0, + ]; + let mut result: ScalarField<64> = ScalarField { base4_slices: modulus_slices, skew: true }; + let _ = result.into(); + } + #[test(should_fail_with = "Reconstructed number is greater than modulus")] + fn test_get_modulus_slices_fail_65() { + //modulus slice represents a number that is greater than the modulus + let modulus_slices2 = [ + 8, 1, 8, 3, 2, 2, 7, 3, 10, 8, 0, 9, 8, 13, 0, 1, 4, 13, 12, 2, 8, 2, 2, 13, 11, 4, 0, + 12, 0, 10, 12, 2, 14, 9, 4, 1, 9, 15, 4, 2, 4, 3, 12, 13, 12, 11, 8, 4, 8, 10, 1, 15, 0, + 15, 10, 12, 9, 15, 8, 0, 0, 0, 0, 0, 0, + ]; + let mut result: ScalarField<65> = ScalarField { base4_slices: modulus_slices2, skew: true }; + let _ = result.into(); + } + + #[test(should_fail_with = "Reconstructed number is greater than modulus")] + fn test_get_modulus_slices_fail_68() { + //modulus slice represents a number that is greater than the modulus + let modulus_slices3 = [ + 8, 0, 0, 0, 2, 8, 3, 2, 2, 7, 3, 9, 7, 0, 9, 8, 13, 0, 1, 4, 13, 12, 2, 8, 2, 2, 13, 11, + 4, 0, 12, 0, 10, 12, 2, 14, 9, 4, 1, 9, 15, 4, 2, 4, 3, 12, 13, 12, 11, 8, 4, 8, 10, 1, + 15, 0, 15, 10, 12, 9, 15, 8, 0, 0, 0, 0, 0, 0, + ]; + let mut result: ScalarField<68> = ScalarField { base4_slices: modulus_slices3, skew: true }; + let _ = result.into(); + } + +} diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils.nr new file mode 100644 index 0000000..2ac0832 --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils.nr @@ -0,0 +1,2 @@ +pub(crate) mod hash_to_curve; +// pub(crate) mod derive_offset_generators; diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils/derive_offset_generators.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils/derive_offset_generators.nr new file mode 100644 index 0000000..21b54a6 --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils/derive_offset_generators.nr @@ -0,0 +1,169 @@ +use crate::BigCurve; +use crate::curve_jac::CurveJ; + +use crate::curves::bn254::BN254; +use bignum::BigNum; +use bignum::BN254_Fq; +unconstrained fn compute_offset_generators( + cofactor: Field, +) -> ([Fq; 2], [Fq; 2]) +where + Fq: BigNum, + Curve: BigCurve, +{ + let seed: [u8; 25] = "bigcurve offset generator".as_bytes(); + + // we only need well-defined parameters for a and b, for hash_to_curve to work + // (no offset generators needed) + let g: Curve = Curve::hash_to_curve(seed); + + let g_init = CurveJ::::from(g); + let mut gen = g_init; + + let cofactor_bits: [u1; 128] = cofactor.to_be_bits(); + let mut it: u32 = 0; + for i in 0..128 { + if (cofactor_bits[i] == 1) { + it = i + 1; + break; + } + } + + for i in it..128 { + gen = gen.dbl().0; + if (cofactor_bits[i] == 1) { + gen = gen.incomplete_add(g_init).0; + } + } + + let mut offset_generator_initial: [Fq; 2] = [Fq::new(); 2]; + let mut offset_generator_final: [Fq; 2] = [Fq::new(); 2]; + + { + let mut genz = gen.z; + genz = genz.__invmod(); + let zz = genz.__mul(genz); + let zzz = zz.__mul(genz); + + offset_generator_initial[0] = gen.x.__mul(zz); + offset_generator_initial[1] = gen.y.__mul(zzz); + } + + let end = (NScalarSlices - 1) * 4; + for _ in 0..end { + gen = gen.dbl().0; + } + { + let mut genz = gen.z; + genz = genz.__invmod(); + let zz = genz.__mul(genz); + let zzz = zz.__mul(genz); + + offset_generator_final[0] = gen.x.__mul(zz); + offset_generator_final[1] = gen.y.__mul(zzz); + } + + (offset_generator_initial, offset_generator_final) +} + +unconstrained fn compute_and_print_offset_generators( + bignumstr: str, + curvestr: str, + cofactor: Field, +) +where + Fq: BigNum, + Curve: BigCurve, +{ + let a: Fq = Curve::a(); + let b: Fq = Curve::b(); + let one: Curve = Curve::one(); + + let input = Curve::one(); + input.validate_on_curve(); + + let (offset_generator_initial, offset_generator_final) = + compute_offset_generators::(cofactor); + + println(f"pub struct {curvestr} {{}}"); + + println(f" fn a() -> {bignumstr} {{ {a} }}"); + println(f" fn b() -> {bignumstr} {{ {b} }}"); + println(f" fn one() -> [{bignumstr}; 2] {{ {one} }}"); + println( + f" fn offset_generator() -> [{bignumstr}; 2] {{ {offset_generator_initial} }}", + ); + println( + f" fn offset_generator_final() -> [{bignumstr}; 2] {{ {offset_generator_final} }}", + ); + println("}}"); +} + +#[test] +fn test_compute_and_print_offset_generators() { + unsafe { + let _ = BN254::one(); + compute_and_print_offset_generators::("BN254_Fq", "BN254", 1); + // compute_and_print_offset_generators::("Pallas_Fq", "Pallas", 1); + // compute_and_print_offset_generators::("Vesta_Fq", "Vesta", 1); + // compute_and_print_offset_generators::( + // "BLS12_377_Fq", + // "BLS12_377", + // 0x170b5d44300000000000000000000000 + // ); + // compute_and_print_offset_generators::( + // "BLS12_381_Fq", + // "BLS12_381", + // 0x396C8C005555E1568C00AAAB0000AAAB + // ); + // compute_and_print_offset_generators::("MNT4_753_Fq", "MNT4_753", 1); + // compute_and_print_offset_generators::("MNT6_753_Fq", "MNT6_753", 1); + // compute_and_print_offset_generators::("Secp256k1_Fq", "Secp256k1", 1); + // compute_and_print_offset_generators::("Secp256r1_Fq", "Secp256r1", 1); + // compute_and_print_offset_generators::("Secp384r1_Fq", "Secp384r1", 1); + // cofactor = 0x170b5d44300000000000000000000000 booooo + } +} + +pub(crate) unconstrained fn verify_offset_generators(cofactor: Field) +where + Fq: BigNum, + Curve: BigCurve, +{ + // For each curve, compute the offset generators and verify they match the ones in the curve parameters + let seed: [u8; 25] = "bigcurve offset generator".as_bytes(); + + // we only need well-defined parameters for a and b, for hash_to_curve to work + // (no offset generators needed) + let g: Curve = Curve::hash_to_curve(seed); + + let g_init = CurveJ::::from(g); + let mut gen = g_init; + + let cofactor_bits: [u1; 128] = cofactor.to_be_bits(); + let mut it: u32 = 0; + for i in 0..128 { + if (cofactor_bits[i] == 1) { + it = i + 1; + break; + } + } + + for i in it..128 { + gen = gen.dbl().0; + if (cofactor_bits[i] == 1) { + gen = gen.incomplete_add(g_init).0; + } + } + let mut genz = gen.z; + genz = genz.__invmod(); + let zz = genz.__mul(genz); + let zzz = zz.__mul(genz); + let computed_initial = [gen.x.__mul(zz), gen.y.__mul(zzz)]; + // Verify against the values in the curve parameters + let expected_initial = Curve::offset_generator(); + println(f"expected_initial: {expected_initial}"); + println(f"computed_initial: {computed_initial}"); + assert_eq(computed_initial[0], expected_initial.x(), "Initial offset generator x mismatch"); + assert_eq(computed_initial[1], expected_initial.y(), "Initial offset generator y mismatch"); +} diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils/hash_to_curve.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils/hash_to_curve.nr new file mode 100644 index 0000000..18b9df0 --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto/noir_bigcurve_vendor/utils/hash_to_curve.nr @@ -0,0 +1,90 @@ +use dep::bignum::BigNum; + +unconstrained fn hash_to_curve_inner( + seedbase: Field, + seed_counter: Field, + a: Fq, + b: Fq, +) -> (Fq, Fq, Field) +where + Fq: BigNum, +{ + let seedhash = dep::poseidon::poseidon2::Poseidon2::hash([seedbase, seed_counter], 2); + // TODO: assert in field? + let seedhash: [u8; 32] = seedhash.to_le_bytes(); + + let x = Fq::derive_from_seed(seedhash); + + let yy = x * x * x + a * x + b; + yy.validate_in_field(); + yy.validate_in_range(); + x.validate_in_field(); + x.validate_in_range(); + let y = yy.__tonelli_shanks_sqrt(); + let yy_reconstructed = y.unwrap_unchecked() * y.unwrap_unchecked(); + let mut result: (Fq, Fq, Field) = (x, y.unwrap_unchecked(), seed_counter); + if (((yy_reconstructed == yy) & (y.is_some())) == false) { + result = hash_to_curve_inner(seedbase, seed_counter + 1, a, b); + } + if (y.is_some()) { + y.unwrap_unchecked().validate_in_field(); + y.unwrap_unchecked().validate_in_range(); + } + result +} + +unconstrained fn __hash_to_curve_witgen( + seed: [u8; SeedBytes], + a: Fq, + b: Fq, +) -> (Fq, Fq, Field) +where + Fq: BigNum, +{ + let hashed_seed = poseidon_hash_bytes(seed); + hash_to_curve_inner(hashed_seed, 0, a, b) +} + +fn poseidon_hash_bytes(seed: [u8; SeedBytes]) -> Field { + let mut padded_seed: [u8; (SeedBytes / 31 + 1) * 31] = [0; (SeedBytes / 31 + 1) * 31]; + for i in 0..SeedBytes { + padded_seed[i] = seed[i]; + } + let packed_seed: [Field; SeedBytes / 31 + 1] = [0; SeedBytes / 31 + 1]; + for i in 0..SeedBytes / 31 + 1 { + let mut packed: Field = 0; + for _ in 0..31 { + packed *= 256; + packed += padded_seed[i] as Field; + } + } + let hashed_seed: Field = dep::poseidon::poseidon2::Poseidon2::hash(packed_seed, SeedBytes / 31 + 1); + hashed_seed +} +pub fn hash_to_curve(seed: [u8; SeedBytes], a: Fq, b: Fq) -> (Fq, Fq) +where + Fq: BigNum, +{ + // Safety: efficient hash to curve witness generation + let (_, y, salt) = unsafe { __hash_to_curve_witgen(seed, a, b) }; + let outer_hash: Field = poseidon_hash_bytes(seed); + + let inner_hash = dep::poseidon::poseidon2::Poseidon2::hash([outer_hash, salt], 2); + + // Field membership is implicitly enforced by to_le_bytes conversion below + let inner_hash: [u8; 32] = inner_hash.to_le_bytes(); + let x = Fq::derive_from_seed(inner_hash); + let yy = x * x * x + a * x + b; + assert(y * y == yy); + + let parity_flag = (inner_hash[0] & 1) == 1; + + let negated_y = y.neg(); + let output_y = if parity_flag { y } else { negated_y }; + + x.validate_in_field(); + x.validate_in_range(); + output_y.validate_in_field(); + output_y.validate_in_range(); + (x, output_y) +} diff --git a/proof_a_ecdsa_p384_sha384_v2/src/crypto_utils.nr b/proof_a_ecdsa_p384_sha384_v2/src/crypto_utils.nr new file mode 100644 index 0000000..9e0ff83 --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/crypto_utils.nr @@ -0,0 +1,61 @@ +// P-384 ECDSA imports (uses local vendored noir_bigcurve) +use crate::crypto::noir_bigcurve_vendor::curves::secp384r1::{Secp384r1, Secp384r1Scalar}; +use crate::crypto::noir_bigcurve_vendor::BigCurve; +// Import BigNum trait from global dep +use dep::bignum::bignum::BigNum as BigNumTrait; +use dep::bignum::{Secp384r1_Fq, Secp384r1_Fr}; + +/// ECDSA P-384 verification +/// Verifies signature (r,s) on message_hash using public key (pk_x, pk_y) +pub fn verify_ecdsa_p384( + message_hash: [u8; 48], + pubkey_x: [u8; 48], + pubkey_y: [u8; 48], + sig_r: [u8; 48], + sig_s: [u8; 48] +) -> bool { + // Convert bytes to BigNum (big-endian) + let pk_x: Secp384r1_Fq = Secp384r1_Fq::from_be_bytes(pubkey_x); + let pk_y: Secp384r1_Fq = Secp384r1_Fq::from_be_bytes(pubkey_y); + let r: Secp384r1_Fr = Secp384r1_Fr::from_be_bytes(sig_r); + let s: Secp384r1_Fr = Secp384r1_Fr::from_be_bytes(sig_s); + + // Security: reject zero r or s (invalid per SEC1/FIPS 186-5) + assert(r != Secp384r1_Fr::zero(), "ECDSA P-384 r must not be zero"); + assert(s != Secp384r1_Fr::zero(), "ECDSA P-384 s must not be zero"); + + let e: Secp384r1_Fr = Secp384r1_Fr::from_be_bytes(message_hash); + + // Compute s^-1 mod n (unconstrained, then verify) + // Safety: __invmod is unconstrained but result is verified by s * s_inv == 1 check below + let s_inv = unsafe { s.__invmod() }; + + // Verify inverse: s * s_inv == 1 (mod n) + let check = s * s_inv; + let one = Secp384r1_Fr::one(); + assert(check == one, "s inverse failed"); + + // Compute u1 = e * s^-1 mod n + let u1_bn = e * s_inv; + let u1: Secp384r1Scalar = Secp384r1Scalar::from_bignum::(u1_bn); + + // Compute u2 = r * s^-1 mod n + let u2_bn = r * s_inv; + let u2: Secp384r1Scalar = Secp384r1Scalar::from_bignum::(u2_bn); + + // Public key point Q + let q = Secp384r1 { x: pk_x, y: pk_y, is_infinity: false }; + q.validate_on_curve(); + + // Generator point G + let g = Secp384r1::one(); + + // Compute R = u1*G + u2*Q using evaluate_linear_expression + let r_point = Secp384r1::evaluate_linear_expression([g, q], [u1, u2], []); + + // Signature valid if R.x == r (mod n) + let rx_as_fr: Secp384r1_Fr = Secp384r1_Fr::from_limbs(r_point.x.get_limbs()); + + // The signature is valid if rx mod n == r AND point is not infinity + !r_point.is_infinity & (rx_as_fr == r) +} diff --git a/proof_a_ecdsa_p384_sha384_v2/src/hash_chain.nr b/proof_a_ecdsa_p384_sha384_v2/src/hash_chain.nr new file mode 100644 index 0000000..0571446 --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/hash_chain.nr @@ -0,0 +1,549 @@ +/** + * Hash Chain Verification for Trustless Metadata Binding + * + * This module verifies that extracted metadata values (GPS, timestamp) actually + * came from the signed C2PA claim, preventing substitution attacks. + * + * The verification chain: + * 1. COSE Signature -> COSE Payload (which is claim_hash or claim_bytes) + * 2. SHA256(claim_bytes) -> claim_hash (verified via signature) + * 3. claim_bytes contains assertion_hash at known offset + * 4. SHA256(assertion_bytes) == assertion_hash + * 5. assertion_bytes contain the metadata values at known offsets + * + * Without this verification, a malicious client could: + * - Extract real GPS from signed image + * - Replace with fake GPS + * - Generate valid proof with fake location + * + * With hash chain verification, the circuit ensures: + * - The metadata values are cryptographically bound to the signature + * - Substitution of any value invalidates the proof + * + * CONSTRAINT BUDGET: + * - SHA256 in Noir: ~15k constraints per KB hashed + * - Claim bytes: typically 1-5 KB -> 15-75k constraints + * - Assertion bytes: typically 200B-2KB -> 3-30k constraints + * - Total budget: ~100k constraints for hash chain + * + * OPTIMIZATION STRATEGIES: + * 1. Use pre-computed claim_hash when claim is large (skip in-circuit hashing) + * 2. Only verify assertion hash for assertions containing sensitive data + * 3. For small claims/assertions, in-circuit SHA256 is acceptable + */ + +// SHA256 from stdlib - use digest function with generic size parameter + +/// Maximum size of claim bytes we'll hash in-circuit +/// Claims larger than this should use the pre-computed hash approach +/// v2: 1280 bytes (claims observed in samples fit; larger claims need a +/// larger size class) +pub global MAX_CLAIM_SIZE: u32 = 1280; + +/// Maximum size of EXIF assertion bytes we'll hash in-circuit +/// v2: 1280 bytes (Leica stds.exif is 1173 bytes) +pub global MAX_EXIF_ASSERTION_SIZE: u32 = 1280; + +/// Maximum size of c2pa.actions assertion bytes we'll hash in-circuit +/// Actions assertions contain edit history (c2pa.created, c2pa.edited, etc.) +/// and AI generation indicators (digitalSourceType: trainedAlgorithmicMedia) +/// v2: 1024 bytes. NOTE: Adobe Photoshop actions assertions can be 1200-1500 +/// bytes and do not fit this size class. +pub global MAX_ACTIONS_ASSERTION_SIZE: u32 = 1024; + +/// SHA256 hash output size +pub global HASH_SIZE: u32 = 32; + +/** + * Verify that claim_hash matches SHA256(claim_bytes) + * + * This binds the claim content to the signature. + * The signature verifies over claim_hash, so if this passes, + * we know claim_bytes are authentic. + * + * IMPORTANT: Uses sha256_var to hash only the first claim_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * claim bytes, not the padded version. + * + * @param claim_bytes Raw CBOR claim bytes (padded to MAX_CLAIM_SIZE) + * @param claim_length Actual length of claim bytes + * @param expected_claim_hash Pre-computed SHA256(claim_bytes) - same as signature input + */ +pub fn verify_claim_hash( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32] +) { + // Bounds check: claim_length must not exceed buffer size + assert(claim_length <= MAX_CLAIM_SIZE, "claim_length exceeds MAX_CLAIM_SIZE"); + + // Compute SHA256 of the ACTUAL claim bytes (not padded) + // sha256_var hashes only the first claim_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(claim_bytes, claim_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_claim_hash[i], + "Claim hash verification failed: claim_bytes do not match expected hash" + ); + } +} + +/** + * Extract assertion hash from claim_bytes at a known offset + * + * The claim contains references to assertions with their expected hashes. + * This function extracts the 32-byte hash at the specified offset. + * + * @param claim_bytes Raw CBOR claim bytes + * @param hash_offset Byte offset where assertion hash appears in claim + * @returns The 32-byte assertion hash from the claim + */ +pub fn extract_assertion_hash_from_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + hash_offset: u32 +) -> [u8; 32] { + let mut assertion_hash: [u8; 32] = [0; 32]; + + // Bounds check + assert( + hash_offset + 32 <= MAX_CLAIM_SIZE, + "Assertion hash offset out of bounds" + ); + + // Extract 32 bytes starting at hash_offset + for i in 0..32 { + assertion_hash[i] = claim_bytes[hash_offset + i]; + } + + assertion_hash +} + +/** + * Verify that assertion_hash matches SHA256(assertion_bytes) + * + * This binds the assertion content to the claim. + * Combined with verify_claim_hash, this creates a complete chain: + * Signature -> Claim -> Assertion -> Metadata + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR or JSON, padded) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_assertion_hash( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_EXIF_ASSERTION_SIZE, "assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Extract a u64 timestamp value from CBOR-encoded assertion bytes + * + * CBOR timestamp encoding (simplified): + * - For small values (0-23): single byte 0x00-0x17 + * - For u8: 0x18 + 1 byte + * - For u16: 0x19 + 2 bytes (big-endian) + * - For u32: 0x1a + 4 bytes (big-endian) + * - For u64: 0x1b + 8 bytes (big-endian) + * + * We extract the raw bytes and convert to u64. + * The offset should point to the START of the CBOR value (type byte). + * + * @param assertion_bytes Raw assertion bytes + * @param timestamp_offset Byte offset where timestamp CBOR value starts + * @returns Extracted timestamp as u64 + */ +pub fn extract_timestamp_from_cbor( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + timestamp_offset: u32 +) -> u64 { + let type_byte = assertion_bytes[timestamp_offset]; + + // Check CBOR type - we expect unsigned integer (major type 0) + let major_type = type_byte >> 5; + let additional_info = type_byte & 0x1f; + + // Major type 0 = unsigned integer + assert(major_type == 0, "Expected CBOR unsigned integer for timestamp"); + + let mut timestamp: u64 = 0; + + if additional_info <= 23 { + // Inline value + timestamp = additional_info as u64; + } else if additional_info == 24 { + // u8 follows - need 2 bytes total + assert(timestamp_offset + 2 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u8 timestamp exceeds buffer"); + timestamp = assertion_bytes[timestamp_offset + 1] as u64; + } else if additional_info == 25 { + // u16 follows (big-endian) - need 3 bytes total + assert(timestamp_offset + 3 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u16 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 2] as u64); + } else if additional_info == 26 { + // u32 follows (big-endian) - need 5 bytes total + assert(timestamp_offset + 5 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u32 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 24; + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 2] as u64) << 16); + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 3] as u64) << 8); + timestamp = timestamp + (assertion_bytes[timestamp_offset + 4] as u64); + } else if additional_info == 27 { + // u64 follows (big-endian) - need 9 bytes total + assert(timestamp_offset + 9 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u64 timestamp exceeds buffer"); + for i in 0..8 { + timestamp = timestamp << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 1 + i] as u64); + } + } else { + // additional_info 28-30 are reserved per CBOR RFC 8949, 31 is indefinite-length + assert(false, "Reserved or unsupported CBOR integer encoding for timestamp"); + } + + timestamp +} + +/** + * GPS BINDING SECURITY MODEL + * ========================== + * + * This module does NOT implement byte-level GPS extraction from CBOR assertions. + * This is a deliberate design choice, not a missing feature. + * + * SECURITY RATIONALE: + * ------------------- + * GPS coordinates are cryptographically bound through the hash chain: + * + * 1. verify_assertion_hash() proves: SHA256(assertion_bytes) == hash_in_claim + * 2. verify_claim_hash() proves: SHA256(claim_bytes) == signed_hash + * 3. COSE signature proves: claim was signed by trusted certificate + * + * Therefore, if the assertion bytes pass hash verification, their ENTIRE CONTENT + * is cryptographically bound to the signature. Any modification to the GPS values + * would change the hash and break verification. + * + * WHY NOT PARSE CBOR IN-CIRCUIT? + * ------------------------------ + * C2PA EXIF GPS coordinates are stored as CBOR rational number arrays: + * { "EXIF:GPSLatitude": [{n: 51, d: 1}, {n: 30, d: 1}, {n: 0, d: 1}] } // 51d 30m 0s + * + * Parsing this requires: + * - Variable-length CBOR decoding (~200+ constraints per value) + * - Rational number arithmetic (degree + minute/60 + second/3600) + * - Sign handling from GPSLatitudeRef/GPSLongitudeRef strings + * + * Total cost: ~500-1000 additional constraints for minimal security gain. + * + * The hash chain already guarantees that the client cannot substitute GPS values + * without invalidating the proof. Adding in-circuit parsing would only catch + * bugs in the client extractor, not malicious tampering. + * + * TRUST MODEL: + * ------------ + * - The CIRCUIT trusts that assertion_bytes were correctly passed from the client + * - The HASH CHAIN proves assertion_bytes match what was signed + * - The CLIENT extracts GPS from the verified bytes + * - Any GPS tampering would require finding a hash collision (computationally infeasible) + * + * For applications requiring stronger guarantees, the circuit could be extended + * to parse CBOR at specific known offsets. This is left as a future enhancement. + */ + +// NOTE: verify_gps_binding() has been intentionally removed. +// GPS binding is provided by verify_assertion_hash() in the hash chain. +// See the SECURITY RATIONALE above for details. + +/** + * Combined hash chain verification + * + * Performs the complete verification: + * 1. SHA256(claim_bytes) == expected_claim_hash (signature input) + * 2. Extract assertion_hash from claim at known offset + * 3. SHA256(assertion_bytes) == assertion_hash + * + * If all pass, we know the assertion_bytes are authentic and + * any values extracted from them are cryptographically bound to the signature. + * + * @param claim_bytes Raw claim bytes (padded) + * @param claim_length Actual claim length + * @param expected_claim_hash SHA256 of claim (same as signature message hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes (padded) + * @param assertion_length Actual assertion length + */ +pub fn verify_full_hash_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Step 1: Verify claim hash + verify_claim_hash(claim_bytes, claim_length, expected_claim_hash); + + // Step 2: Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Step 3: Verify assertion hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // At this point, we've proven: + // - claim_bytes hash to the signed value + // - assertion_bytes hash to a reference in the signed claim + // - Therefore, assertion_bytes are authentic + // - Any values in assertion_bytes are cryptographically bound + + // Silence unused warnings + let _ = claim_length; + let _ = assertion_length; +} + +/** + * Verify timestamp is bound to assertion via hash chain + * + * Combines hash chain verification with timestamp extraction. + * Proves that exact_timestamp actually came from the signed assertion. + * + * @param claim_bytes Raw claim bytes + * @param claim_length Actual claim length + * @param expected_claim_hash Expected claim hash (signature input) + * @param assertion_hash_offset Offset of assertion hash in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + * @param timestamp_offset Offset of timestamp in assertion + * @param expected_timestamp The timestamp value the circuit is using + */ +pub fn verify_timestamp_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + timestamp_offset: u32, + expected_timestamp: u64 +) { + // First verify the hash chain + verify_full_hash_chain( + claim_bytes, + claim_length, + expected_claim_hash, + assertion_hash_offset, + assertion_bytes, + assertion_length + ); + + // Then extract and verify the timestamp + let extracted_timestamp = extract_timestamp_from_cbor(assertion_bytes, timestamp_offset); + + assert( + extracted_timestamp == expected_timestamp, + "Timestamp binding failed: extracted timestamp does not match expected value" + ); +} + +/** + * Verify content hash exists in claim at specified offset + * + * SECURITY: This binds the public content_hash to the signed claim. + * Without this verification, a malicious client could substitute + * a different image's content_hash while keeping the valid signature. + * + * @param claim_bytes Raw claim bytes (CBOR encoded) + * @param content_hash_offset Byte offset where content hash appears in claim + * @param expected_content_hash The content hash (Field) to verify + */ +pub fn verify_content_hash_in_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + // Bounds check + assert( + content_hash_offset + 32 <= MAX_CLAIM_SIZE, + "Content hash offset out of bounds" + ); + + // Extract 32 bytes from claim at offset and convert to Field + let mut extracted_hash: Field = 0; + for i in 0..32 { + extracted_hash = extracted_hash * 256 + claim_bytes[content_hash_offset + i] as Field; + } + + // Verify the extracted content hash matches the public input + assert( + extracted_hash == expected_content_hash, + "Content hash binding failed: public content_hash does not match value in signed claim" + ); +} + +/** + * Verify assertion hash chain (without redundant claim hash check) + * + * Use this when claim_hash has already been verified separately. + * Verifies: SHA256(assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + */ +pub fn verify_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // Silence unused warning + let _ = assertion_length; +} + +/** + * Verify actions assertion hash matches SHA256(actions_assertion_bytes) + * + * This is the same as verify_assertion_hash but for the larger actions buffer. + * Actions assertions (c2pa.actions.v2) must fit MAX_ACTIONS_ASSERTION_SIZE. + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR, padded to MAX_ACTIONS_ASSERTION_SIZE) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_actions_assertion_hash( + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_ACTIONS_ASSERTION_SIZE, "actions_assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Actions assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Verify actions assertion hash chain (without redundant claim hash check) + * + * Use this for c2pa.actions.v2 assertions up to MAX_ACTIONS_ASSERTION_SIZE bytes. + * Verifies: SHA256(actions_assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw actions assertion bytes (up to MAX_ACTIONS_ASSERTION_SIZE bytes) + * @param assertion_length Actual assertion length + */ +pub fn verify_actions_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_actions_assertion_hash(assertion_bytes, assertion_length, assertion_hash); +} + +// Tests +#[test] +fn test_content_hash_binding() { + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a known content hash at offset 100 + // Content hash as bytes: 0x0000...0001 (just 1 for simplicity) + claim_bytes[131] = 1; // Last byte = 1 + + // Expected field value is 1 + let expected_hash: Field = 1; + + // This should pass + verify_content_hash_in_claim(claim_bytes, 100, expected_hash); +} + +#[test] +fn test_extract_assertion_hash() { + // Create test claim bytes with a known hash at offset 10 + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a test hash at offset 10 + let test_hash: [u8; 32] = [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 + ]; + + for i in 0..32 { + claim_bytes[10 + i] = test_hash[i]; + } + + let extracted = extract_assertion_hash_from_claim(claim_bytes, 10); + + for i in 0..32 { + assert(extracted[i] == test_hash[i]); + } +} + +#[test] +fn test_extract_cbor_timestamp_inline() { + // Test inline value (0-23) + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x17; // Inline value 23 + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 23); +} + +#[test] +fn test_extract_cbor_timestamp_u32() { + // Test u32 value + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x1a; // u32 follows + // Value: 1700000000 (0x6553F100) - a Unix timestamp + assertion_bytes[1] = 0x65; + assertion_bytes[2] = 0x53; + assertion_bytes[3] = 0xF1; + assertion_bytes[4] = 0x00; + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 1700000000); +} diff --git a/proof_a_ecdsa_p384_sha384_v2/src/main.nr b/proof_a_ecdsa_p384_sha384_v2/src/main.nr new file mode 100644 index 0000000..1d0a436 --- /dev/null +++ b/proof_a_ecdsa_p384_sha384_v2/src/main.nr @@ -0,0 +1,582 @@ +/// Apertrue ProofA ECDSA P-384 SHA-384 v2 - Certificate Chain Verification +/// +/// For a P-256 leaf certificate issued by a P-384 intermediate that signs +/// with ecdsa-with-SHA384. Same as proof_a_ecdsa_p384_v2 except the hash: +/// the full leaf TBSCertificate is a private input, hashed in-circuit with +/// SHA-384 (zkpassport/sha512) and DER-walked from offset 0 (cert_binding +/// lib). The TBS signature AlgorithmIdentifier must be ecdsa-with-SHA384 +/// (1.2.840.10045.4.3.3), so the prover picks this variant from the OID: +/// ...04 03 02 (ecdsa-with-SHA256) -> proof_a_ecdsa_p384_v2 +/// ...04 03 03 (ecdsa-with-SHA384) -> proof_a_ecdsa_p384_sha384_v2 +/// The intermediate's P-384 signature is checked over that digest, and the +/// leaf key and notBefore/notAfter come from the parsed bytes. +/// +/// DIGEST: ECDSA takes e = leftmost min(384, hashlen) bits of the hash +/// (FIPS 186-5). For SHA-384 that is the whole 384-bit digest, passed as is. +/// +/// This circuit proves: +/// 1. The intermediate CA signed (ECDSA P-384, SHA-384) the leaf TBSCertificate +/// 2. The intermediate CA is in the Oracle's promoted trust list +/// 3. The nullifier is derived from the P-256 leaf key found in that TBS +/// 4. proof_timestamp lies within that certificate's validity (dates private) +/// 5. Time range proof (graduated time disclosure) +/// 6. Location range proof (privacy circles) +/// 7. Hash chain verification +/// 8. Poseidon commitments for optional future reveal +/// +/// PUBLIC LAYOUT (index: name; one Field each unless noted) +/// 0 trust_list_root +/// 1 content_hash +/// 2 nullifier pedersen_hash([content_hash, pedersen_hash([leaf_x, leaf_y])]) +/// 3 proof_timestamp +/// 4 time_min +/// 5 time_max +/// 6 edit_time_min +/// 7 edit_time_max +/// 8 center_lat_scaled +/// 9 center_lon_scaled +/// 10 location_flags +/// 11 radius_squared_scaled +/// 12 claim_hash_commitment +/// 13 content_hash_offset +/// 14 skip_content_hash_binding +/// 15 skip_assertion_hash_verification +/// Return values: +/// 16 link_commit pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]) +/// 17 location_commitment +/// 18 time_commitment +/// 19 edit_time_commitment +/// 20..51 actions_assertion_hash (32 x u8) +/// Total 52. Versus v1: cert_not_before (4), cert_not_after (5) and +/// tbs_hash_commitment (14) are removed; every later index shifts down. + +use std::hash::pedersen_hash; +use dep::poseidon::poseidon2::Poseidon2; +use dep::cert_binding::{bind_leaf_cert_sha384, LeafCertSha384}; + +mod crypto; +mod crypto_utils; +mod hash_chain; + +use crypto_utils::verify_ecdsa_p384; +use hash_chain::{ + MAX_CLAIM_SIZE, + MAX_EXIF_ASSERTION_SIZE, + MAX_ACTIONS_ASSERTION_SIZE, + verify_claim_hash, + verify_content_hash_in_claim, + verify_assertion_chain, + verify_actions_assertion_chain, +}; + +/// Maximum leaf TBSCertificate size (DER bytes) +global MAX_TBS_SIZE: u32 = 1280; + +/// ProofA ECDSA P-384 SHA-384 v2 main entry point +fn main( + // === PUBLIC INPUTS (shared with ProofB) === + trust_list_root: pub Field, + content_hash: pub Field, + nullifier: pub Field, + proof_timestamp: pub Field, + + // === PUBLIC INPUTS: TIME RANGE BOUNDS === + time_min: pub Field, + time_max: pub Field, + + // === PUBLIC INPUTS: EDIT TIME RANGE BOUNDS (for edited images) === + // When a photo is edited (e.g., Leica capture -> Lightroom export), the capture + // and edit timestamps differ. These bounds constrain the edit/signing timestamp. + // Set to 0 when no edit occurred (direct camera capture). + edit_time_min: pub Field, // Minimum edit timestamp bound (0 if no edit) + edit_time_max: pub Field, // Maximum edit timestamp bound (0 if no edit) + + // === PUBLIC INPUTS: LOCATION PRIVACY CIRCLE === + center_lat_scaled: pub Field, + center_lon_scaled: pub Field, + location_flags: pub u8, // bit 0 = lat negative (South), bit 1 = lon negative (West) + radius_squared_scaled: pub Field, + + // === PUBLIC INPUT: Claim Hash Commitment (packed from 32 bytes to 1 Field) === + // This is Poseidon2(bytes32_to_field_array(claim_hash)). Saves 31 public input fields. + claim_hash_commitment: pub Field, + + // === PUBLIC INPUT: Content Hash Offset === + content_hash_offset: pub u32, + + // === PRIVATE: LEAF TBSCertificate (DER, zero padded past tbs_len) === + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + + // === PRIVATE: CLAIM HASH BYTES (unpacked from commitment) === + claim_hash: [u8; 32], + + // === PRIVATE: SKIP FLAGS === + skip_content_hash_binding: pub u8, + skip_assertion_hash_verification: pub u8, + + // === PRIVATE: ECDSA P-384 CERTIFICATE SIGNATURE & KEY === + cert_signature_ecdsa_p384_r: [u8; 48], + cert_signature_ecdsa_p384_s: [u8; 48], + intermediate_ecdsa_p384_pubkey_x: [u8; 48], + intermediate_ecdsa_p384_pubkey_y: [u8; 48], + + // === PRIVATE: LINKING WITNESS === + intermediate_leaf: Field, + link_blind: Field, + + // === PRIVATE: MERKLE MEMBERSHIP === + merkle_path: [Field; 8], + merkle_indices: [Field; 8], + + // === PRIVATE: EXACT TIMESTAMP === + exact_timestamp: Field, + + // === PRIVATE: EXACT GPS LOCATION === + exact_lat_scaled: Field, + exact_lon_scaled: Field, + exact_lat_is_negative: u8, + exact_lon_is_negative: u8, + + // === PRIVATE: HASH CHAIN DATA === + enable_hash_chain_verification: u8, + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + exif_assertion_hash_offset: u32, + exif_assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + exif_assertion_length: u32, + + // === PRIVATE: ACTIONS ASSERTION === + actions_assertion_hash_offset: u32, + actions_assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + actions_assertion_length: u32, + + // === PRIVATE: COMMITMENT SALTS === + location_salt: Field, + time_salt: Field, + + // === PRIVATE: EDIT TIMESTAMP & SALT (for separate edit time commitment) === + exact_edit_timestamp: Field, // Edit/signing timestamp (0 if no edit) + edit_time_salt: Field // Salt for edit time commitment +) -> pub (Field, Field, Field, Field, [u8; 32]) { // Returns (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) + // ================================================================ + // STEP 0: Verify claim hash commitment packing + // ================================================================ + let computed_claim_commitment = Poseidon2::hash(bytes32_to_field_array(claim_hash), 2); + assert(computed_claim_commitment == claim_hash_commitment, "Claim hash commitment mismatch"); + + // ================================================================ + // STEP 1: Hash + DER-walk the leaf TBS; P-384 intermediate signs that hash + // ================================================================ + let leaf = verify_leaf_certificate( + tbs_certificate, + tbs_len, + cert_signature_ecdsa_p384_r, + cert_signature_ecdsa_p384_s, + intermediate_ecdsa_p384_pubkey_x, + intermediate_ecdsa_p384_pubkey_y + ); + + // ================================================================ + // STEP 2: Derive Leaf Key Hash (P-256 - 32-byte coordinates) + // NOTE: Leaf key is P-256 even when intermediate is P-384. + // COSE signatures use ES256 (P-256) for the leaf key. + // ================================================================ + let x_field = bytes_to_field(leaf.pubkey_x); + let y_field = bytes_to_field(leaf.pubkey_y); + let computed_leaf_key_hash = pedersen_hash([x_field, y_field]); + + // ================================================================ + // STEP 3: Verify Nullifier Derivation + // ================================================================ + let expected_nullifier = pedersen_hash([content_hash, computed_leaf_key_hash]); + assert(nullifier == expected_nullifier, "Invalid nullifier (leaf key binding failed)"); + + // ================================================================ + // STEP 4: Compute Link Commitment + // ================================================================ + let claim_hash_field = bytes_to_field(claim_hash); + let link_commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + + // ================================================================ + // STEP 4b: Verify Intermediate Leaf Formulation + // ================================================================ + let int_x_field = bytes48_to_field(intermediate_ecdsa_p384_pubkey_x); + let int_y_field = bytes48_to_field(intermediate_ecdsa_p384_pubkey_y); + let computed_intermediate_hash = pedersen_hash([int_x_field, int_y_field]); + + assert( + intermediate_leaf == computed_intermediate_hash, + "Intermediate Leaf witnessing mismatch" + ); + + // ================================================================ + // STEP 4c: Merkle Membership + // ================================================================ + let computed_root = compute_merkle_root(intermediate_leaf, merkle_path, merkle_indices); + assert(computed_root == trust_list_root, "Intermediate CA not in trust list"); + + // ================================================================ + // STEP 5: Certificate Validity + // ================================================================ + // Dates come from the signed TBS and stay private. + assert(proof_timestamp as u64 as Field == proof_timestamp, "proof_timestamp exceeds u64"); + let ts = proof_timestamp as u64; + let not_before = leaf.not_before; + let not_after = leaf.not_after; + assert(ts >= not_before, "Certificate not yet valid"); + assert(ts <= not_after, "Certificate expired"); + + // ================================================================ + // STEP 6: Time Range Proof + // ================================================================ + assert(exact_timestamp as u64 as Field == exact_timestamp, "exact_timestamp exceeds u64"); + assert(time_min as u64 as Field == time_min, "time_min exceeds u64"); + assert(time_max as u64 as Field == time_max, "time_max exceeds u64"); + let exact_ts = exact_timestamp as u64; + let min_ts = time_min as u64; + let max_ts = time_max as u64; + + assert(exact_ts >= min_ts, "Exact timestamp before time_min"); + assert(exact_ts <= max_ts, "Exact timestamp after time_max"); + + // ================================================================ + // STEP 6b: Edit Time Range Proof (0 = no edit, skip) + // ================================================================ + // When a photo is edited (capture -> export), exact_edit_timestamp is the + // signing/export time. For direct camera captures, it's 0 (sentinel). + if exact_edit_timestamp != 0 { + assert(exact_edit_timestamp as u64 as Field == exact_edit_timestamp, "exact_edit_timestamp exceeds u64"); + assert(edit_time_min as u64 as Field == edit_time_min, "edit_time_min exceeds u64"); + assert(edit_time_max as u64 as Field == edit_time_max, "edit_time_max exceeds u64"); + let edit_ts = exact_edit_timestamp as u64; + let edit_min = edit_time_min as u64; + let edit_max = edit_time_max as u64; + assert(edit_ts >= edit_min, "Edit timestamp before edit_time_min"); + assert(edit_ts <= edit_max, "Edit timestamp after edit_time_max"); + } else { + assert(edit_time_min == 0, "edit_time_min must be 0 when no edit"); + assert(edit_time_max == 0, "edit_time_max must be 0 when no edit"); + } + + // ================================================================ + // STEP 7: Location Range Proof + // ================================================================ + // Unpack location_flags: bit 0 = lat negative, bit 1 = lon negative + // Reject if unused high bits (2-7) are set - prevents flag stuffing + assert(location_flags <= 3, "location_flags has invalid high bits set (must be 0-3)"); + let center_lat_is_negative = location_flags & 1; + let center_lon_is_negative = (location_flags >> 1) & 1; + + assert(exact_lat_is_negative <= 1, "exact_lat_is_negative must be 0 or 1"); + assert(exact_lon_is_negative <= 1, "exact_lon_is_negative must be 0 or 1"); + assert(skip_content_hash_binding <= 1, "skip_content_hash_binding must be 0 or 1"); + assert(skip_assertion_hash_verification <= 1, "skip_assertion_hash_verification must be 0 or 1"); + + assert(exact_lat_scaled as u64 as Field == exact_lat_scaled, "exact_lat_scaled exceeds u64"); + assert(center_lat_scaled as u64 as Field == center_lat_scaled, "center_lat_scaled exceeds u64"); + assert(exact_lon_scaled as u64 as Field == exact_lon_scaled, "exact_lon_scaled exceeds u64"); + assert(center_lon_scaled as u64 as Field == center_lon_scaled, "center_lon_scaled exceeds u64"); + + { + let lat_same_sign = (exact_lat_is_negative == center_lat_is_negative); + let d_lat = if lat_same_sign { + if exact_lat_scaled as u64 > center_lat_scaled as u64 { + exact_lat_scaled - center_lat_scaled + } else { + center_lat_scaled - exact_lat_scaled + } + } else { + exact_lat_scaled + center_lat_scaled + }; + + let lon_same_sign = (exact_lon_is_negative == center_lon_is_negative); + let d_lon = if lon_same_sign { + if exact_lon_scaled as u64 > center_lon_scaled as u64 { + exact_lon_scaled - center_lon_scaled + } else { + center_lon_scaled - exact_lon_scaled + } + } else { + exact_lon_scaled + center_lon_scaled + }; + + let distance_squared = d_lat * d_lat + d_lon * d_lon; + assert(distance_squared as u64 as Field == distance_squared, "distance_squared exceeds u64"); + assert(radius_squared_scaled as u64 as Field == radius_squared_scaled, "radius_squared_scaled exceeds u64"); + assert( + distance_squared as u64 <= radius_squared_scaled as u64, + "Location outside privacy circle" + ); + } + + // ================================================================ + // STEP 8: Hash Chain Verification + // ================================================================ + assert(enable_hash_chain_verification == 1, "Hash chain verification must be enabled"); + + verify_claim_hash(claim_bytes, claim_length, claim_hash); + + if skip_content_hash_binding == 0 { + verify_content_hash_binding(claim_bytes, content_hash_offset, content_hash); + } + + if skip_assertion_hash_verification == 0 { + verify_assertion_chain( + claim_bytes, + exif_assertion_hash_offset, + exif_assertion_bytes, + exif_assertion_length + ); + } + + let actions_assertion_hash: [u8; 32] = if actions_assertion_hash_offset > 0 { + verify_actions_assertion_chain( + claim_bytes, + actions_assertion_hash_offset, + actions_assertion_bytes, + actions_assertion_length + ); + dep::sha256::sha256_var(actions_assertion_bytes, actions_assertion_length as u32) + } else { + [0u8; 32] + }; + + // ================================================================ + // STEP 9: Compute Poseidon Commitments + // ================================================================ + let lat_sign_field = exact_lat_is_negative as Field; + let lon_sign_field = exact_lon_is_negative as Field; + + let location_commitment = Poseidon2::hash( + [exact_lat_scaled, exact_lon_scaled, lat_sign_field, lon_sign_field, location_salt], + 5 + ); + + let time_commitment = Poseidon2::hash([exact_timestamp, time_salt], 2); + + // Edit time commitment: Poseidon2([edit_timestamp, salt]) or 0 sentinel + // Poseidon2 never outputs 0 for valid inputs, so 0 is safe as "no edit" sentinel + let edit_time_commitment = if exact_edit_timestamp == 0 { + 0 // Sentinel: no edit happened + } else { + Poseidon2::hash([exact_edit_timestamp, edit_time_salt], 2) + }; + + (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) +} + +/// Hash (SHA-384) and DER-walk the leaf TBSCertificate, check its signature +/// algorithm is ecdsa-with-SHA384, then check that the intermediate's ECDSA +/// P-384 signature covers exactly that SHA-384. +fn verify_leaf_certificate( + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + sig_r: [u8; 48], + sig_s: [u8; 48], + intermediate_x: [u8; 48], + intermediate_y: [u8; 48] +) -> LeafCertSha384 { + let leaf = bind_leaf_cert_sha384(tbs_certificate, tbs_len); + let valid = verify_ecdsa_p384(leaf.sha384, intermediate_x, intermediate_y, sig_r, sig_s); + assert(valid, "ECDSA P-384 certificate verification failed"); + leaf +} + +/// Convert 32 bytes to Field (big-endian) +fn bytes_to_field(bytes: [u8; 32]) -> Field { + let mut result: Field = 0; + for i in 0..32 { + result = result * 256 + bytes[i] as Field; + } + result +} + +/// Convert 48 bytes to Field (big-endian) +fn bytes48_to_field(bytes: [u8; 48]) -> Field { + let mut result: Field = 0; + for i in 0..48 { + result = result * 256 + bytes[i] as Field; + } + result +} + +/// Convert 32 bytes to 2 Field elements for Poseidon2 hashing +/// Splits into two 16-byte (128-bit) chunks that fit within the BN254 field +fn bytes32_to_field_array(bytes: [u8; 32]) -> [Field; 2] { + let mut f0: Field = 0; + for i in 0..16 { + f0 = f0 * 256 + bytes[i] as Field; + } + let mut f1: Field = 0; + for i in 16..32 { + f1 = f1 * 256 + bytes[i] as Field; + } + [f0, f1] +} + +fn verify_content_hash_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + verify_content_hash_in_claim(claim_bytes, content_hash_offset, expected_content_hash); +} + +fn compute_merkle_root(leaf: Field, path: [Field; 8], indices: [Field; 8]) -> Field { + let mut current = leaf; + for i in 0..8 { + assert((indices[i] == 0) | (indices[i] == 1), "Merkle index must be 0 or 1"); + let path_element = path[i]; + let is_right = indices[i]; + let left = if is_right == 0 { current } else { path_element }; + let right = if is_right == 0 { path_element } else { current }; + current = pedersen_hash([left, right]); + } + current +} + +// ==================================================================== +// TESTS +// ==================================================================== + +#[test] +fn test_merkle_root_computation() { + let leaf: Field = 12345; + let path: [Field; 8] = [0; 8]; + let indices: [Field; 8] = [0; 8]; + let root = compute_merkle_root(leaf, path, indices); + assert(root != leaf); + let root2 = compute_merkle_root(leaf, path, indices); + assert(root == root2); +} + +#[test] +fn test_bytes48_to_field() { + let mut bytes: [u8; 48] = [0; 48]; + bytes[47] = 1; + let field = bytes48_to_field(bytes); + assert(field == 1); +} + +#[test] +fn test_bytes_to_field() { + let mut bytes: [u8; 32] = [0; 32]; + bytes[31] = 1; + assert(bytes_to_field(bytes) == 1); +} + +#[test] +fn test_nullifier_derivation_ecdsa_p384() { + let content_hash: Field = 111; + let leaf_key_hash: Field = 222; + let nullifier = pedersen_hash([content_hash, leaf_key_hash]); + let different_nullifier = pedersen_hash([333 as Field, leaf_key_hash]); + assert(nullifier != different_nullifier); +} + +// ==================================================================== +// CERTIFICATE TESTS (synthetic P-256 leaf, P-384 intermediate, +// ecdsa-with-SHA384; plus the real Samsung SHA-256 leaf as a negative) +// ==================================================================== + +mod cert_tests { + use super::{verify_leaf_certificate, MAX_TBS_SIZE}; + use dep::cert_binding::synthetic_vectors as sv; + use dep::cert_binding::test_vectors as tv; + + fn pad(a: [u8; M]) -> [u8; MAX_TBS_SIZE] { + let mut out: [u8; MAX_TBS_SIZE] = [0; MAX_TBS_SIZE]; + for i in 0..M { + out[i] = a[i]; + } + out + } + + fn find_p256_spki(t: [u8; N]) -> u32 { + let mut off: u32 = 0; + for i in 0..1000 { + if (off == 0) & (t[i] == 0x30) & (t[i + 1] == 0x59) & (t[i + 2] == 0x30) & (t[i + 3] == 0x13) { + off = i; + } + } + assert(off != 0); + off + } + + #[test] + fn test_sha384_leaf_verifies_and_binds_key() { + let leaf = verify_leaf_certificate( + pad(sv::SYN_P384_SHA384_LEAF_TBS), + sv::SYN_P384_SHA384_LEAF_TBS_LEN, + sv::SYN_P384_SHA384_LEAF_SIG_R, + sv::SYN_P384_SHA384_LEAF_SIG_S, + sv::SYN_P384_SHA384_LEAF_ISSUER_X, + sv::SYN_P384_SHA384_LEAF_ISSUER_Y, + ); + assert(leaf.sha384 == sv::SYN_P384_SHA384_LEAF_SHA384); + assert(leaf.pubkey_x == sv::SYN_P384_SHA384_LEAF_PUB_X); + assert(leaf.pubkey_y == sv::SYN_P384_SHA384_LEAF_PUB_Y); + assert(leaf.not_before == sv::SYN_P384_SHA384_LEAF_NOT_BEFORE); + assert(leaf.not_after == sv::SYN_P384_SHA384_LEAF_NOT_AFTER); + } + + #[test(should_fail_with = "ECDSA P-384 certificate verification failed")] + fn test_substituted_leaf_key_rejected() { + // Genuine CA signature, another P-256 key in the SPKI. + let mut t = pad(sv::SYN_P384_SHA384_LEAF_TBS); + let off = find_p256_spki(t); + for i in 0..32 { + t[off + 27 + i] = tv::LEICA_LEAF_PUB_X[i]; + t[off + 59 + i] = tv::LEICA_LEAF_PUB_Y[i]; + } + let _ = verify_leaf_certificate( + t, + sv::SYN_P384_SHA384_LEAF_TBS_LEN, + sv::SYN_P384_SHA384_LEAF_SIG_R, + sv::SYN_P384_SHA384_LEAF_SIG_S, + sv::SYN_P384_SHA384_LEAF_ISSUER_X, + sv::SYN_P384_SHA384_LEAF_ISSUER_Y, + ); + } + + #[test(should_fail_with = "ECDSA P-384 certificate verification failed")] + fn test_tampered_not_after_rejected() { + // Push notAfter's year digit forward (UTCTime "35" -> "45"). + let mut t = pad(sv::SYN_P384_SHA384_LEAF_TBS); + let mut first: u32 = 0; + let mut second: u32 = 0; + for i in 0..400 { + if (t[i] == 0x17) & (t[i + 1] == 0x0d) { + if first == 0 { + first = i; + } else if second == 0 { + second = i; + } + } + } + assert(second != 0); + t[second + 2] = 0x34; + let _ = verify_leaf_certificate( + t, + sv::SYN_P384_SHA384_LEAF_TBS_LEN, + sv::SYN_P384_SHA384_LEAF_SIG_R, + sv::SYN_P384_SHA384_LEAF_SIG_S, + sv::SYN_P384_SHA384_LEAF_ISSUER_X, + sv::SYN_P384_SHA384_LEAF_ISSUER_Y, + ); + } + + #[test(should_fail_with = "TBS signature algorithm mismatch")] + fn test_sha256_signed_leaf_rejected() { + // The real Samsung leaf is ecdsa-with-SHA256: wrong variant. + let _ = verify_leaf_certificate( + pad(tv::SAMSUNG_LEAF_TBS), + tv::SAMSUNG_LEAF_TBS_LEN, + tv::SAMSUNG_LEAF_SIG_R, + tv::SAMSUNG_LEAF_SIG_S, + tv::SAMSUNG_LEAF_ISSUER_X, + tv::SAMSUNG_LEAF_ISSUER_Y, + ); + } +} From 478624c7ad0f67e0fc6c7e0c1436d7b2c4914552 Mon Sep 17 00:00:00 2001 From: Jamie Newton <33573418+newtsjamie@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:44:21 +0000 Subject: [PATCH 2/7] Add ProofA skip v2 for 2-cert chains (ProofMode) proof_a_skip_v2 verifies the root's ECDSA P-256 signature over the leaf TBSCertificate, hashed in-circuit with SHA-512 (ecdsa-with-SHA512, as ProofMode signs), and takes the leaf key and validity dates from the DER walk. The root SPKI is the Merkle leaf, as for v2 intermediates. Public layout and input names match proof_a_ecdsa_p256_v2; claim and assertion size classes follow v1 proof_a_skip. cert_binding gains bind_leaf_cert_sha512 and the ProofMode leaf as a test vector (root key recovered from the leaf signature, since the root certificate is not in the C2PA chain). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + cert_binding/src/lib.nr | 19 +- cert_binding/src/proofmode_vectors.nr | 18 + proof_a_skip_v2/Nargo.toml | 14 + proof_a_skip_v2/src/hash_chain.nr | 548 ++++++++++++++++++++ proof_a_skip_v2/src/main.nr | 701 ++++++++++++++++++++++++++ 6 files changed, 1300 insertions(+), 1 deletion(-) create mode 100644 cert_binding/src/proofmode_vectors.nr create mode 100644 proof_a_skip_v2/Nargo.toml create mode 100644 proof_a_skip_v2/src/hash_chain.nr create mode 100644 proof_a_skip_v2/src/main.nr diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 79e3828..f24042a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,6 +32,7 @@ jobs: - proof_a_ecdsa_p256_v2 - proof_a_ecdsa_p384_v2 - proof_a_ecdsa_p384_sha384_v2 + - proof_a_skip_v2 - proof_b_es256_v2_core - proof_b_es256_v2 - proof_b_es256_v2_large diff --git a/cert_binding/src/lib.nr b/cert_binding/src/lib.nr index df857d0..f3b402e 100644 --- a/cert_binding/src/lib.nr +++ b/cert_binding/src/lib.nr @@ -33,6 +33,7 @@ use dep::sha512::{sha384::sha384_var, sha512::sha512_var}; pub mod test_vectors; pub mod synthetic_vectors; +pub mod proofmode_vectors; /// Uncompressed P-256 SubjectPublicKeyInfo header (27 bytes), followed by /// X (32 bytes) and Y (32 bytes). @@ -311,7 +312,8 @@ pub fn bind_leaf_cert(tbs: [u8; N], tbs_len: u32) -> LeafCert { // ==================================================================== mod tests { - use super::{bind_leaf_cert, bind_leaf_cert_sha384, days_from_civil, LeafCert}; + use super::{bind_leaf_cert, bind_leaf_cert_sha384, bind_leaf_cert_sha512, days_from_civil, LeafCert}; + use super::proofmode_vectors as pm; use super::test_vectors as tv; use super::synthetic_vectors as sv; @@ -517,4 +519,19 @@ mod tests { // Samsung leaf is signed ecdsa-with-SHA256; the SHA-384 path must refuse it. let _ = bind_leaf_cert_sha384(pad(tv::SAMSUNG_LEAF_TBS), tv::SAMSUNG_LEAF_TBS_LEN); } + + #[test] + fn test_sha512_proofmode_leaf_binds() { + let c = bind_leaf_cert_sha512(pad(pm::PROOFMODE_LEAF_TBS), pm::PROOFMODE_LEAF_TBS_LEN); + assert(c.sha512 == pm::PROOFMODE_LEAF_SHA512, "sha512 mismatch"); + assert(c.pubkey_x == pm::PROOFMODE_LEAF_PUB_X); + assert(c.pubkey_y == pm::PROOFMODE_LEAF_PUB_Y); + assert(c.not_before == pm::PROOFMODE_LEAF_NOT_BEFORE); + assert(c.not_after == pm::PROOFMODE_LEAF_NOT_AFTER); + } + + #[test(should_fail_with = "TBS signature algorithm mismatch")] + fn test_sha512_rejects_sha256_signed_leaf() { + let _ = bind_leaf_cert_sha512(pad(tv::LEICA_LEAF_TBS), tv::LEICA_LEAF_TBS_LEN); + } } diff --git a/cert_binding/src/proofmode_vectors.nr b/cert_binding/src/proofmode_vectors.nr new file mode 100644 index 0000000..d7f837c --- /dev/null +++ b/cert_binding/src/proofmode_vectors.nr @@ -0,0 +1,18 @@ +// ProofMode leaf certificate (CN=ProofMode-User Content Credentials, issuer +// CN=ProofMode-Root Offline Root CA), taken from a ProofMode C2PA video. +// Leaf key P-256; signed ecdsa-with-SHA512 by a P-256 root. +// The root certificate is not carried in the C2PA x5chain, so ISSUER_X/Y is +// the root key recovered from the leaf signature (ECDSA public key recovery; +// one of two candidates, both of which verify). The deployed trust list must +// use the real root SPKI taken from the device. + +pub global PROOFMODE_LEAF_TBS_LEN: u32 = 398; +pub global PROOFMODE_LEAF_TBS: [u8; 398] = [0x30, 0x82, 0x01, 0x8a, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x15, 0x00, 0xbc, 0xee, 0xb9, 0x8b, 0xbc, 0x1a, 0x97, 0x50, 0xf1, 0xe9, 0x25, 0xdc, 0x84, 0xa3, 0x1f, 0x32, 0xd0, 0x92, 0x2e, 0x9b, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x04, 0x30, 0x42, 0x31, 0x27, 0x30, 0x25, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1e, 0x50, 0x72, 0x6f, 0x6f, 0x66, 0x4d, 0x6f, 0x64, 0x65, 0x2d, 0x52, 0x6f, 0x6f, 0x74, 0x20, 0x4f, 0x66, 0x66, 0x6c, 0x69, 0x6e, 0x65, 0x20, 0x52, 0x6f, 0x6f, 0x74, 0x20, 0x43, 0x41, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0e, 0x50, 0x72, 0x6f, 0x6f, 0x66, 0x4d, 0x6f, 0x64, 0x65, 0x2d, 0x52, 0x6f, 0x6f, 0x74, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x36, 0x30, 0x31, 0x31, 0x36, 0x30, 0x39, 0x32, 0x33, 0x34, 0x35, 0x5a, 0x17, 0x0d, 0x32, 0x37, 0x30, 0x31, 0x31, 0x36, 0x30, 0x39, 0x32, 0x33, 0x34, 0x35, 0x5a, 0x30, 0x46, 0x31, 0x2b, 0x30, 0x29, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x22, 0x50, 0x72, 0x6f, 0x6f, 0x66, 0x4d, 0x6f, 0x64, 0x65, 0x2d, 0x55, 0x73, 0x65, 0x72, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x43, 0x72, 0x65, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x73, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0e, 0x50, 0x72, 0x6f, 0x6f, 0x66, 0x4d, 0x6f, 0x64, 0x65, 0x2d, 0x55, 0x73, 0x65, 0x72, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x03, 0x13, 0xb9, 0x67, 0x43, 0x83, 0xa5, 0x1a, 0x3b, 0x71, 0x8d, 0xbf, 0xa3, 0xa9, 0x96, 0xef, 0x3c, 0x19, 0xfb, 0xa2, 0xba, 0x3e, 0xd1, 0xe5, 0x7b, 0xea, 0x4d, 0x20, 0xed, 0x5f, 0x8e, 0x8e, 0x2a, 0x2a, 0xb9, 0x67, 0x1b, 0x1b, 0x73, 0x81, 0x18, 0xe8, 0xf7, 0xb1, 0x06, 0xfa, 0x73, 0x87, 0x01, 0x1c, 0xd7, 0x8e, 0x00, 0x7c, 0x82, 0x96, 0x2c, 0x66, 0x48, 0xca, 0x1a, 0x67, 0xc9, 0x64, 0xa3, 0x59, 0x30, 0x57, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x07, 0x80, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x28, 0xf5, 0x71, 0x65, 0xd9, 0x65, 0xc0, 0xb4, 0x2f, 0x68, 0x5c, 0x0e, 0xaa, 0xa9, 0x61, 0x87, 0x29, 0x8a, 0x3e, 0x9c, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x02, 0x30, 0x00, 0x30, 0x13, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x0c, 0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x04]; +pub global PROOFMODE_LEAF_SHA512: [u8; 64] = [0x27, 0x5e, 0x3e, 0x08, 0xd2, 0x5b, 0x66, 0xe7, 0xac, 0xbb, 0x32, 0x9f, 0xc0, 0xef, 0x1e, 0x5c, 0x00, 0xcc, 0xc7, 0x4d, 0x35, 0x24, 0x22, 0x72, 0x1d, 0x78, 0x1c, 0x45, 0x5a, 0x04, 0x66, 0xc9, 0x49, 0x09, 0x9f, 0xc5, 0x8e, 0xc5, 0x8b, 0xd7, 0x6e, 0xde, 0xb0, 0x67, 0xab, 0x7f, 0x58, 0xfe, 0x5a, 0x3b, 0x95, 0x5c, 0xb3, 0xb0, 0xea, 0x7c, 0x14, 0x88, 0xb2, 0xef, 0xd5, 0xe9, 0x9a, 0x7c]; +pub global PROOFMODE_LEAF_NOT_BEFORE: u64 = 1768555425; +pub global PROOFMODE_LEAF_NOT_AFTER: u64 = 1800091425; +pub global PROOFMODE_LEAF_PUB_X: [u8; 32] = [0x03, 0x13, 0xb9, 0x67, 0x43, 0x83, 0xa5, 0x1a, 0x3b, 0x71, 0x8d, 0xbf, 0xa3, 0xa9, 0x96, 0xef, 0x3c, 0x19, 0xfb, 0xa2, 0xba, 0x3e, 0xd1, 0xe5, 0x7b, 0xea, 0x4d, 0x20, 0xed, 0x5f, 0x8e, 0x8e]; +pub global PROOFMODE_LEAF_PUB_Y: [u8; 32] = [0x2a, 0x2a, 0xb9, 0x67, 0x1b, 0x1b, 0x73, 0x81, 0x18, 0xe8, 0xf7, 0xb1, 0x06, 0xfa, 0x73, 0x87, 0x01, 0x1c, 0xd7, 0x8e, 0x00, 0x7c, 0x82, 0x96, 0x2c, 0x66, 0x48, 0xca, 0x1a, 0x67, 0xc9, 0x64]; +pub global PROOFMODE_LEAF_ISSUER_X: [u8; 32] = [0x51, 0x99, 0xc5, 0x16, 0x7a, 0xea, 0x35, 0xfb, 0x37, 0x76, 0xa0, 0x57, 0x88, 0x87, 0x5f, 0x12, 0x18, 0x52, 0x76, 0x36, 0x60, 0x08, 0x89, 0xf9, 0x2d, 0x7b, 0xb0, 0xdc, 0xeb, 0xf8, 0x8f, 0x7f]; +pub global PROOFMODE_LEAF_ISSUER_Y: [u8; 32] = [0xa8, 0x30, 0x4d, 0xc5, 0xf7, 0x72, 0x7a, 0x4d, 0xe0, 0x20, 0xe7, 0xe8, 0xd2, 0x59, 0x52, 0x4e, 0xef, 0x1a, 0x5f, 0x6d, 0x11, 0xa9, 0xe2, 0x1d, 0x3b, 0x05, 0x48, 0x34, 0x69, 0x62, 0xb1, 0x09]; +pub global PROOFMODE_LEAF_SIG: [u8; 64] = [0x43, 0x2d, 0xe7, 0xff, 0x8a, 0xb7, 0x15, 0x6f, 0xcb, 0xf0, 0x0a, 0x9b, 0xc8, 0xb3, 0x27, 0x53, 0x4d, 0x2e, 0xbe, 0xb6, 0xa9, 0xe9, 0xdb, 0x4d, 0x3f, 0x0e, 0x39, 0xcf, 0x27, 0x46, 0xd7, 0x19, 0x3e, 0xf5, 0xf9, 0xc3, 0x11, 0x6f, 0x6f, 0x93, 0x01, 0xcb, 0x84, 0xe8, 0x8b, 0xe6, 0xa5, 0xc7, 0xe0, 0x69, 0x5a, 0x4b, 0x87, 0x89, 0x7c, 0xf3, 0x93, 0xd6, 0x86, 0x42, 0x0e, 0x03, 0xa6, 0x53]; diff --git a/proof_a_skip_v2/Nargo.toml b/proof_a_skip_v2/Nargo.toml new file mode 100644 index 0000000..59674f1 --- /dev/null +++ b/proof_a_skip_v2/Nargo.toml @@ -0,0 +1,14 @@ +[package] +name = "apertrue_proof_a_skip_v2" +type = "bin" +authors = ["Apertrue"] +compiler_version = ">=1.0.0" +description = "ProofA Skip v2: 2-cert chain (ProofMode). P-256 root signs the P-256 leaf with ecdsa-with-SHA512; leaf key and validity bound to that TBS" + +[dependencies] +# Leaf TBSCertificate hashing (SHA-512) and DER walk +cert_binding = { path = "../cert_binding" } +# SHA-256 for hash chain verification +sha256 = { tag = "v0.3.0", git = "https://github.com/noir-lang/sha256" } +# Poseidon for commitment schemes +poseidon = { tag = "v0.1.1", git = "https://github.com/noir-lang/poseidon" } diff --git a/proof_a_skip_v2/src/hash_chain.nr b/proof_a_skip_v2/src/hash_chain.nr new file mode 100644 index 0000000..d7fe6d5 --- /dev/null +++ b/proof_a_skip_v2/src/hash_chain.nr @@ -0,0 +1,548 @@ +/** + * Hash Chain Verification for Trustless Metadata Binding + * + * This module verifies that extracted metadata values (GPS, timestamp) actually + * came from the signed C2PA claim, preventing substitution attacks. + * + * The verification chain: + * 1. COSE Signature -> COSE Payload (which is claim_hash or claim_bytes) + * 2. SHA256(claim_bytes) -> claim_hash (verified via signature) + * 3. claim_bytes contains assertion_hash at known offset + * 4. SHA256(assertion_bytes) == assertion_hash + * 5. assertion_bytes contain the metadata values at known offsets + * + * Without this verification, a malicious client could: + * - Extract real GPS from signed image + * - Replace with fake GPS + * - Generate valid proof with fake location + * + * With hash chain verification, the circuit ensures: + * - The metadata values are cryptographically bound to the signature + * - Substitution of any value invalidates the proof + * + * CONSTRAINT BUDGET: + * - SHA256 in Noir: ~15k constraints per KB hashed + * - Claim bytes: typically 1-5 KB -> 15-75k constraints + * - Assertion bytes: typically 200B-2KB -> 3-30k constraints + * - Total budget: ~100k constraints for hash chain + * + * OPTIMIZATION STRATEGIES: + * 1. Use pre-computed claim_hash when claim is large (skip in-circuit hashing) + * 2. Only verify assertion hash for assertions containing sensitive data + * 3. For small claims/assertions, in-circuit SHA256 is acceptable + */ + +// SHA256 from stdlib - use digest function with generic size parameter + +/// Maximum size of claim bytes we'll hash in-circuit +/// Claims larger than this should use the pre-computed hash approach +/// RESTORED to 2048 for full cryptographic hash chain verification +/// ProofMode claims are ~1299 bytes, so 2048 provides sufficient headroom +pub global MAX_CLAIM_SIZE: u32 = 2048; + +/// Maximum size of EXIF assertion bytes we'll hash in-circuit +/// RESTORED to 1024 for full assertion hash verification +pub global MAX_EXIF_ASSERTION_SIZE: u32 = 1024; + +/// Maximum size of c2pa.actions assertion bytes we'll hash in-circuit +/// Actions assertions contain edit history (c2pa.created, c2pa.edited, etc.) +/// and AI generation indicators (digitalSourceType: trainedAlgorithmicMedia) +/// NOTE: Adobe Photoshop actions assertions can be 1200-1500 bytes, so 2048 provides headroom +pub global MAX_ACTIONS_ASSERTION_SIZE: u32 = 2048; + +/// SHA256 hash output size +pub global HASH_SIZE: u32 = 32; + +/** + * Verify that claim_hash matches SHA256(claim_bytes) + * + * This binds the claim content to the signature. + * The signature verifies over claim_hash, so if this passes, + * we know claim_bytes are authentic. + * + * IMPORTANT: Uses sha256_var to hash only the first claim_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * claim bytes, not the padded version. + * + * @param claim_bytes Raw CBOR claim bytes (padded to MAX_CLAIM_SIZE) + * @param claim_length Actual length of claim bytes + * @param expected_claim_hash Pre-computed SHA256(claim_bytes) - same as signature input + */ +pub fn verify_claim_hash( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32] +) { + // Bounds check: claim_length must not exceed buffer size + assert(claim_length <= MAX_CLAIM_SIZE, "claim_length exceeds MAX_CLAIM_SIZE"); + + // Compute SHA256 of the ACTUAL claim bytes (not padded) + // sha256_var hashes only the first claim_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(claim_bytes, claim_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_claim_hash[i], + "Claim hash verification failed: claim_bytes do not match expected hash" + ); + } +} + +/** + * Extract assertion hash from claim_bytes at a known offset + * + * The claim contains references to assertions with their expected hashes. + * This function extracts the 32-byte hash at the specified offset. + * + * @param claim_bytes Raw CBOR claim bytes + * @param hash_offset Byte offset where assertion hash appears in claim + * @returns The 32-byte assertion hash from the claim + */ +pub fn extract_assertion_hash_from_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + hash_offset: u32 +) -> [u8; 32] { + let mut assertion_hash: [u8; 32] = [0; 32]; + + // Bounds check + assert( + hash_offset + 32 <= MAX_CLAIM_SIZE, + "Assertion hash offset out of bounds" + ); + + // Extract 32 bytes starting at hash_offset + for i in 0..32 { + assertion_hash[i] = claim_bytes[hash_offset + i]; + } + + assertion_hash +} + +/** + * Verify that assertion_hash matches SHA256(assertion_bytes) + * + * This binds the assertion content to the claim. + * Combined with verify_claim_hash, this creates a complete chain: + * Signature -> Claim -> Assertion -> Metadata + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR or JSON, padded) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_assertion_hash( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_EXIF_ASSERTION_SIZE, "assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Extract a u64 timestamp value from CBOR-encoded assertion bytes + * + * CBOR timestamp encoding (simplified): + * - For small values (0-23): single byte 0x00-0x17 + * - For u8: 0x18 + 1 byte + * - For u16: 0x19 + 2 bytes (big-endian) + * - For u32: 0x1a + 4 bytes (big-endian) + * - For u64: 0x1b + 8 bytes (big-endian) + * + * We extract the raw bytes and convert to u64. + * The offset should point to the START of the CBOR value (type byte). + * + * @param assertion_bytes Raw assertion bytes + * @param timestamp_offset Byte offset where timestamp CBOR value starts + * @returns Extracted timestamp as u64 + */ +pub fn extract_timestamp_from_cbor( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + timestamp_offset: u32 +) -> u64 { + let type_byte = assertion_bytes[timestamp_offset]; + + // Check CBOR type - we expect unsigned integer (major type 0) + let major_type = type_byte >> 5; + let additional_info = type_byte & 0x1f; + + // Major type 0 = unsigned integer + assert(major_type == 0, "Expected CBOR unsigned integer for timestamp"); + + let mut timestamp: u64 = 0; + + if additional_info <= 23 { + // Inline value + timestamp = additional_info as u64; + } else if additional_info == 24 { + // u8 follows - need 2 bytes total + assert(timestamp_offset + 2 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u8 timestamp exceeds buffer"); + timestamp = assertion_bytes[timestamp_offset + 1] as u64; + } else if additional_info == 25 { + // u16 follows (big-endian) - need 3 bytes total + assert(timestamp_offset + 3 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u16 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 2] as u64); + } else if additional_info == 26 { + // u32 follows (big-endian) - need 5 bytes total + assert(timestamp_offset + 5 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u32 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 24; + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 2] as u64) << 16); + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 3] as u64) << 8); + timestamp = timestamp + (assertion_bytes[timestamp_offset + 4] as u64); + } else if additional_info == 27 { + // u64 follows (big-endian) - need 9 bytes total + assert(timestamp_offset + 9 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u64 timestamp exceeds buffer"); + for i in 0..8 { + timestamp = timestamp << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 1 + i] as u64); + } + } else { + // additional_info 28-30 are reserved per CBOR RFC 8949, 31 is indefinite-length + assert(false, "Reserved or unsupported CBOR integer encoding for timestamp"); + } + + timestamp +} + +/** + * GPS BINDING SECURITY MODEL + * ========================== + * + * This module does NOT implement byte-level GPS extraction from CBOR assertions. + * This is a deliberate design choice, not a missing feature. + * + * SECURITY RATIONALE: + * ------------------- + * GPS coordinates are cryptographically bound through the hash chain: + * + * 1. verify_assertion_hash() proves: SHA256(assertion_bytes) == hash_in_claim + * 2. verify_claim_hash() proves: SHA256(claim_bytes) == signed_hash + * 3. COSE signature proves: claim was signed by trusted certificate + * + * Therefore, if the assertion bytes pass hash verification, their ENTIRE CONTENT + * is cryptographically bound to the signature. Any modification to the GPS values + * would change the hash and break verification. + * + * WHY NOT PARSE CBOR IN-CIRCUIT? + * ------------------------------ + * C2PA EXIF GPS coordinates are stored as CBOR rational number arrays: + * { "EXIF:GPSLatitude": [{n: 51, d: 1}, {n: 30, d: 1}, {n: 0, d: 1}] } // 51d 30m 0s + * + * Parsing this requires: + * - Variable-length CBOR decoding (~200+ constraints per value) + * - Rational number arithmetic (degree + minute/60 + second/3600) + * - Sign handling from GPSLatitudeRef/GPSLongitudeRef strings + * + * Total cost: ~500-1000 additional constraints for minimal security gain. + * + * The hash chain already guarantees that the client cannot substitute GPS values + * without invalidating the proof. Adding in-circuit parsing would only catch + * bugs in the client extractor, not malicious tampering. + * + * TRUST MODEL: + * ------------ + * - The CIRCUIT trusts that assertion_bytes were correctly passed from the client + * - The HASH CHAIN proves assertion_bytes match what was signed + * - The CLIENT extracts GPS from the verified bytes + * - Any GPS tampering would require finding a hash collision (computationally infeasible) + * + * For applications requiring stronger guarantees, the circuit could be extended + * to parse CBOR at specific known offsets. This is left as a future enhancement. + */ + +// NOTE: verify_gps_binding() has been intentionally removed. +// GPS binding is provided by verify_assertion_hash() in the hash chain. +// See the SECURITY RATIONALE above for details. + +/** + * Combined hash chain verification + * + * Performs the complete verification: + * 1. SHA256(claim_bytes) == expected_claim_hash (signature input) + * 2. Extract assertion_hash from claim at known offset + * 3. SHA256(assertion_bytes) == assertion_hash + * + * If all pass, we know the assertion_bytes are authentic and + * any values extracted from them are cryptographically bound to the signature. + * + * @param claim_bytes Raw claim bytes (padded) + * @param claim_length Actual claim length + * @param expected_claim_hash SHA256 of claim (same as signature message hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes (padded) + * @param assertion_length Actual assertion length + */ +pub fn verify_full_hash_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Step 1: Verify claim hash + verify_claim_hash(claim_bytes, claim_length, expected_claim_hash); + + // Step 2: Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Step 3: Verify assertion hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // At this point, we've proven: + // - claim_bytes hash to the signed value + // - assertion_bytes hash to a reference in the signed claim + // - Therefore, assertion_bytes are authentic + // - Any values in assertion_bytes are cryptographically bound + + // Silence unused warnings + let _ = claim_length; + let _ = assertion_length; +} + +/** + * Verify timestamp is bound to assertion via hash chain + * + * Combines hash chain verification with timestamp extraction. + * Proves that exact_timestamp actually came from the signed assertion. + * + * @param claim_bytes Raw claim bytes + * @param claim_length Actual claim length + * @param expected_claim_hash Expected claim hash (signature input) + * @param assertion_hash_offset Offset of assertion hash in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + * @param timestamp_offset Offset of timestamp in assertion + * @param expected_timestamp The timestamp value the circuit is using + */ +pub fn verify_timestamp_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + timestamp_offset: u32, + expected_timestamp: u64 +) { + // First verify the hash chain + verify_full_hash_chain( + claim_bytes, + claim_length, + expected_claim_hash, + assertion_hash_offset, + assertion_bytes, + assertion_length + ); + + // Then extract and verify the timestamp + let extracted_timestamp = extract_timestamp_from_cbor(assertion_bytes, timestamp_offset); + + assert( + extracted_timestamp == expected_timestamp, + "Timestamp binding failed: extracted timestamp does not match expected value" + ); +} + +/** + * Verify content hash exists in claim at specified offset + * + * SECURITY: This binds the public content_hash to the signed claim. + * Without this verification, a malicious client could substitute + * a different image's content_hash while keeping the valid signature. + * + * @param claim_bytes Raw claim bytes (CBOR encoded) + * @param content_hash_offset Byte offset where content hash appears in claim + * @param expected_content_hash The content hash (Field) to verify + */ +pub fn verify_content_hash_in_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + // Bounds check + assert( + content_hash_offset + 32 <= MAX_CLAIM_SIZE, + "Content hash offset out of bounds" + ); + + // Extract 32 bytes from claim at offset and convert to Field + let mut extracted_hash: Field = 0; + for i in 0..32 { + extracted_hash = extracted_hash * 256 + claim_bytes[content_hash_offset + i] as Field; + } + + // Verify the extracted content hash matches the public input + assert( + extracted_hash == expected_content_hash, + "Content hash binding failed: public content_hash does not match value in signed claim" + ); +} + +/** + * Verify assertion hash chain (without redundant claim hash check) + * + * Use this when claim_hash has already been verified separately. + * Verifies: SHA256(assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + */ +pub fn verify_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // Silence unused warning + let _ = assertion_length; +} + +/** + * Verify actions assertion hash matches SHA256(actions_assertion_bytes) + * + * This is the same as verify_assertion_hash but for the larger actions buffer. + * Actions assertions (c2pa.actions.v2) can be up to 2048 bytes (Adobe Photoshop). + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR, padded to MAX_ACTIONS_ASSERTION_SIZE) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_actions_assertion_hash( + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_ACTIONS_ASSERTION_SIZE, "actions_assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Actions assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Verify actions assertion hash chain (without redundant claim hash check) + * + * Use this for c2pa.actions.v2 assertions which can be up to 2048 bytes. + * Verifies: SHA256(actions_assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw actions assertion bytes (up to 2048 bytes) + * @param assertion_length Actual assertion length + */ +pub fn verify_actions_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_actions_assertion_hash(assertion_bytes, assertion_length, assertion_hash); +} + +// Tests +#[test] +fn test_content_hash_binding() { + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a known content hash at offset 100 + // Content hash as bytes: 0x0000...0001 (just 1 for simplicity) + claim_bytes[131] = 1; // Last byte = 1 + + // Expected field value is 1 + let expected_hash: Field = 1; + + // This should pass + verify_content_hash_in_claim(claim_bytes, 100, expected_hash); +} + +#[test] +fn test_extract_assertion_hash() { + // Create test claim bytes with a known hash at offset 10 + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a test hash at offset 10 + let test_hash: [u8; 32] = [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 + ]; + + for i in 0..32 { + claim_bytes[10 + i] = test_hash[i]; + } + + let extracted = extract_assertion_hash_from_claim(claim_bytes, 10); + + for i in 0..32 { + assert(extracted[i] == test_hash[i]); + } +} + +#[test] +fn test_extract_cbor_timestamp_inline() { + // Test inline value (0-23) + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x17; // Inline value 23 + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 23); +} + +#[test] +fn test_extract_cbor_timestamp_u32() { + // Test u32 value + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x1a; // u32 follows + // Value: 1700000000 (0x6553F100) - a Unix timestamp + assertion_bytes[1] = 0x65; + assertion_bytes[2] = 0x53; + assertion_bytes[3] = 0xF1; + assertion_bytes[4] = 0x00; + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 1700000000); +} diff --git a/proof_a_skip_v2/src/main.nr b/proof_a_skip_v2/src/main.nr new file mode 100644 index 0000000..91a78f6 --- /dev/null +++ b/proof_a_skip_v2/src/main.nr @@ -0,0 +1,701 @@ +/// Apertrue ProofA Skip v2 - 2-Cert Chain Verification (ProofMode) +/// +/// For 2-cert chains where the leaf is signed directly by a root CA with no +/// intermediate (ProofMode: CN=ProofMode-Root Offline Root CA signs +/// CN=ProofMode-User Content Credentials). The root plays the intermediate's +/// role: its P-256 SPKI is the Merkle leaf and its signature over the leaf +/// TBSCertificate is verified in-circuit. +/// +/// v1 proof_a_skip verified no signature over the leaf at all: the leaf key, +/// dates and the trust-list leaf were free witnesses. v2 hashes the full leaf +/// TBS (SHA-512), DER-walks it from offset 0 (cert_binding lib), requires the +/// TBS signature algorithm to be ecdsa-with-SHA512, verifies the root's ECDSA +/// P-256 signature over that digest, and takes the leaf key and +/// notBefore/notAfter from the parsed bytes. +/// +/// DIGEST: for P-256, ECDSA takes e = leftmost 256 bits of the hash +/// (FIPS 186-5), so the first 32 bytes of the SHA-512 digest are verified. +/// +/// 2-cert chains whose root signs with ecdsa-with-SHA256 need no special +/// circuit: proof_a_ecdsa_p256_v2 verifies them as is (root SPKI as leaf). +/// +/// This circuit proves: +/// 1. The root CA signed (ECDSA P-256, SHA-512) the leaf TBSCertificate +/// 2. The root CA SPKI is in the Oracle's promoted trust list (Merkle membership) +/// 3. The nullifier is derived from the leaf key found in that TBSCertificate +/// 4. proof_timestamp lies within that certificate's validity (dates private) +/// 5. Time range proof (graduated time disclosure) +/// 6. Location range proof (privacy circles) +/// 7. Hash chain verification (claim and assertion integrity) +/// 8. Poseidon commitments for optional future reveal +/// +/// Supported leaf: subjectPublicKeyInfo is uncompressed P-256, TBS <= 1024 B. +/// Claim/assertion size classes follow v1 proof_a_skip (claim 2048, exif 1024, +/// actions 2048), since ProofMode claims are about 1300 bytes. Inputs keep the +/// proof_a_ecdsa_p256_v2 names: intermediate_ecdsa_pubkey_x/y is the ROOT key +/// and intermediate_leaf = pedersen_hash([root_x, root_y]). +/// +/// PUBLIC LAYOUT (index: name; one Field each unless noted) +/// 0 trust_list_root +/// 1 content_hash +/// 2 nullifier pedersen_hash([content_hash, pedersen_hash([leaf_x, leaf_y])]) +/// 3 proof_timestamp +/// 4 time_min +/// 5 time_max +/// 6 edit_time_min +/// 7 edit_time_max +/// 8 center_lat_scaled +/// 9 center_lon_scaled +/// 10 location_flags +/// 11 radius_squared_scaled +/// 12 claim_hash_commitment +/// 13 content_hash_offset +/// 14 skip_content_hash_binding +/// 15 skip_assertion_hash_verification +/// Return values: +/// 16 link_commit pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]) +/// 17 location_commitment +/// 18 time_commitment +/// 19 edit_time_commitment +/// 20..51 actions_assertion_hash (32 x u8) +/// Total 52. Versus v1: cert_not_before (4), cert_not_after (5) and +/// tbs_hash_commitment (14) are removed; every later index shifts down. +/// +/// Shared with ProofB v2 (must be equal across the pair): trust_list_root, +/// content_hash, nullifier, proof_timestamp, claim_hash_commitment, +/// content_hash_offset, link_commit. + +use std::ecdsa_secp256r1::verify_signature; +use std::hash::pedersen_hash; +use dep::poseidon::poseidon2::Poseidon2; +use dep::cert_binding::{bind_leaf_cert_sha512, LeafCertSha512}; + +mod hash_chain; + +use hash_chain::{ + MAX_CLAIM_SIZE, + MAX_EXIF_ASSERTION_SIZE, + MAX_ACTIONS_ASSERTION_SIZE, + verify_claim_hash, + verify_content_hash_in_claim, + verify_assertion_chain, + verify_actions_assertion_chain, +}; + +/// Maximum leaf TBSCertificate size (DER bytes) +global MAX_TBS_SIZE: u32 = 1024; + +/// ProofA Skip v2 main entry point +fn main( + // === PUBLIC INPUTS (shared with ProofB) === + trust_list_root: pub Field, + content_hash: pub Field, + nullifier: pub Field, + proof_timestamp: pub Field, + + // === PUBLIC INPUTS: TIME RANGE BOUNDS (for graduated time disclosure) === + time_min: pub Field, + time_max: pub Field, + + // === PUBLIC INPUTS: EDIT TIME RANGE BOUNDS (for edited images) === + // When a photo is edited (e.g., Leica capture -> Lightroom export), the capture + // and edit timestamps differ. These bounds constrain the edit/signing timestamp. + // Set to 0 when no edit occurred (direct camera capture). + edit_time_min: pub Field, // Minimum edit timestamp bound (0 if no edit) + edit_time_max: pub Field, // Maximum edit timestamp bound (0 if no edit) + + // === PUBLIC INPUTS: LOCATION PRIVACY CIRCLE (for graduated location disclosure) === + center_lat_scaled: pub Field, + center_lon_scaled: pub Field, + location_flags: pub u8, // bit 0 = lat negative (South), bit 1 = lon negative (West) + radius_squared_scaled: pub Field, + + // === PUBLIC INPUT: Claim Hash Commitment (packed from 32 bytes to 1 Field) === + // This is Poseidon2(bytes32_to_field_array(claim_hash)). Saves 31 public input fields. + claim_hash_commitment: pub Field, + + // === PUBLIC INPUT: Content Hash Offset (for content binding) === + content_hash_offset: pub u32, + + // === PRIVATE: LEAF TBSCertificate (DER, zero padded past tbs_len) === + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + + // === PRIVATE: CLAIM HASH BYTES (unpacked from commitment) === + claim_hash: [u8; 32], + + // === PRIVATE: SKIP FLAGS === + skip_content_hash_binding: pub u8, + skip_assertion_hash_verification: pub u8, + + // === PRIVATE: ECDSA P-256 CERTIFICATE SIGNATURE & KEY === + cert_signature_ecdsa: [u8; 64], + intermediate_ecdsa_pubkey_x: [u8; 32], + intermediate_ecdsa_pubkey_y: [u8; 32], + + // === PRIVATE: LINKING WITNESS === + intermediate_leaf: Field, + link_blind: Field, + + // === PRIVATE: MERKLE MEMBERSHIP (trust list verification) === + merkle_path: [Field; 8], + merkle_indices: [Field; 8], + + // === PRIVATE: EXACT TIMESTAMP (for time range proof) === + exact_timestamp: Field, + + // === PRIVATE: EXACT GPS LOCATION (for location range proof) === + exact_lat_scaled: Field, + exact_lon_scaled: Field, + exact_lat_is_negative: u8, + exact_lon_is_negative: u8, + + // === PRIVATE: HASH CHAIN DATA === + enable_hash_chain_verification: u8, + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + exif_assertion_hash_offset: u32, + exif_assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + exif_assertion_length: u32, + + // === PRIVATE: ACTIONS ASSERTION === + actions_assertion_hash_offset: u32, + actions_assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + actions_assertion_length: u32, + + // === PRIVATE: COMMITMENT SALTS === + location_salt: Field, + time_salt: Field, + + // === PRIVATE: EDIT TIMESTAMP & SALT (for separate edit time commitment) === + exact_edit_timestamp: Field, // Edit/signing timestamp (0 if no edit) + edit_time_salt: Field // Salt for edit time commitment +) -> pub (Field, Field, Field, Field, [u8; 32]) { // Returns (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) + // ================================================================ + // STEP 0: Verify claim hash commitment packing + // ================================================================ + let computed_claim_commitment = Poseidon2::hash(bytes32_to_field_array(claim_hash), 2); + assert(computed_claim_commitment == claim_hash_commitment, "Claim hash commitment mismatch"); + + // ================================================================ + // STEP 1: Hash + DER-walk the leaf TBS; intermediate signs that hash + // ================================================================ + let leaf = verify_leaf_certificate( + tbs_certificate, + tbs_len, + cert_signature_ecdsa, + intermediate_ecdsa_pubkey_x, + intermediate_ecdsa_pubkey_y + ); + + // ================================================================ + // STEP 2: Derive Leaf Key Hash (key taken from the signed TBS) + // ================================================================ + let x_field = bytes_to_field(leaf.pubkey_x); + let y_field = bytes_to_field(leaf.pubkey_y); + let computed_leaf_key_hash = pedersen_hash([x_field, y_field]); + + // ================================================================ + // STEP 3: Verify Nullifier Derivation + // ================================================================ + let expected_nullifier = pedersen_hash([content_hash, computed_leaf_key_hash]); + assert(nullifier == expected_nullifier, "Invalid nullifier (leaf key binding failed)"); + + // ================================================================ + // STEP 4: Compute Link Commitment (returned as output) + // ================================================================ + let claim_hash_field = bytes_to_field(claim_hash); + let link_commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + + // ================================================================ + // STEP 4b: Verify Intermediate Leaf Formulation + // ================================================================ + let int_x_field = bytes_to_field(intermediate_ecdsa_pubkey_x); + let int_y_field = bytes_to_field(intermediate_ecdsa_pubkey_y); + let computed_intermediate_hash = pedersen_hash([int_x_field, int_y_field]); + + assert( + intermediate_leaf == computed_intermediate_hash, + "Intermediate Leaf witnessing mismatch (Self-Signing Attack prevention)" + ); + + // ================================================================ + // STEP 4c: Merkle Membership (Trust List Verification) + // ================================================================ + let computed_root = compute_merkle_root(intermediate_leaf, merkle_path, merkle_indices); + assert(computed_root == trust_list_root, "Intermediate CA not in trust list"); + + // ================================================================ + // STEP 5: Certificate Validity (Time) + // ================================================================ + // Dates come from the signed TBS and stay private. + assert(proof_timestamp as u64 as Field == proof_timestamp, "proof_timestamp exceeds u64"); + let ts = proof_timestamp as u64; + let not_before = leaf.not_before; + let not_after = leaf.not_after; + assert(ts >= not_before, "Certificate not yet valid at proof time"); + assert(ts <= not_after, "Certificate expired at proof time"); + + // ================================================================ + // STEP 6: Time Range Proof (Graduated Time Disclosure) + // ================================================================ + assert(exact_timestamp as u64 as Field == exact_timestamp, "exact_timestamp exceeds u64"); + assert(time_min as u64 as Field == time_min, "time_min exceeds u64"); + assert(time_max as u64 as Field == time_max, "time_max exceeds u64"); + let exact_ts = exact_timestamp as u64; + let min_ts = time_min as u64; + let max_ts = time_max as u64; + + assert(exact_ts >= min_ts, "Exact timestamp is before disclosed time_min"); + assert(exact_ts <= max_ts, "Exact timestamp is after disclosed time_max"); + + // ================================================================ + // STEP 6b: Edit Time Range Proof (0 = no edit, skip) + // ================================================================ + // When a photo is edited (capture -> export), exact_edit_timestamp is the + // signing/export time. For direct camera captures, it's 0 (sentinel). + if exact_edit_timestamp != 0 { + assert(exact_edit_timestamp as u64 as Field == exact_edit_timestamp, "exact_edit_timestamp exceeds u64"); + assert(edit_time_min as u64 as Field == edit_time_min, "edit_time_min exceeds u64"); + assert(edit_time_max as u64 as Field == edit_time_max, "edit_time_max exceeds u64"); + let edit_ts = exact_edit_timestamp as u64; + let edit_min = edit_time_min as u64; + let edit_max = edit_time_max as u64; + assert(edit_ts >= edit_min, "Edit timestamp before edit_time_min"); + assert(edit_ts <= edit_max, "Edit timestamp after edit_time_max"); + } else { + assert(edit_time_min == 0, "edit_time_min must be 0 when no edit"); + assert(edit_time_max == 0, "edit_time_max must be 0 when no edit"); + } + + // ================================================================ + // STEP 7: Location Range Proof (Graduated Location Disclosure) + // ================================================================ + // Unpack location_flags: bit 0 = lat negative, bit 1 = lon negative + // Reject if unused high bits (2-7) are set - prevents flag stuffing + assert(location_flags <= 3, "location_flags has invalid high bits set (must be 0-3)"); + let center_lat_is_negative = location_flags & 1; + let center_lon_is_negative = (location_flags >> 1) & 1; + + assert(exact_lat_is_negative <= 1, "exact_lat_is_negative must be 0 or 1"); + assert(exact_lon_is_negative <= 1, "exact_lon_is_negative must be 0 or 1"); + assert(skip_content_hash_binding <= 1, "skip_content_hash_binding must be 0 or 1"); + assert(skip_assertion_hash_verification <= 1, "skip_assertion_hash_verification must be 0 or 1"); + + assert(exact_lat_scaled as u64 as Field == exact_lat_scaled, "exact_lat_scaled exceeds u64"); + assert(center_lat_scaled as u64 as Field == center_lat_scaled, "center_lat_scaled exceeds u64"); + assert(exact_lon_scaled as u64 as Field == exact_lon_scaled, "exact_lon_scaled exceeds u64"); + assert(center_lon_scaled as u64 as Field == center_lon_scaled, "center_lon_scaled exceeds u64"); + + { + let lat_same_sign = (exact_lat_is_negative == center_lat_is_negative); + let d_lat = if lat_same_sign { + if exact_lat_scaled as u64 > center_lat_scaled as u64 { + exact_lat_scaled - center_lat_scaled + } else { + center_lat_scaled - exact_lat_scaled + } + } else { + exact_lat_scaled + center_lat_scaled + }; + + let lon_same_sign = (exact_lon_is_negative == center_lon_is_negative); + let d_lon = if lon_same_sign { + if exact_lon_scaled as u64 > center_lon_scaled as u64 { + exact_lon_scaled - center_lon_scaled + } else { + center_lon_scaled - exact_lon_scaled + } + } else { + exact_lon_scaled + center_lon_scaled + }; + + // NOTE: Euclidean distance in coordinate space. At high latitudes, + // 1 deg lon < 1 deg lat in real-world distance, so this circle is elliptical. + // The client-side radius computation (metersToScaledRadius) compensates + // by using the longitude conversion at the user's latitude, ensuring the + // privacy circle covers at least the requested radius in ALL directions. + let distance_squared = d_lat * d_lat + d_lon * d_lon; + assert(distance_squared as u64 as Field == distance_squared, "distance_squared exceeds u64"); + assert(radius_squared_scaled as u64 as Field == radius_squared_scaled, "radius_squared_scaled exceeds u64"); + + assert( + distance_squared as u64 <= radius_squared_scaled as u64, + "Exact GPS location is outside disclosed privacy circle" + ); + } + + // ================================================================ + // STEP 8: Hash Chain Verification (Trustless Metadata Binding) + // ================================================================ + assert( + enable_hash_chain_verification == 1, + "Hash chain verification must be enabled" + ); + + // Step 8a: Verify claim_hash = SHA256(claim_bytes) + verify_claim_hash(claim_bytes, claim_length, claim_hash); + + // Step 8b: Verify content_hash exists in claim_bytes + if skip_content_hash_binding == 0 { + verify_content_hash_binding(claim_bytes, content_hash_offset, content_hash); + } + + // Step 8c: Verify assertion hash chain + if skip_assertion_hash_verification == 0 { + verify_assertion_chain( + claim_bytes, + exif_assertion_hash_offset, + exif_assertion_bytes, + exif_assertion_length + ); + } + + // Step 8d: Verify actions assertion hash chain (optional) + let actions_assertion_hash: [u8; 32] = if actions_assertion_hash_offset > 0 { + verify_actions_assertion_chain( + claim_bytes, + actions_assertion_hash_offset, + actions_assertion_bytes, + actions_assertion_length + ); + let hash_result: [u8; 32] = dep::sha256::sha256_var( + actions_assertion_bytes, + actions_assertion_length as u32 + ); + hash_result + } else { + [0u8; 32] + }; + + // ================================================================ + // STEP 9: Compute Poseidon Commitments (Optional Future Reveal) + // ================================================================ + let lat_sign_field = exact_lat_is_negative as Field; + let lon_sign_field = exact_lon_is_negative as Field; + + let location_commitment = Poseidon2::hash( + [exact_lat_scaled, exact_lon_scaled, lat_sign_field, lon_sign_field, location_salt], + 5 + ); + + let time_commitment = Poseidon2::hash( + [exact_timestamp, time_salt], + 2 + ); + + // Edit time commitment: Poseidon2([edit_timestamp, salt]) or 0 sentinel + // Poseidon2 never outputs 0 for valid inputs, so 0 is safe as "no edit" sentinel + let edit_time_commitment = if exact_edit_timestamp == 0 { + 0 // Sentinel: no edit happened + } else { + Poseidon2::hash([exact_edit_timestamp, edit_time_salt], 2) + }; + + // Return public outputs + (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) +} + +/// First 32 bytes of a SHA-512 digest: the ECDSA P-256 message input +/// (e = leftmost 256 bits of the hash). +fn sha512_to_p256_input(digest: [u8; 64]) -> [u8; 32] { + let mut out: [u8; 32] = [0; 32]; + for i in 0..32 { + out[i] = digest[i]; + } + out +} + +/// Hash (SHA-512) and DER-walk the leaf TBSCertificate, check its signature +/// algorithm is ecdsa-with-SHA512, then check that the root's ECDSA P-256 +/// signature covers exactly that digest. +fn verify_leaf_certificate( + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + cert_signature_ecdsa: [u8; 64], + intermediate_ecdsa_pubkey_x: [u8; 32], + intermediate_ecdsa_pubkey_y: [u8; 32] +) -> LeafCertSha512 { + let leaf = bind_leaf_cert_sha512(tbs_certificate, tbs_len); + let valid = verify_signature( + intermediate_ecdsa_pubkey_x, + intermediate_ecdsa_pubkey_y, + cert_signature_ecdsa, + sha512_to_p256_input(leaf.sha512) + ); + assert(valid, "ECDSA P-256 certificate verification failed"); + leaf +} + +/// Convert 32 bytes to Field (big-endian) +fn bytes_to_field(bytes: [u8; 32]) -> Field { + let mut result: Field = 0; + for i in 0..32 { + result = result * 256 + bytes[i] as Field; + } + result +} + +/// Convert 32 bytes to 2 Field elements for Poseidon2 hashing +/// Splits into two 16-byte (128-bit) chunks that fit within the BN254 field +fn bytes32_to_field_array(bytes: [u8; 32]) -> [Field; 2] { + // First 16 bytes -> Field 0 + let mut f0: Field = 0; + for i in 0..16 { + f0 = f0 * 256 + bytes[i] as Field; + } + // Last 16 bytes -> Field 1 + let mut f1: Field = 0; + for i in 16..32 { + f1 = f1 * 256 + bytes[i] as Field; + } + [f0, f1] +} + +/// Verify content hash exists in claim at offset +fn verify_content_hash_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + verify_content_hash_in_claim(claim_bytes, content_hash_offset, expected_content_hash); +} + +/// Compute Merkle root from leaf and proof +fn compute_merkle_root( + leaf: Field, + path: [Field; 8], + indices: [Field; 8] +) -> Field { + let mut current = leaf; + + for i in 0..8 { + assert((indices[i] == 0) | (indices[i] == 1), "Merkle index must be 0 or 1"); + let path_element = path[i]; + let is_right = indices[i]; + let left = if is_right == 0 { current } else { path_element }; + let right = if is_right == 0 { path_element } else { current }; + current = pedersen_hash([left, right]); + } + + current +} + +// ==================================================================== +// TESTS +// ==================================================================== + +#[test] +fn test_merkle_root_computation() { + let leaf: Field = 12345; + let path: [Field; 8] = [0; 8]; + let indices: [Field; 8] = [0; 8]; + + let root = compute_merkle_root(leaf, path, indices); + assert(root != leaf, "Merkle root should not equal leaf"); + + let root2 = compute_merkle_root(leaf, path, indices); + assert(root == root2, "Merkle root should be deterministic"); +} + +#[test] +fn test_merkle_different_leaves() { + let path: [Field; 8] = [0; 8]; + let indices: [Field; 8] = [0; 8]; + + let root1 = compute_merkle_root(111, path, indices); + let root2 = compute_merkle_root(222, path, indices); + + assert(root1 != root2, "Different leaves should produce different roots"); +} + +#[test] +fn test_time_range_exact_bounds() { + let exact: u64 = 1000; + let min: u64 = 1000; + let max: u64 = 2000; + + assert(exact >= min, "Timestamp at min bound should pass"); + assert(exact <= max, "Timestamp within range should pass"); +} + +#[test] +fn test_location_same_point() { + let exact_lat: Field = 510000000; + let exact_lon: Field = 100000000; + let center_lat: Field = 510000000; + let center_lon: Field = 100000000; + + let d_lat = if exact_lat as u64 > center_lat as u64 { + exact_lat - center_lat + } else { + center_lat - exact_lat + }; + + let d_lon = if exact_lon as u64 > center_lon as u64 { + exact_lon - center_lon + } else { + center_lon - exact_lon + }; + + let distance_squared = d_lat * d_lat + d_lon * d_lon; + assert(distance_squared == 0, "Same point should have zero distance"); +} + +#[test] +fn test_bytes_to_field() { + let mut bytes: [u8; 32] = [0; 32]; + bytes[31] = 1; + let field = bytes_to_field(bytes); + assert(field == 1); + + bytes[31] = 255; + let field2 = bytes_to_field(bytes); + assert(field2 == 255); +} + +#[test] +fn test_nullifier_derivation_ecdsa() { + let content_hash: Field = 111; + let leaf_key_hash: Field = 222; + let nullifier = pedersen_hash([content_hash, leaf_key_hash]); + + let different_content: Field = 333; + let different_nullifier = pedersen_hash([different_content, leaf_key_hash]); + assert(nullifier != different_nullifier); +} + +#[test] +fn test_link_commitment_with_claim_hash() { + let intermediate_leaf: Field = 12345; + let claim_hash_field: Field = 99999; + let link_blind: Field = 67890; + + let commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + let commit2 = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + assert(commit == commit2); + + let different_claim: Field = 11111; + let commit3 = pedersen_hash([intermediate_leaf, different_claim, link_blind]); + assert(commit != commit3); +} + +// ==================================================================== +// REAL CERTIFICATE TESTS (ProofMode P-256 leaf, P-256 root, +// ecdsa-with-SHA512; root key recovered from the signature) +// ==================================================================== + +mod real_cert_tests { + use super::{verify_leaf_certificate, MAX_TBS_SIZE}; + use dep::cert_binding::proofmode_vectors as pm; + use dep::cert_binding::test_vectors as tv; + + fn pad(a: [u8; M]) -> [u8; MAX_TBS_SIZE] { + let mut out: [u8; MAX_TBS_SIZE] = [0; MAX_TBS_SIZE]; + for i in 0..M { + out[i] = a[i]; + } + out + } + + fn spki_offset(t: [u8; MAX_TBS_SIZE]) -> u32 { + let mut off: u32 = 0; + for i in 0..600 { + if (off == 0) & (t[i] == 0x30) & (t[i + 1] == 0x59) & (t[i + 2] == 0x30) & (t[i + 3] == 0x13) { + off = i; + } + } + assert(off != 0); + off + } + + #[test] + fn test_proofmode_leaf_verifies_and_binds_key() { + let leaf = verify_leaf_certificate( + pad(pm::PROOFMODE_LEAF_TBS), + pm::PROOFMODE_LEAF_TBS_LEN, + pm::PROOFMODE_LEAF_SIG, + pm::PROOFMODE_LEAF_ISSUER_X, + pm::PROOFMODE_LEAF_ISSUER_Y, + ); + assert(leaf.sha512 == pm::PROOFMODE_LEAF_SHA512); + assert(leaf.pubkey_x == pm::PROOFMODE_LEAF_PUB_X); + assert(leaf.pubkey_y == pm::PROOFMODE_LEAF_PUB_Y); + assert(leaf.not_before == pm::PROOFMODE_LEAF_NOT_BEFORE); + assert(leaf.not_after == pm::PROOFMODE_LEAF_NOT_AFTER); + } + + #[test(should_fail_with = "ECDSA P-256 certificate verification failed")] + fn test_substituted_leaf_key_rejected() { + // The v1 skip forgery: any key in the leaf. Genuine root signature, + // another P-256 key in the SPKI. + let mut t = pad(pm::PROOFMODE_LEAF_TBS); + let off = spki_offset(t); + for i in 0..32 { + t[off + 27 + i] = tv::LEICA_LEAF_PUB_X[i]; + t[off + 59 + i] = tv::LEICA_LEAF_PUB_Y[i]; + } + let _ = verify_leaf_certificate( + t, + pm::PROOFMODE_LEAF_TBS_LEN, + pm::PROOFMODE_LEAF_SIG, + pm::PROOFMODE_LEAF_ISSUER_X, + pm::PROOFMODE_LEAF_ISSUER_Y, + ); + } + + #[test(should_fail_with = "ECDSA P-256 certificate verification failed")] + fn test_tampered_not_after_rejected() { + // Extend notAfter by a decade (UTCTime "27" -> "37"). + let mut t = pad(pm::PROOFMODE_LEAF_TBS); + let mut first: u32 = 0; + let mut second: u32 = 0; + for i in 0..300 { + if (t[i] == 0x17) & (t[i + 1] == 0x0d) { + if first == 0 { + first = i; + } else if second == 0 { + second = i; + } + } + } + assert(second != 0); + t[second + 2] = 0x33; + let _ = verify_leaf_certificate( + t, + pm::PROOFMODE_LEAF_TBS_LEN, + pm::PROOFMODE_LEAF_SIG, + pm::PROOFMODE_LEAF_ISSUER_X, + pm::PROOFMODE_LEAF_ISSUER_Y, + ); + } + + #[test(should_fail_with = "ECDSA P-256 certificate verification failed")] + fn test_other_root_rejected() { + // A different P-256 key (the Leica intermediate) did not sign this leaf. + let _ = verify_leaf_certificate( + pad(pm::PROOFMODE_LEAF_TBS), + pm::PROOFMODE_LEAF_TBS_LEN, + pm::PROOFMODE_LEAF_SIG, + tv::LEICA_LEAF_ISSUER_X, + tv::LEICA_LEAF_ISSUER_Y, + ); + } + + #[test(should_fail_with = "TBS signature algorithm mismatch")] + fn test_sha256_signed_leaf_rejected() { + // Leica leaf is ecdsa-with-SHA256: proof_a_ecdsa_p256_v2 handles it. + let mut s: [u8; 64] = [0; 64]; + for i in 0..32 { + s[i] = tv::LEICA_LEAF_SIG_R[i]; + s[32 + i] = tv::LEICA_LEAF_SIG_S[i]; + } + let _ = verify_leaf_certificate( + pad(tv::LEICA_LEAF_TBS), + tv::LEICA_LEAF_TBS_LEN, + s, + tv::LEICA_LEAF_ISSUER_X, + tv::LEICA_LEAF_ISSUER_Y, + ); + } +} From 5d988fe65a8353dbf5437f0869d54473d4f3d4c4 Mon Sep 17 00:00:00 2001 From: Jamie Newton <33573418+newtsjamie@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:51:28 +0000 Subject: [PATCH 3/7] Add RSA leaf key binding and ProofB PS256 v2 cert_binding gains read_rsa2048_spki (rsaEncryption, 2048-bit modulus, e = 65537), be_bytes_to_limbs, rsa_key_hash over all modulus limbs, p256_key_hash, and bind_leaf_cert_rsa_signed for sha256WithRSAEncryption issuers, which reads the leaf key type (P-256 or RSA-2048) from the SPKI DER. Tests cover the real Adobe RSA leaf and synthetic RSA chains. proof_b_ps256_v2 verifies the PS256 COSE signature with the leaf modulus given as bytes (limbs derived in-circuit) and derives the nullifier from the full-modulus key hash, so it pairs with RSA ProofA v2. Public layout matches proof_b_es256_v2 (7 values). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + cert_binding/src/lib.nr | 190 +++++++++++++++++ cert_binding/src/rsa_vectors.nr | 45 ++++ proof_b_ps256_v2/Nargo.toml | 19 ++ proof_b_ps256_v2/src/main.nr | 362 ++++++++++++++++++++++++++++++++ 5 files changed, 617 insertions(+) create mode 100644 cert_binding/src/rsa_vectors.nr create mode 100644 proof_b_ps256_v2/Nargo.toml create mode 100644 proof_b_ps256_v2/src/main.nr diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f24042a..6422323 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,6 +36,7 @@ jobs: - proof_b_es256_v2_core - proof_b_es256_v2 - proof_b_es256_v2_large + - proof_b_ps256_v2 - image_aggregator - tree_aggregator - selective_disclosure diff --git a/cert_binding/src/lib.nr b/cert_binding/src/lib.nr index f3b402e..f802753 100644 --- a/cert_binding/src/lib.nr +++ b/cert_binding/src/lib.nr @@ -29,11 +29,13 @@ /// - Dates before 1970-01-01 are rejected (unix time is unsigned here). use dep::sha256::sha256_var; +use std::hash::pedersen_hash; use dep::sha512::{sha384::sha384_var, sha512::sha512_var}; pub mod test_vectors; pub mod synthetic_vectors; pub mod proofmode_vectors; +pub mod rsa_vectors; /// Uncompressed P-256 SubjectPublicKeyInfo header (27 bytes), followed by /// X (32 bytes) and Y (32 bytes). @@ -261,6 +263,121 @@ pub fn bind_leaf_cert_sha512(tbs: [u8; N], tbs_len: u32) -> LeafCert LeafCertSha512 { sha512, pubkey_x, pubkey_y, not_before: w.not_before, not_after: w.not_after } } +// -------------------------------------------------------------------- +// RSA keys and leaf key hashing +// -------------------------------------------------------------------- + +/// RSA-2048 rsaEncryption SubjectPublicKeyInfo header (33 bytes): SPKI +/// SEQUENCE(290), AlgorithmIdentifier rsaEncryption NULL, BIT STRING(271), +/// RSAPublicKey SEQUENCE(266), INTEGER(257) with a 0x00 sign byte. Then the +/// 256-byte modulus and INTEGER 65537 (02 03 01 00 01). Total 294 bytes. +global SPKI_RSA2048_PREFIX: [u8; 33] = [ + 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, + 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, + 0x01, 0x01, 0x00, +]; +global RSA_E65537: [u8; 5] = [0x02, 0x03, 0x01, 0x00, 0x01]; + +/// DER content of AlgorithmIdentifier sha256WithRSAEncryption +/// (OID 1.2.840.113549.1.1.11, NULL parameters). +pub global ALG_RSA_SHA256: [u8; 13] = + [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00]; + +/// Read an RSA-2048 rsaEncryption SubjectPublicKeyInfo at spki_start and +/// return the big-endian modulus. The modulus must have its top bit set +/// (exactly 2048 bits) and the public exponent must be 65537. +pub fn read_rsa2048_spki(tbs: [u8; N], tbs_len: u32, spki_start: u32) -> [u8; 256] { + assert(spki_start + 294 <= tbs_len, "SPKI exceeds tbs_len"); + for i in 0..33 { + assert(tbs[spki_start + i] == SPKI_RSA2048_PREFIX[i], "SPKI is not RSA-2048 rsaEncryption"); + } + let mut modulus: [u8; 256] = [0; 256]; + for i in 0..256 { + modulus[i] = tbs[spki_start + 33 + i]; + } + assert(modulus[0] >= 0x80, "RSA modulus is not 2048 bits"); + for i in 0..5 { + assert(tbs[spki_start + 289 + i] == RSA_E65537[i], "RSA exponent is not 65537"); + } + modulus +} + +/// Big-endian bytes to noir-bignum limbs (120-bit limbs, least significant +/// first). Each limb is built from at most 15 bytes, so it is < 2^120. +pub fn be_bytes_to_limbs(bytes: [u8; NB]) -> [u128; NL] { + assert(NL * 15 >= NB, "too few limbs"); + let mut limbs: [u128; NL] = [0; NL]; + for i in 0..NL { + let mut limb: Field = 0; + for j in 0..15 { + // byte index from the most significant end of limb i + let k = 15 * i + 14 - j; // little-endian byte position + if k < NB { + limb = limb * 256 + bytes[NB - 1 - k] as Field; + } + } + limbs[i] = limb as u128; + } + limbs +} + +/// Key hash of an RSA public key for nullifiers and trust-list leaves: +/// pedersen_hash over ALL modulus limbs (v1 hashed only the 8 low limbs, +/// which an attacker can match with a modulus they can factor). +pub fn rsa_key_hash(modulus: [u8; NB]) -> Field { + let limbs: [u128; NL] = be_bytes_to_limbs(modulus); + let mut f: [Field; NL] = [0; NL]; + for i in 0..NL { + f[i] = limbs[i] as Field; + } + pedersen_hash(f) +} + +/// Key hash of a P-256 public key, as in the v2 circuits: +/// pedersen_hash([x as Field, y as Field]). +pub fn p256_key_hash(x: [u8; 32], y: [u8; 32]) -> Field { + let mut xf: Field = 0; + let mut yf: Field = 0; + for i in 0..32 { + xf = xf * 256 + x[i] as Field; + yf = yf * 256 + y[i] as Field; + } + pedersen_hash([xf, yf]) +} + +/// A leaf whose key is P-256 or RSA-2048, identified by key hash. +pub struct LeafCertAnyKey { + pub sha256: [u8; 32], + /// 0 = P-256 (key_hash = p256_key_hash), 1 = RSA-2048 (key_hash = rsa_key_hash, 18 limbs) + pub key_type: u8, + pub key_hash: Field, + pub not_before: u64, + pub not_after: u64, +} + +/// Hash (SHA-256) and parse a DER TBSCertificate signed with +/// sha256WithRSAEncryption whose subject key is either uncompressed P-256 or +/// RSA-2048/65537. The key type is read from the SPKI DER itself (P-256 SPKI +/// is SEQUENCE(89), RSA-2048 is SEQUENCE(290)); it is not a prover choice. +pub fn bind_leaf_cert_rsa_signed(tbs: [u8; N], tbs_len: u32) -> LeafCertAnyKey { + assert(tbs_len <= N, "tbs_len exceeds buffer"); + let sha256: [u8; 32] = sha256_var(tbs, tbs_len); + let w = walk_tbs(tbs, tbs_len); + assert_sig_alg(tbs, w, ALG_RSA_SHA256); + let is_p256 = tbs[w.spki_start + 1] == 0x59; + let mut key_hash: Field = 0; + let mut key_type: u8 = 0; + if is_p256 { + let (x, y) = read_p256_spki(tbs, tbs_len, w.spki_start); + key_hash = p256_key_hash(x, y); + } else { + let m = read_rsa2048_spki(tbs, tbs_len, w.spki_start); + key_hash = rsa_key_hash::<256, 18>(m); + key_type = 1; + } + LeafCertAnyKey { sha256, key_type, key_hash, not_before: w.not_before, not_after: w.not_after } +} + /// Hash and parse a DER TBSCertificate whose subject key is P-256. /// This body is kept as originally written (rather than calling walk_tbs) /// so the compiled v2 circuits, and their verification keys, do not change. @@ -314,6 +431,8 @@ pub fn bind_leaf_cert(tbs: [u8; N], tbs_len: u32) -> LeafCert { mod tests { use super::{bind_leaf_cert, bind_leaf_cert_sha384, bind_leaf_cert_sha512, days_from_civil, LeafCert}; use super::proofmode_vectors as pm; + use super::rsa_vectors as rv; + use super::{bind_leaf_cert_rsa_signed, be_bytes_to_limbs, rsa_key_hash, p256_key_hash}; use super::test_vectors as tv; use super::synthetic_vectors as sv; @@ -534,4 +653,75 @@ mod tests { fn test_sha512_rejects_sha256_signed_leaf() { let _ = bind_leaf_cert_sha512(pad(tv::LEICA_LEAF_TBS), tv::LEICA_LEAF_TBS_LEN); } + + #[test] + fn test_be_bytes_to_limbs() { + let mut b: [u8; 256] = [0; 256]; + b[255] = 0x01; + b[240] = 0x02; // byte 15 from the end: lowest byte of limb 1 + b[0] = 0x80; // top byte: limb 17 (2048 = 17 * 120 + 8) + let l: [u128; 18] = be_bytes_to_limbs(b); + assert(l[0] == 1); + assert(l[1] == 2); + assert(l[17] == 0x80); + for i in 2..17 { + assert(l[i] == 0); + } + } + + #[test] + fn test_rsa_leaf_by_rsa_ca_binds_modulus() { + let c = bind_leaf_cert_rsa_signed(pad(rv::SYN_RSA_LEAF_BY_RSA2048_TBS), rv::SYN_RSA_LEAF_BY_RSA2048_TBS_LEN); + assert(c.sha256 == rv::SYN_RSA_LEAF_BY_RSA2048_SHA256); + assert(c.key_type == 1); + assert(c.key_hash == rsa_key_hash::<256, 18>(rv::SYN_RSA_LEAF_MODULUS)); + assert(c.not_before == rv::SYN_RSA_LEAF_BY_RSA2048_NOT_BEFORE); + assert(c.not_after == rv::SYN_RSA_LEAF_BY_RSA2048_NOT_AFTER); + } + + #[test] + fn test_p256_leaf_by_rsa_ca_binds_key() { + let c = bind_leaf_cert_rsa_signed(pad(rv::SYN_P256_LEAF_BY_RSA2048_TBS), rv::SYN_P256_LEAF_BY_RSA2048_TBS_LEN); + assert(c.key_type == 0); + assert(c.key_hash == p256_key_hash(rv::SYN_EC_LEAF_PUB_X, rv::SYN_EC_LEAF_PUB_Y)); + } + + #[test] + fn test_adobe_rsa_leaf_binds_modulus() { + // Real Adobe leaf: RSA-2048 key, signed sha256WithRSAEncryption. + let c = bind_leaf_cert_rsa_signed(pad(tv::ADOBE_LEAF_TBS), tv::ADOBE_LEAF_TBS_LEN); + assert(c.sha256 == tv::ADOBE_LEAF_SHA256); + assert(c.key_type == 1); + assert(c.key_hash == rsa_key_hash::<256, 18>(rv::ADOBE_LEAF_MODULUS)); + assert(c.not_before == tv::ADOBE_LEAF_NOT_BEFORE); + assert(c.not_after == tv::ADOBE_LEAF_NOT_AFTER); + } + + #[test(should_fail_with = "RSA exponent is not 65537")] + fn test_rsa_exponent_altered() { + let mut t = pad(rv::SYN_RSA_LEAF_BY_RSA2048_TBS); + let mut off: u32 = 0; + for i in 0..400 { + if (off == 0) & (t[i] == 0x30) & (t[i + 1] == 0x82) & (t[i + 2] == 0x01) & (t[i + 3] == 0x22) { + off = i; + } + } + assert(off != 0); + t[off + 293] = 0x03; + let _ = bind_leaf_cert_rsa_signed(t, rv::SYN_RSA_LEAF_BY_RSA2048_TBS_LEN); + } + + #[test(should_fail_with = "TBS signature algorithm mismatch")] + fn test_rsa_path_rejects_ecdsa_signed_leaf() { + let _ = bind_leaf_cert_rsa_signed(pad(tv::LEICA_LEAF_TBS), tv::LEICA_LEAF_TBS_LEN); + } + + #[test] + fn test_rsa_key_hash_differs_in_high_limbs() { + // v1 hashed only limbs 0..8; here a change in the top byte must move the hash. + let mut m = rv::SYN_RSA_LEAF_MODULUS; + let h1 = rsa_key_hash::<256, 18>(m); + m[0] = m[0] ^ 0x01; + assert(h1 != rsa_key_hash::<256, 18>(m)); + } } diff --git a/cert_binding/src/rsa_vectors.nr b/cert_binding/src/rsa_vectors.nr new file mode 100644 index 0000000..1a63ad6 --- /dev/null +++ b/cert_binding/src/rsa_vectors.nr @@ -0,0 +1,45 @@ +// Synthetic RSA test chains (Python cryptography; random keys, discarded). +// Issuers sign sha256WithRSAEncryption, e = 65537. REDC = floor(2^(2*bits+6) / n) +// as 120-bit limbs, least significant first (noir-bignum Barrett parameter). + +pub global SYN_RSA2048_CA_MODULUS: [u8; 256] = [0xcc, 0x5b, 0x5f, 0xd2, 0x76, 0xcf, 0xe2, 0x32, 0x25, 0x29, 0x7f, 0x93, 0x3b, 0x54, 0xf8, 0xeb, 0x91, 0x91, 0x40, 0xa1, 0x0a, 0x12, 0xc7, 0xe7, 0x15, 0x83, 0xde, 0x40, 0x41, 0x17, 0xd2, 0xb7, 0x96, 0xda, 0xb2, 0xdd, 0x57, 0xed, 0xef, 0xc8, 0xa5, 0x45, 0x5c, 0x58, 0x7b, 0x87, 0xd2, 0xe4, 0x3b, 0x0f, 0x6f, 0xa0, 0x61, 0xa0, 0xa1, 0xb6, 0xf6, 0xe9, 0x45, 0x18, 0xa2, 0x50, 0xea, 0x75, 0x2b, 0x7f, 0x8d, 0x53, 0x13, 0x80, 0x6f, 0xad, 0x1f, 0x83, 0x06, 0x9c, 0x6f, 0x28, 0xa8, 0x88, 0xf4, 0x14, 0x02, 0x36, 0xe9, 0x5d, 0xdc, 0xac, 0xb3, 0x83, 0xee, 0xf7, 0xd4, 0xae, 0x21, 0xf2, 0x69, 0x42, 0xee, 0xa3, 0x93, 0x03, 0xb2, 0x55, 0xfe, 0x54, 0xcd, 0xc2, 0x58, 0x74, 0xc9, 0x90, 0xe4, 0x88, 0x3f, 0x32, 0x70, 0xbb, 0x29, 0x5e, 0x14, 0xa8, 0x74, 0xaa, 0xb9, 0xe7, 0xb1, 0xbb, 0x9a, 0xb1, 0x9b, 0xb8, 0x44, 0x41, 0x97, 0xce, 0xf1, 0xbc, 0xc7, 0x62, 0x23, 0xeb, 0xed, 0xa5, 0x69, 0x2f, 0x71, 0xf8, 0x48, 0x5f, 0x65, 0x1a, 0x65, 0x65, 0x17, 0x00, 0x48, 0x98, 0x93, 0x48, 0xd8, 0x28, 0xc1, 0xbd, 0x87, 0x33, 0xa8, 0x13, 0x0b, 0x9a, 0xc6, 0x55, 0x4a, 0x6c, 0x81, 0x97, 0x51, 0xea, 0x75, 0x4f, 0x60, 0x48, 0xef, 0x9e, 0x24, 0xb6, 0xae, 0x7e, 0x6d, 0x3b, 0x87, 0xee, 0x86, 0x20, 0xd4, 0x09, 0x37, 0x81, 0x9c, 0x80, 0xb5, 0x28, 0x41, 0x1a, 0x8b, 0xe3, 0x9b, 0xbe, 0xa5, 0xba, 0xbb, 0x8b, 0x03, 0xc6, 0x52, 0x23, 0x99, 0xbe, 0xac, 0x72, 0x1d, 0x5a, 0xf7, 0x59, 0x08, 0x88, 0x31, 0x9a, 0x4a, 0x05, 0x35, 0xb9, 0x56, 0x32, 0x54, 0xf9, 0x40, 0x8b, 0x51, 0x0a, 0xec, 0xe7, 0x88, 0x9a, 0x2b, 0xfb, 0x48, 0x18, 0xbd, 0x72, 0x6c, 0x20, 0x75, 0x2e, 0xbd, 0x27]; +pub global SYN_RSA2048_CA_REDC: [u128; 18] = [0x834119225b4a231712b8a605536c53, 0x2c0c4029acf7b2fa76b452f7499ef4, 0x278b111bd7e6f919e99a41b6f9947b, 0x54a6e5b5759ec3431b3cfed64dd3ab, 0xb9959771a215c05c67192139c8c92c, 0xe3fb90bb44bb76c8e9d8591d0c0d51, 0x494b699ce845daca2c0e835d77b2f, 0x39916b5c685ae4a15375086626fd3f, 0x3678b56f0342c5a08ef76e46a7d6fd, 0xdee73fca2cea8266daeadd467daf4, 0xe1140291149c4e2104b3f8b782eda8, 0xe1849883d6a3257aa5dfa4cb4b9b7e, 0xcc7f19d815cb1a71757c1c6563a2d9, 0x4e57b37524156fffce2da915e4b7fd, 0xfc8ee1f73a486f36f68ecd5788bf6b, 0xc7ef599c4f0d78722b04dcb716e3d2, 0x672955d2c50dc228f23dd739239d96, 0x502c]; +pub global SYN_RSA4096_CA_MODULUS: [u8; 512] = [0xcd, 0x28, 0xe4, 0x2c, 0x7b, 0xe0, 0x05, 0xcb, 0x44, 0xb3, 0xc5, 0x43, 0x31, 0x5e, 0x4a, 0x5f, 0x25, 0x7b, 0xde, 0xcf, 0xad, 0x2b, 0xb1, 0xce, 0x3c, 0xef, 0x6a, 0x9b, 0x8e, 0xc2, 0x3e, 0x14, 0x01, 0xb8, 0xc2, 0x87, 0x3d, 0x4b, 0x97, 0x49, 0x3f, 0x19, 0x36, 0x20, 0x53, 0xf9, 0xc9, 0x25, 0xaf, 0x3b, 0xcc, 0xd5, 0xe7, 0xce, 0xbf, 0xe7, 0xd5, 0xfb, 0x44, 0x16, 0x18, 0x7a, 0x02, 0x6c, 0xf4, 0x90, 0xb8, 0x16, 0x22, 0xdb, 0xea, 0x9b, 0x33, 0xfe, 0x55, 0x39, 0xa8, 0x09, 0xed, 0xb5, 0xd0, 0x9b, 0xa8, 0xee, 0x46, 0xe0, 0x33, 0x83, 0xde, 0x0e, 0x6c, 0xcc, 0x5d, 0x68, 0x88, 0xb6, 0x39, 0x39, 0x66, 0x24, 0xa4, 0xfc, 0xe3, 0x64, 0x6d, 0x13, 0xee, 0xa4, 0x9f, 0x6a, 0x92, 0x8f, 0x24, 0x36, 0xb4, 0xfb, 0x7c, 0xdd, 0xcc, 0x30, 0x30, 0xc8, 0x63, 0x3e, 0xa4, 0xc7, 0x8c, 0xaf, 0xe3, 0x6c, 0x7b, 0xa5, 0xda, 0x6a, 0x7d, 0x52, 0xe4, 0x1a, 0x74, 0x8e, 0x67, 0x12, 0x46, 0x35, 0xa1, 0x03, 0x84, 0xb1, 0x9d, 0xd2, 0xbe, 0x16, 0xe4, 0xbf, 0x93, 0xdb, 0x12, 0x80, 0x0b, 0x18, 0x2f, 0x9e, 0x1e, 0xcf, 0x75, 0x32, 0x32, 0xe2, 0xa1, 0xb2, 0x84, 0xc7, 0xab, 0xd8, 0x01, 0xa2, 0xb4, 0xed, 0x59, 0x89, 0xdf, 0x6c, 0x97, 0xb4, 0xd1, 0xf1, 0x21, 0x1d, 0xc8, 0x18, 0x96, 0x44, 0xea, 0x8b, 0x50, 0xe9, 0xcd, 0x6f, 0x5f, 0x94, 0xd0, 0xeb, 0xe5, 0x34, 0x3d, 0x08, 0x1a, 0x09, 0x98, 0x45, 0x8b, 0x13, 0x14, 0x08, 0xab, 0x11, 0x40, 0x82, 0xf5, 0x71, 0x47, 0xe5, 0x96, 0xf6, 0xa8, 0xde, 0x1f, 0x86, 0x68, 0x54, 0x82, 0xc8, 0x41, 0xca, 0x33, 0xaa, 0x2a, 0xb6, 0x9c, 0x9d, 0xa6, 0x66, 0xe5, 0xec, 0xe8, 0xb6, 0x5a, 0x59, 0x11, 0x4a, 0x52, 0x6a, 0x18, 0x14, 0xc7, 0x8e, 0xc6, 0x88, 0xe0, 0xc7, 0xb7, 0xc3, 0xdd, 0xec, 0xb5, 0xba, 0x0a, 0x3a, 0x0d, 0x6b, 0x6f, 0xac, 0x25, 0x65, 0xbf, 0x7a, 0x1c, 0xd6, 0x32, 0xb5, 0x69, 0x31, 0x40, 0xd0, 0xb6, 0xea, 0xa8, 0xd5, 0x90, 0x80, 0xb9, 0xb6, 0xcd, 0x70, 0x3c, 0xd0, 0xe2, 0x94, 0x79, 0x4b, 0x1a, 0x55, 0xba, 0x4a, 0xc2, 0x02, 0xff, 0x2b, 0xc7, 0x44, 0x63, 0x3d, 0x89, 0x53, 0x7a, 0x42, 0xb4, 0xe3, 0x04, 0x42, 0x1b, 0x46, 0x26, 0xdb, 0x50, 0xe6, 0xbb, 0xef, 0xc3, 0x6f, 0x61, 0xb2, 0x11, 0x07, 0xb3, 0x4d, 0xa9, 0xd7, 0x81, 0xf0, 0xfa, 0x8f, 0x53, 0xe4, 0x18, 0x26, 0xc9, 0x67, 0x0a, 0xb4, 0xb8, 0xef, 0xcb, 0xa7, 0x1b, 0xe2, 0x92, 0xf9, 0x4b, 0x37, 0x34, 0x56, 0xa5, 0x9e, 0xce, 0xcf, 0x97, 0x18, 0xe4, 0xb1, 0xee, 0xcd, 0xe9, 0x3d, 0x89, 0xd0, 0x4d, 0xa9, 0x59, 0x9d, 0x5a, 0x68, 0x01, 0x4f, 0x39, 0x94, 0xb5, 0x0b, 0x18, 0xaf, 0xd3, 0xef, 0xce, 0xdb, 0x6c, 0x21, 0x70, 0xfd, 0x23, 0xc0, 0x65, 0x57, 0xcc, 0xdf, 0x2d, 0x93, 0x2f, 0xcf, 0x5b, 0x22, 0x76, 0xf4, 0x76, 0x44, 0xab, 0x1e, 0x1f, 0xf8, 0x9c, 0x49, 0xa4, 0x0e, 0x50, 0x7f, 0xa5, 0xc5, 0xcb, 0x11, 0x38, 0x4d, 0xcf, 0x5c, 0x53, 0x47, 0xaa, 0x01, 0x30, 0xda, 0x53, 0x95, 0x11, 0xcb, 0xef, 0x87, 0x76, 0x6c, 0xc3, 0xf4, 0x65, 0x0c, 0x45, 0xbc, 0x9d, 0xb7, 0xb2, 0x3b, 0xcf, 0x9a, 0x45, 0xbc, 0xb7, 0x5c, 0xf6, 0x9f, 0xbc, 0x1a, 0xa9, 0x82, 0x43, 0x16, 0x49, 0xac, 0xee, 0x4d, 0x5c, 0xd3, 0xfd, 0x8a, 0xb8, 0x7d, 0x79, 0x2b, 0x1b, 0xd6, 0x94, 0x53, 0xea, 0x33, 0xf4, 0x55, 0x87, 0x73, 0xdc, 0xf7, 0x0a, 0x25, 0xff, 0x32, 0xe1, 0x8c, 0x1e, 0x53, 0x9f, 0x17, 0xdc, 0x4c, 0x8c, 0x2c, 0x76, 0x37, 0xec, 0x7b]; +pub global SYN_RSA4096_CA_REDC: [u128; 35] = [0x322b18b476525547119f916a7a547b, 0xa7d0235c97108b9f84611563eba125, 0x309f0ee797a85d69a039cff82dc058, 0x8101241be23604ce8e8a629cb807a6, 0x9cfe207b1b36860f7209387dc2020b, 0x9df8bacc1d68c72d9957d51efdc5ed, 0xa0bacb32ca410d92a83f4fa5caae17, 0xfb1fa49472f321b421b2aed217a944, 0x6fc4a40c13505553d62e5d2f063e91, 0xf885e810bc893d52e404b2fe0fc6e8, 0xfcb9a6a90a1ddc54d61219394ed90a, 0x420c2168c9015f2a1d09628b74ef62, 0x5679a02aeca25a8772f0fcacaefecf, 0xb392c060cc359428c667d1d622b87f, 0x1936da5bdf4d82923a448ff8644745, 0x6fbf8526314bae7e9a286ade355b62, 0x1f30097c81c0217e4792c5b2b459e6, 0x29eecf09eb97d66136ea34766dc8a1, 0x2eec833d79cc808adb630ce986d956, 0xb4c5ee6fcadc2ae425bff15c4117f4, 0xaf0e75656654a5a3c4d07673df754e, 0x5dbe649f66f070923e6aec1ac093db, 0xec7bb2e312016d5e01ee9ef55fb83a, 0xc97ae6a040a6812e31b91a5b8e8679, 0x1f5043570e99336bf3d4426cb56e2e, 0xd53193c27f5c424b4bf38e311cdfa6, 0xdb3e72aa46e034476da160561db487, 0xd974536e49b1f5e8ed69c5c5506f62, 0xec8a468360540f96690e5dbfd4ff10, 0x2226b42a8b395b133f52a773f3c21, 0x4e30d02fe620b29748db574d2a8e3d, 0xcb09434c08951d2c9b1df572552ae3, 0x335cc795acde4bad658a3eb43d16df, 0x461d5d21ded81c068dfcf5d4ebb4d, 0x4fdc17]; +pub global SYN_OTHER_RSA2048_MODULUS: [u8; 256] = [0xf5, 0x9e, 0x54, 0xa3, 0x57, 0x0d, 0xc2, 0xa0, 0xb1, 0xf1, 0x56, 0xf6, 0xb5, 0x7a, 0xd2, 0x6f, 0x99, 0x4c, 0xfc, 0x4a, 0x11, 0x14, 0xea, 0x57, 0xd5, 0xd3, 0xf3, 0x0d, 0xfa, 0x70, 0xc3, 0x9b, 0x3c, 0xd1, 0x6d, 0x92, 0x4f, 0xfc, 0x98, 0xd1, 0x6b, 0x4d, 0xb1, 0x17, 0x17, 0x21, 0xf5, 0x98, 0xdf, 0x34, 0xd4, 0x4f, 0x33, 0x32, 0x34, 0x83, 0x6d, 0xcc, 0x1d, 0xe5, 0x3c, 0xef, 0x6e, 0xf0, 0xa2, 0x20, 0x07, 0xc3, 0xc2, 0x94, 0xff, 0xa4, 0xc5, 0x70, 0x42, 0x4f, 0xf8, 0x86, 0x79, 0x5b, 0x78, 0x99, 0x55, 0x1d, 0x8c, 0xd5, 0x5b, 0x29, 0x37, 0xca, 0xad, 0x9a, 0x70, 0xd8, 0x8f, 0x21, 0xd5, 0x3e, 0x8c, 0xd5, 0x02, 0x52, 0xb2, 0x15, 0x9e, 0x5a, 0x89, 0x6a, 0x4a, 0xe8, 0x30, 0xe5, 0xe3, 0xf1, 0x55, 0x63, 0xc4, 0x58, 0x24, 0xe0, 0x07, 0x83, 0x07, 0xa9, 0x03, 0x68, 0x65, 0x74, 0x44, 0x35, 0x06, 0xbd, 0xf4, 0xfe, 0x76, 0x68, 0x47, 0x57, 0x6a, 0x46, 0xb2, 0x08, 0xa1, 0x97, 0x5e, 0x62, 0x4c, 0xfd, 0xdc, 0x2d, 0xd2, 0x82, 0x82, 0x32, 0xac, 0xd6, 0x40, 0xf2, 0x50, 0x2a, 0x47, 0x36, 0x8c, 0x3b, 0x7b, 0x5e, 0x60, 0xaf, 0xdb, 0x1a, 0x2a, 0x55, 0x99, 0xa0, 0x75, 0x1b, 0x78, 0x08, 0x13, 0xdd, 0x40, 0x2d, 0x93, 0x99, 0x33, 0x85, 0x46, 0xb5, 0x1c, 0x3e, 0x51, 0x45, 0x38, 0xa7, 0x9f, 0xd6, 0x8b, 0x53, 0x79, 0x5b, 0x73, 0xb3, 0xc0, 0xe1, 0x78, 0x57, 0x68, 0x51, 0xd8, 0xe9, 0x73, 0xf0, 0xf5, 0x8c, 0xbc, 0x9e, 0x41, 0xcc, 0x4b, 0x70, 0x3d, 0x21, 0x97, 0x60, 0x1d, 0x02, 0x23, 0x0d, 0xe5, 0x7e, 0x3f, 0x5c, 0xd0, 0x3c, 0x77, 0xbb, 0x9a, 0x42, 0x9d, 0xb6, 0xca, 0x80, 0x3d, 0x48, 0xb0, 0xb5, 0x46, 0xd5, 0x1c, 0x4b, 0x75, 0x92, 0x29, 0xb3, 0xdc, 0xa1]; +pub global SYN_OTHER_RSA2048_REDC: [u128; 18] = [0xb7325060f0ca76441c521dc1da352, 0xee2357f500825d66bb45b9707af2f8, 0x57e5031292be60e2c998d8b4c5fb3d, 0x86a150c8d247c0ba53953575027782, 0xacf22d255f7327cdcd7fde95dc315e, 0x2f0b3a8452207536a541b327dc144, 0x72d1fcb842b152cd1d1ea0682fdce3, 0x72010979925886175ed5ee1410aac4, 0x3906bee7b6580301abc74ab3617df7, 0x54ced94abb0341d13aa4d6106f0183, 0x68236d22aae7f8b4855f4f859e9f73, 0x909c76f4ded2bfd6afba8e2564cdb2, 0xd847eb772b93e90cfbae91c5e2eb3a, 0x266e490337f1f5f9b9a8dc8997e95e, 0x2f0cdcde48066db64ad77d4cc9013c, 0x27b9e3c69ac53cea37c3e9b8edf496, 0x800bafb61613744994153fe8f38572, 0x42b4]; +pub global SYN_EC_LEAF_PUB_X: [u8; 32] = [0x92, 0x7b, 0x79, 0x03, 0x50, 0xe6, 0x88, 0xac, 0xd2, 0x13, 0x9b, 0xed, 0x45, 0x7b, 0x39, 0x0e, 0x11, 0x4b, 0x98, 0x26, 0x1b, 0x44, 0xb2, 0x43, 0x35, 0x35, 0x6a, 0xe0, 0x32, 0x4c, 0x20, 0x44]; +pub global SYN_EC_LEAF_PUB_Y: [u8; 32] = [0x84, 0x39, 0xaf, 0x37, 0xa9, 0x98, 0xff, 0x27, 0x1a, 0x94, 0xac, 0x12, 0x07, 0x9f, 0x84, 0x18, 0xdf, 0x0f, 0x45, 0x18, 0xd5, 0x00, 0xa8, 0xfe, 0xe2, 0x8f, 0x60, 0xe3, 0xd5, 0x52, 0x98, 0xa2]; +pub global SYN_RSA_LEAF_MODULUS: [u8; 256] = [0xb7, 0x7d, 0xf0, 0xed, 0x1a, 0x83, 0x81, 0x3d, 0x47, 0xa7, 0x0e, 0xd5, 0xe2, 0x31, 0x75, 0xf9, 0xe7, 0x6b, 0x98, 0x65, 0xf4, 0x2a, 0x80, 0xf3, 0x72, 0x64, 0x74, 0xd4, 0xf2, 0x14, 0x51, 0x4a, 0x70, 0xd6, 0x4d, 0xd7, 0x98, 0xf4, 0x3f, 0xbd, 0x94, 0x32, 0xe4, 0xd2, 0xd4, 0x80, 0xfb, 0x2e, 0x38, 0xb4, 0xd9, 0x8c, 0x06, 0x5f, 0xc3, 0x23, 0x40, 0x6e, 0xef, 0x96, 0x9e, 0xc6, 0xeb, 0xa8, 0x1a, 0x25, 0xa0, 0xb3, 0x0b, 0x08, 0xe7, 0xd8, 0xa1, 0xfc, 0xf4, 0x20, 0xcb, 0xcb, 0x27, 0xca, 0x56, 0xcb, 0xb6, 0xd8, 0x99, 0xfc, 0x7c, 0xb1, 0xd1, 0xb5, 0x28, 0xdd, 0xaa, 0x33, 0x7d, 0xe3, 0xc9, 0x06, 0x84, 0x9b, 0x5a, 0x8a, 0x9b, 0x05, 0x52, 0x14, 0x14, 0xe7, 0x9d, 0x59, 0xff, 0x51, 0xab, 0xeb, 0x90, 0x9b, 0x89, 0xc2, 0x42, 0x96, 0x77, 0x68, 0xeb, 0x1b, 0x7c, 0x16, 0x35, 0x4e, 0x8f, 0x0a, 0x57, 0x57, 0x21, 0x7a, 0xd1, 0x6c, 0xca, 0x11, 0x26, 0xac, 0x41, 0x7f, 0xc3, 0x5d, 0x49, 0x14, 0x12, 0x79, 0xf4, 0x92, 0x15, 0xf3, 0x84, 0x62, 0x43, 0x47, 0x48, 0x88, 0x6c, 0xb9, 0xe6, 0xab, 0x46, 0xa1, 0x4f, 0xad, 0x64, 0xe7, 0x06, 0x40, 0x72, 0x1c, 0x71, 0x91, 0xf7, 0xd0, 0xca, 0x56, 0x0b, 0xab, 0x9b, 0x16, 0x9b, 0x18, 0xbd, 0xfa, 0x28, 0x67, 0x4e, 0xd7, 0x9b, 0xaf, 0x62, 0xd2, 0xbe, 0xcb, 0x40, 0xdf, 0x6f, 0x52, 0xb9, 0xc6, 0xb7, 0x68, 0x34, 0xa8, 0x52, 0xe9, 0xf0, 0x3b, 0xb5, 0x30, 0x28, 0x8c, 0x4c, 0x18, 0x62, 0xca, 0x77, 0x5a, 0x99, 0x87, 0x18, 0xd0, 0xdb, 0xc1, 0x3b, 0x2c, 0xfe, 0x6c, 0xfa, 0xaa, 0xf9, 0x31, 0x17, 0xa6, 0xc6, 0xf2, 0x6d, 0xea, 0x2e, 0x6b, 0x07, 0x1d, 0x57, 0x1e, 0xba, 0x47, 0x9d, 0x81, 0x9c, 0xe5, 0x21, 0x38, 0xe5, 0x31]; +pub global SYN_RSA_LEAF_REDC: [u128; 18] = [0x70113d81df7ff3d4dad3cf2a481f68, 0xb2b787271ed6fd51b4aa3ea54037f3, 0x341dcad2a35b0474b96dfd11f19aba, 0x49a6b5331e6355397d74171bdb81e4, 0x7c2957820c2f117751d154f1bc29e6, 0x9390052ac0404b868e6cbc8eb122bb, 0x78e75c833b8b510dbdfc60b74c9503, 0xba36cea388a56d34699c623120c145, 0x4d8306f11ff101c1b079a1beeb4a9d, 0x759a10790a9bc4f212190417d55914, 0x5edd2efcebaf4f381ac1bfafc54425, 0xb26b8476baf65912b529a776dd96a0, 0x2547407f990de6af03e6d8abaf0466, 0xfffdb6c66a745990459c7f3806b267, 0x594af1d596a3f0201a700ff73302c, 0xd989887a6f2323f706ca4d04905bc7, 0x3e8d8117c3c5dffdac53dbcf94e13c, 0x594a]; +pub global SYN_P256_LEAF_BY_RSA2048_TBS_LEN: u32 = 287; +pub global SYN_P256_LEAF_BY_RSA2048_TBS: [u8; 287] = [0x30, 0x82, 0x01, 0x1b, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x01, 0x65, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x33, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0d, 0x41, 0x70, 0x65, 0x72, 0x74, 0x72, 0x75, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x10, 0x54, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x2d, 0x32, 0x30, 0x34, 0x38, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x35, 0x30, 0x33, 0x30, 0x34, 0x30, 0x35, 0x30, 0x36, 0x30, 0x37, 0x5a, 0x17, 0x0d, 0x33, 0x34, 0x30, 0x38, 0x30, 0x39, 0x31, 0x30, 0x31, 0x31, 0x31, 0x32, 0x5a, 0x30, 0x40, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0d, 0x41, 0x70, 0x65, 0x72, 0x74, 0x72, 0x75, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x31, 0x26, 0x30, 0x24, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1d, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x2d, 0x32, 0x35, 0x36, 0x20, 0x4c, 0x65, 0x61, 0x66, 0x20, 0x28, 0x52, 0x53, 0x41, 0x2d, 0x32, 0x30, 0x34, 0x38, 0x20, 0x43, 0x41, 0x29, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x92, 0x7b, 0x79, 0x03, 0x50, 0xe6, 0x88, 0xac, 0xd2, 0x13, 0x9b, 0xed, 0x45, 0x7b, 0x39, 0x0e, 0x11, 0x4b, 0x98, 0x26, 0x1b, 0x44, 0xb2, 0x43, 0x35, 0x35, 0x6a, 0xe0, 0x32, 0x4c, 0x20, 0x44, 0x84, 0x39, 0xaf, 0x37, 0xa9, 0x98, 0xff, 0x27, 0x1a, 0x94, 0xac, 0x12, 0x07, 0x9f, 0x84, 0x18, 0xdf, 0x0f, 0x45, 0x18, 0xd5, 0x00, 0xa8, 0xfe, 0xe2, 0x8f, 0x60, 0xe3, 0xd5, 0x52, 0x98, 0xa2, 0xa3, 0x10, 0x30, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00]; +pub global SYN_P256_LEAF_BY_RSA2048_SHA256: [u8; 32] = [0xc4, 0xe8, 0xc4, 0x38, 0xfe, 0x5a, 0xf1, 0x7a, 0x27, 0x77, 0xa4, 0x8e, 0x21, 0x25, 0x6c, 0x0a, 0x6a, 0x56, 0x22, 0x23, 0xe0, 0x8d, 0x3b, 0x99, 0x0a, 0x55, 0xb6, 0xcd, 0xe1, 0xba, 0x78, 0xd2]; +pub global SYN_P256_LEAF_BY_RSA2048_NOT_BEFORE: u64 = 1741064767; +pub global SYN_P256_LEAF_BY_RSA2048_NOT_AFTER: u64 = 2038731072; +pub global SYN_P256_LEAF_BY_RSA2048_SIG: [u8; 256] = [0x5f, 0xe3, 0x58, 0x6b, 0x58, 0x27, 0xfb, 0xc0, 0xd9, 0x72, 0xe2, 0xd8, 0xed, 0x92, 0x11, 0x95, 0xaf, 0x17, 0x1a, 0xa8, 0x47, 0x9d, 0x8c, 0xf7, 0x1c, 0xe9, 0x6f, 0xd3, 0x8c, 0x1a, 0x4b, 0xc0, 0x29, 0xc6, 0xac, 0x1c, 0xfa, 0x42, 0xd6, 0x42, 0xa5, 0x78, 0x1c, 0xc0, 0xaf, 0x85, 0x21, 0xf6, 0x5d, 0x1a, 0xdf, 0x0a, 0x5b, 0xd8, 0xfc, 0x42, 0x1b, 0x70, 0x47, 0x42, 0xdd, 0xa0, 0x35, 0x57, 0x90, 0x9c, 0x95, 0x57, 0x4a, 0xa0, 0xfb, 0x24, 0x28, 0x3e, 0x6b, 0x3b, 0x15, 0xe6, 0x07, 0xb7, 0x44, 0x46, 0x5b, 0xaf, 0x86, 0xab, 0xa8, 0xdb, 0x3d, 0xde, 0x67, 0x6e, 0x2c, 0x94, 0x8b, 0x4b, 0x83, 0xfe, 0x44, 0xb7, 0xf4, 0x69, 0xb3, 0xbb, 0x3a, 0x51, 0xa2, 0x23, 0x07, 0x0c, 0x04, 0x13, 0x4c, 0x1a, 0xb3, 0x6e, 0x1d, 0x6e, 0x81, 0xd9, 0xb3, 0xbf, 0x96, 0xb6, 0x8f, 0x49, 0x33, 0x96, 0xaa, 0x50, 0xaa, 0x3a, 0x72, 0x77, 0xaf, 0xb8, 0xbf, 0x22, 0x3e, 0x0e, 0x8e, 0x49, 0x2b, 0x66, 0x54, 0x6b, 0xa1, 0x81, 0xf8, 0x67, 0xa2, 0x0d, 0xbe, 0xfa, 0xa1, 0xc3, 0x80, 0xd9, 0xa5, 0x63, 0x2e, 0xa5, 0x3f, 0xfc, 0x98, 0x09, 0x84, 0xb2, 0xa3, 0x81, 0x4e, 0xd0, 0xaf, 0xaf, 0x20, 0x8e, 0xeb, 0xe9, 0x95, 0x78, 0x30, 0x56, 0x3d, 0x8e, 0x24, 0x67, 0xcc, 0x91, 0x3d, 0x25, 0xb4, 0xf9, 0x75, 0x02, 0x82, 0x47, 0x3a, 0x79, 0x42, 0x2b, 0xdf, 0xa4, 0x27, 0xad, 0x67, 0x44, 0x4a, 0x17, 0x77, 0x58, 0xaa, 0x78, 0xff, 0x86, 0xd0, 0x5d, 0x66, 0xd8, 0xf6, 0x8c, 0xb6, 0x8d, 0x7b, 0x78, 0x71, 0x68, 0xbe, 0x72, 0x60, 0x76, 0x5e, 0x9c, 0x9e, 0x44, 0xfc, 0xe6, 0xf3, 0xe3, 0x3e, 0xc8, 0x86, 0x77, 0x46, 0xae, 0xab, 0xb1, 0x78, 0x2d, 0x33, 0x17, 0xd3, 0xa4, 0x60, 0x34, 0xd1, 0x04]; +pub global SYN_RSA_LEAF_BY_RSA2048_TBS_LEN: u32 = 493; +pub global SYN_RSA_LEAF_BY_RSA2048_TBS: [u8; 493] = [0x30, 0x82, 0x01, 0xe9, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x01, 0x66, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x33, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0d, 0x41, 0x70, 0x65, 0x72, 0x74, 0x72, 0x75, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x10, 0x54, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x2d, 0x32, 0x30, 0x34, 0x38, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x35, 0x30, 0x33, 0x30, 0x34, 0x30, 0x35, 0x30, 0x36, 0x30, 0x37, 0x5a, 0x17, 0x0d, 0x33, 0x34, 0x30, 0x38, 0x30, 0x39, 0x31, 0x30, 0x31, 0x31, 0x31, 0x32, 0x5a, 0x30, 0x43, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0d, 0x41, 0x70, 0x65, 0x72, 0x74, 0x72, 0x75, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x31, 0x29, 0x30, 0x27, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x2d, 0x32, 0x30, 0x34, 0x38, 0x20, 0x4c, 0x65, 0x61, 0x66, 0x20, 0x28, 0x52, 0x53, 0x41, 0x2d, 0x32, 0x30, 0x34, 0x38, 0x20, 0x43, 0x41, 0x29, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xb7, 0x7d, 0xf0, 0xed, 0x1a, 0x83, 0x81, 0x3d, 0x47, 0xa7, 0x0e, 0xd5, 0xe2, 0x31, 0x75, 0xf9, 0xe7, 0x6b, 0x98, 0x65, 0xf4, 0x2a, 0x80, 0xf3, 0x72, 0x64, 0x74, 0xd4, 0xf2, 0x14, 0x51, 0x4a, 0x70, 0xd6, 0x4d, 0xd7, 0x98, 0xf4, 0x3f, 0xbd, 0x94, 0x32, 0xe4, 0xd2, 0xd4, 0x80, 0xfb, 0x2e, 0x38, 0xb4, 0xd9, 0x8c, 0x06, 0x5f, 0xc3, 0x23, 0x40, 0x6e, 0xef, 0x96, 0x9e, 0xc6, 0xeb, 0xa8, 0x1a, 0x25, 0xa0, 0xb3, 0x0b, 0x08, 0xe7, 0xd8, 0xa1, 0xfc, 0xf4, 0x20, 0xcb, 0xcb, 0x27, 0xca, 0x56, 0xcb, 0xb6, 0xd8, 0x99, 0xfc, 0x7c, 0xb1, 0xd1, 0xb5, 0x28, 0xdd, 0xaa, 0x33, 0x7d, 0xe3, 0xc9, 0x06, 0x84, 0x9b, 0x5a, 0x8a, 0x9b, 0x05, 0x52, 0x14, 0x14, 0xe7, 0x9d, 0x59, 0xff, 0x51, 0xab, 0xeb, 0x90, 0x9b, 0x89, 0xc2, 0x42, 0x96, 0x77, 0x68, 0xeb, 0x1b, 0x7c, 0x16, 0x35, 0x4e, 0x8f, 0x0a, 0x57, 0x57, 0x21, 0x7a, 0xd1, 0x6c, 0xca, 0x11, 0x26, 0xac, 0x41, 0x7f, 0xc3, 0x5d, 0x49, 0x14, 0x12, 0x79, 0xf4, 0x92, 0x15, 0xf3, 0x84, 0x62, 0x43, 0x47, 0x48, 0x88, 0x6c, 0xb9, 0xe6, 0xab, 0x46, 0xa1, 0x4f, 0xad, 0x64, 0xe7, 0x06, 0x40, 0x72, 0x1c, 0x71, 0x91, 0xf7, 0xd0, 0xca, 0x56, 0x0b, 0xab, 0x9b, 0x16, 0x9b, 0x18, 0xbd, 0xfa, 0x28, 0x67, 0x4e, 0xd7, 0x9b, 0xaf, 0x62, 0xd2, 0xbe, 0xcb, 0x40, 0xdf, 0x6f, 0x52, 0xb9, 0xc6, 0xb7, 0x68, 0x34, 0xa8, 0x52, 0xe9, 0xf0, 0x3b, 0xb5, 0x30, 0x28, 0x8c, 0x4c, 0x18, 0x62, 0xca, 0x77, 0x5a, 0x99, 0x87, 0x18, 0xd0, 0xdb, 0xc1, 0x3b, 0x2c, 0xfe, 0x6c, 0xfa, 0xaa, 0xf9, 0x31, 0x17, 0xa6, 0xc6, 0xf2, 0x6d, 0xea, 0x2e, 0x6b, 0x07, 0x1d, 0x57, 0x1e, 0xba, 0x47, 0x9d, 0x81, 0x9c, 0xe5, 0x21, 0x38, 0xe5, 0x31, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x10, 0x30, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00]; +pub global SYN_RSA_LEAF_BY_RSA2048_SHA256: [u8; 32] = [0x03, 0x4f, 0x74, 0xad, 0xb7, 0xe0, 0x64, 0x00, 0x2f, 0x0c, 0xdd, 0x5e, 0x9c, 0x61, 0x88, 0xec, 0x4a, 0x76, 0xee, 0x21, 0x1c, 0x3c, 0x5b, 0x4c, 0x28, 0x8c, 0xf9, 0xa6, 0x6c, 0x06, 0x35, 0x6b]; +pub global SYN_RSA_LEAF_BY_RSA2048_NOT_BEFORE: u64 = 1741064767; +pub global SYN_RSA_LEAF_BY_RSA2048_NOT_AFTER: u64 = 2038731072; +pub global SYN_RSA_LEAF_BY_RSA2048_SIG: [u8; 256] = [0x66, 0x1c, 0xa0, 0xa6, 0x8b, 0xc7, 0x0b, 0xfb, 0x28, 0x71, 0xe3, 0xa8, 0xb6, 0xa7, 0x1f, 0x2a, 0x84, 0x7d, 0xd1, 0xcb, 0x88, 0xde, 0xc5, 0x56, 0x25, 0xe6, 0xdc, 0x56, 0x7e, 0x4c, 0x16, 0xa8, 0x6b, 0x0f, 0xd9, 0x3a, 0x55, 0x1d, 0xe2, 0x06, 0x93, 0xc1, 0x11, 0xde, 0xe5, 0x25, 0x6d, 0x18, 0x36, 0x67, 0xc7, 0xd8, 0x0a, 0x0c, 0xfc, 0x73, 0xe3, 0x5d, 0xc1, 0x73, 0x7f, 0xd3, 0x80, 0xef, 0xb0, 0xd7, 0xa1, 0xa7, 0x74, 0xec, 0x57, 0xf4, 0xd9, 0xd7, 0xa4, 0x2f, 0x72, 0x65, 0x33, 0x14, 0xec, 0x9a, 0x56, 0x99, 0x84, 0x2d, 0xa0, 0x69, 0x43, 0xc2, 0x53, 0x81, 0x4f, 0xaa, 0x26, 0x13, 0xc2, 0xec, 0x55, 0x46, 0xf3, 0x7a, 0x1e, 0xc3, 0x9e, 0x51, 0x63, 0xae, 0xb9, 0x3c, 0xcf, 0xf5, 0xff, 0xc8, 0x33, 0x0f, 0x5b, 0x5b, 0x26, 0xd2, 0x75, 0x71, 0x34, 0x60, 0x16, 0x84, 0x3b, 0x28, 0x04, 0xd0, 0x05, 0xe1, 0x3f, 0x9c, 0x11, 0x2d, 0xc1, 0x1c, 0x45, 0x02, 0x8e, 0xe0, 0x21, 0x37, 0x4a, 0xbf, 0x97, 0x79, 0x6f, 0x84, 0xdf, 0x3f, 0x40, 0xa1, 0x66, 0x0a, 0x09, 0x12, 0x53, 0x2c, 0xe3, 0x2d, 0x02, 0xf8, 0x85, 0x43, 0x8f, 0xee, 0xa9, 0xf2, 0x9e, 0x15, 0xae, 0x92, 0x68, 0x1c, 0x1f, 0x5c, 0x47, 0x07, 0xf4, 0xdf, 0x81, 0x71, 0x4e, 0x72, 0x69, 0x95, 0x9c, 0xf3, 0xfa, 0x7d, 0xae, 0x59, 0x25, 0x6b, 0xd8, 0x4e, 0xa9, 0x41, 0x4c, 0xa5, 0xcf, 0x24, 0x49, 0x07, 0x3a, 0xfa, 0x24, 0x99, 0x44, 0xe7, 0xdc, 0x71, 0x56, 0x9a, 0x11, 0xd3, 0x83, 0x08, 0x7b, 0xc6, 0x28, 0x7e, 0x32, 0x24, 0xf6, 0xfd, 0x2b, 0xe8, 0x70, 0x42, 0x24, 0xc4, 0x07, 0x22, 0xff, 0xef, 0xdc, 0x05, 0x06, 0xe8, 0x12, 0xf6, 0xce, 0x8f, 0x05, 0x42, 0xdb, 0x69, 0x55, 0x29, 0x3c, 0x48, 0xd8, 0x28]; +pub global SYN_P256_LEAF_BY_RSA4096_TBS_LEN: u32 = 287; +pub global SYN_P256_LEAF_BY_RSA4096_TBS: [u8; 287] = [0x30, 0x82, 0x01, 0x1b, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x01, 0x67, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x33, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0d, 0x41, 0x70, 0x65, 0x72, 0x74, 0x72, 0x75, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x10, 0x54, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x2d, 0x34, 0x30, 0x39, 0x36, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x35, 0x30, 0x33, 0x30, 0x34, 0x30, 0x35, 0x30, 0x36, 0x30, 0x37, 0x5a, 0x17, 0x0d, 0x33, 0x34, 0x30, 0x38, 0x30, 0x39, 0x31, 0x30, 0x31, 0x31, 0x31, 0x32, 0x5a, 0x30, 0x40, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0d, 0x41, 0x70, 0x65, 0x72, 0x74, 0x72, 0x75, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x31, 0x26, 0x30, 0x24, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1d, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x2d, 0x32, 0x35, 0x36, 0x20, 0x4c, 0x65, 0x61, 0x66, 0x20, 0x28, 0x52, 0x53, 0x41, 0x2d, 0x34, 0x30, 0x39, 0x36, 0x20, 0x43, 0x41, 0x29, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x92, 0x7b, 0x79, 0x03, 0x50, 0xe6, 0x88, 0xac, 0xd2, 0x13, 0x9b, 0xed, 0x45, 0x7b, 0x39, 0x0e, 0x11, 0x4b, 0x98, 0x26, 0x1b, 0x44, 0xb2, 0x43, 0x35, 0x35, 0x6a, 0xe0, 0x32, 0x4c, 0x20, 0x44, 0x84, 0x39, 0xaf, 0x37, 0xa9, 0x98, 0xff, 0x27, 0x1a, 0x94, 0xac, 0x12, 0x07, 0x9f, 0x84, 0x18, 0xdf, 0x0f, 0x45, 0x18, 0xd5, 0x00, 0xa8, 0xfe, 0xe2, 0x8f, 0x60, 0xe3, 0xd5, 0x52, 0x98, 0xa2, 0xa3, 0x10, 0x30, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00]; +pub global SYN_P256_LEAF_BY_RSA4096_SHA256: [u8; 32] = [0x8e, 0x08, 0x1c, 0xa7, 0x62, 0x45, 0xaf, 0x97, 0x89, 0xb6, 0x5b, 0xfa, 0xb6, 0x29, 0x00, 0x54, 0xdc, 0xf0, 0x9f, 0xa9, 0x67, 0x9e, 0xea, 0x86, 0x05, 0xf0, 0x78, 0x5a, 0xa0, 0x7c, 0xbd, 0xc3]; +pub global SYN_P256_LEAF_BY_RSA4096_NOT_BEFORE: u64 = 1741064767; +pub global SYN_P256_LEAF_BY_RSA4096_NOT_AFTER: u64 = 2038731072; +pub global SYN_P256_LEAF_BY_RSA4096_SIG: [u8; 512] = [0x4e, 0x2e, 0xb9, 0x51, 0x20, 0x63, 0xcc, 0xce, 0x1c, 0x1e, 0xb3, 0x5f, 0x32, 0xcf, 0x96, 0x1e, 0x4f, 0xe3, 0xeb, 0x5a, 0x61, 0xb0, 0xb7, 0xf3, 0x5f, 0x3c, 0xf2, 0x82, 0xb1, 0xbb, 0xff, 0x11, 0x06, 0x48, 0x21, 0x68, 0xf4, 0x05, 0x9d, 0xdb, 0xc4, 0x2a, 0xef, 0x0a, 0x65, 0x35, 0xfa, 0xc1, 0xfe, 0x33, 0x67, 0x68, 0xde, 0xd8, 0x3e, 0xa8, 0xe3, 0x24, 0x67, 0x89, 0x5c, 0x6e, 0x93, 0x31, 0x77, 0xbf, 0x86, 0xf8, 0xdc, 0x48, 0x88, 0x02, 0x68, 0x4e, 0x2c, 0xca, 0x08, 0x16, 0xb2, 0x29, 0x6e, 0x13, 0xc7, 0x24, 0x9f, 0xb1, 0x3c, 0x8b, 0xce, 0x31, 0x07, 0x61, 0x6a, 0x7e, 0x35, 0xa5, 0x06, 0x86, 0x13, 0x6f, 0x3a, 0x35, 0x61, 0x38, 0x58, 0x75, 0x82, 0x81, 0xbf, 0xd0, 0x58, 0xd2, 0xe1, 0xf8, 0xa4, 0x07, 0xf2, 0x40, 0x66, 0x9d, 0xcb, 0xa5, 0x67, 0x1a, 0x82, 0x4f, 0x6b, 0xc6, 0xb9, 0x0f, 0xba, 0x17, 0x45, 0x08, 0x29, 0xeb, 0xe2, 0x27, 0x19, 0xf6, 0x58, 0xf3, 0x38, 0xa7, 0xac, 0x49, 0x8d, 0xbd, 0xa7, 0xe2, 0x9c, 0xc0, 0x13, 0x42, 0x45, 0xab, 0x21, 0x60, 0x3a, 0x64, 0x53, 0x2f, 0x68, 0x6a, 0x55, 0x50, 0x72, 0x7c, 0xe8, 0xde, 0x95, 0x2a, 0x4d, 0x24, 0x78, 0x8a, 0x8a, 0xd5, 0xdf, 0xdb, 0xfb, 0x7a, 0x2a, 0x36, 0x68, 0x29, 0xea, 0x49, 0x37, 0x6a, 0x2d, 0xfd, 0x26, 0x7d, 0xed, 0xc2, 0x01, 0x70, 0xc4, 0x4a, 0xe0, 0xea, 0xbe, 0x54, 0xa3, 0x18, 0x98, 0x36, 0x36, 0x4a, 0xb5, 0x0f, 0xa1, 0x73, 0xa6, 0x2b, 0x8e, 0x50, 0xc8, 0xc5, 0x10, 0xf3, 0x92, 0x24, 0x30, 0xc1, 0x03, 0x78, 0x5c, 0x8c, 0x0d, 0xb0, 0xdf, 0x50, 0x8a, 0xd5, 0x1d, 0x2a, 0xd6, 0x80, 0x18, 0xe3, 0x1b, 0x27, 0x76, 0x83, 0xdc, 0x8b, 0xf0, 0x76, 0xc3, 0xd2, 0x03, 0x20, 0x84, 0x2b, 0x0b, 0xa4, 0x9f, 0x53, 0xf4, 0x03, 0x47, 0xd0, 0xd8, 0x96, 0x22, 0xdc, 0x77, 0x43, 0xbb, 0x00, 0xc4, 0x4a, 0x5d, 0xd6, 0x58, 0xab, 0x3e, 0x3a, 0xae, 0x56, 0x77, 0x87, 0x56, 0x49, 0xdb, 0x85, 0x17, 0x1e, 0x97, 0x4b, 0x3a, 0x32, 0x75, 0x00, 0x47, 0xf7, 0xaa, 0x65, 0xfd, 0x7e, 0x46, 0xbc, 0x67, 0x81, 0x23, 0xde, 0x2f, 0x2e, 0xa4, 0x6d, 0xf7, 0xdd, 0x00, 0x54, 0x90, 0x82, 0x40, 0x28, 0xd5, 0x49, 0xd3, 0x69, 0xb0, 0x21, 0x86, 0x90, 0x1f, 0x0b, 0x44, 0xde, 0x6d, 0x22, 0x99, 0xe0, 0x75, 0xb0, 0xd8, 0xf7, 0x94, 0xb7, 0xb3, 0xde, 0xbb, 0x2d, 0x3a, 0xc4, 0x7f, 0x1c, 0x25, 0x0d, 0xa2, 0x45, 0xbb, 0xd9, 0x7c, 0x26, 0xf9, 0x1b, 0xe5, 0x8c, 0x57, 0xc0, 0xbf, 0xae, 0x84, 0x8e, 0x9c, 0xef, 0xbb, 0x0c, 0xf1, 0xd4, 0xfb, 0xe8, 0x62, 0x37, 0xf0, 0xe6, 0x35, 0x3b, 0x5c, 0xcb, 0x6d, 0xc3, 0x0e, 0xf4, 0xc2, 0xa6, 0x65, 0x7c, 0xea, 0x78, 0x72, 0x9f, 0xbf, 0x37, 0xba, 0xc7, 0x22, 0x7c, 0x46, 0x50, 0x9d, 0xa8, 0xc3, 0x76, 0xa2, 0x53, 0x72, 0xf9, 0x7b, 0xd8, 0x4d, 0xe0, 0xd1, 0xd0, 0x4f, 0xf6, 0x48, 0xe7, 0x88, 0xfe, 0x61, 0x36, 0x2d, 0xb0, 0x76, 0x36, 0x18, 0x4a, 0xa3, 0x7f, 0x9e, 0xf8, 0x54, 0x15, 0x49, 0x85, 0x7a, 0xed, 0xa4, 0x28, 0xed, 0x1c, 0x56, 0x9c, 0x6a, 0x29, 0xc6, 0x4c, 0x0e, 0x71, 0xb6, 0x4f, 0x37, 0xfc, 0x72, 0xee, 0xe9, 0x46, 0x08, 0xde, 0x4d, 0x9a, 0x0f, 0x5e, 0x5e, 0xab, 0x34, 0x3e, 0x74, 0xd7, 0x31, 0x19, 0x60, 0x9b, 0x40, 0x23, 0x8e, 0xca, 0xec, 0x04, 0x9b, 0xb8, 0x8b, 0x0a, 0xc7, 0x18, 0xdb, 0x55, 0xb0, 0x4f, 0xef, 0x59, 0xe7, 0xfc, 0x5e, 0xb3, 0x85, 0xce, 0xc7, 0x22, 0x45, 0x51, 0x78, 0x9d, 0x07, 0x66, 0xd3, 0xdf]; +// Modulus of the real Adobe leaf in test_vectors::ADOBE_LEAF_TBS. +pub global ADOBE_LEAF_MODULUS: [u8; 256] = [0xab, 0xcf, 0x5d, 0x71, 0xb9, 0x32, 0x36, 0xdd, 0x95, 0xff, 0x4a, 0x8b, 0x5d, 0x20, 0x19, 0xcc, 0xf6, 0xbf, 0xe2, 0x19, 0xa7, 0x02, 0x5e, 0x63, 0x75, 0xe8, 0x4a, 0x13, 0xf8, 0x8e, 0x73, 0x85, 0x38, 0x0b, 0xcb, 0xbe, 0x5f, 0xa3, 0x77, 0x17, 0x77, 0xaa, 0xa0, 0x3a, 0x4a, 0x1f, 0x2e, 0xeb, 0x74, 0x23, 0x65, 0x0a, 0x0f, 0x4a, 0xba, 0x98, 0x68, 0xb8, 0x2c, 0x55, 0x63, 0x3d, 0xe1, 0xf0, 0x45, 0x37, 0x28, 0xd1, 0x8b, 0xf6, 0x6f, 0xee, 0x87, 0x96, 0x80, 0x2e, 0x08, 0x90, 0x25, 0xe4, 0xd8, 0xe4, 0x89, 0x57, 0x43, 0xa4, 0x27, 0x93, 0x97, 0xef, 0x65, 0x30, 0xa8, 0x12, 0x22, 0x58, 0x65, 0x95, 0x31, 0x24, 0xaa, 0xa3, 0x4e, 0xa1, 0xf8, 0x8a, 0x1a, 0xcf, 0x0a, 0x56, 0x60, 0xc4, 0xa6, 0xcd, 0xec, 0x1c, 0xb9, 0x97, 0xb2, 0x88, 0xdc, 0x54, 0xe8, 0xb9, 0x34, 0x9f, 0x21, 0x64, 0x86, 0x95, 0xea, 0x65, 0x59, 0x2b, 0xda, 0xb6, 0x97, 0x7c, 0xe0, 0xbc, 0xd3, 0x2b, 0x0d, 0xa9, 0x71, 0xab, 0x3b, 0xda, 0xc5, 0x19, 0xe0, 0xcc, 0xcc, 0x8e, 0x46, 0xe7, 0x7a, 0x76, 0xa6, 0x7e, 0xeb, 0x94, 0x54, 0xc5, 0x15, 0xc8, 0x25, 0x86, 0xac, 0xe6, 0x1f, 0xf0, 0x91, 0x70, 0x2e, 0xac, 0x3a, 0x0f, 0xdf, 0x50, 0x62, 0x91, 0x30, 0x0d, 0xad, 0x10, 0xfb, 0x53, 0xfe, 0xc8, 0x87, 0xc8, 0x64, 0x6f, 0x05, 0xd2, 0xe3, 0x85, 0x91, 0x4a, 0x2d, 0xae, 0xd1, 0x9a, 0x14, 0x67, 0xe6, 0xd0, 0xbb, 0x4f, 0x2f, 0xc8, 0x61, 0x36, 0x88, 0x0c, 0x59, 0x16, 0x58, 0x1a, 0x93, 0x88, 0x9d, 0x64, 0x4b, 0xc4, 0x8b, 0xf7, 0x99, 0x26, 0x28, 0x92, 0x1d, 0xc5, 0x9c, 0x31, 0xb0, 0xee, 0x39, 0x43, 0x38, 0x77, 0x5c, 0x1f, 0x86, 0x4d, 0xff, 0xb6, 0x9f, 0x2c, 0xfd, 0x09, 0xf5, 0x4d, 0xcb, 0xb1]; +// PS256 (salt 32) by SYN_RSA_LEAF over SHA-256(PS_SIG_STRUCTURE), which embeds PS_CLAIM. +pub global PS_SIG_STRUCTURE_LEN: u32 = 204; +pub global PS_SIG_STRUCTURE: [u8; 204] = [0x84, 0x6a, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x61, 0xed, 0x99, 0xe4, 0x37, 0x4a, 0xb0, 0xb9, 0x92, 0x4c, 0x17, 0x96, 0xe3, 0x44, 0xe3, 0x3d, 0x3a, 0x1d, 0x07, 0x14, 0xcf, 0x74, 0x78, 0xca, 0x2e, 0x6f, 0xd0, 0xd2, 0xf8, 0x25, 0x1d, 0x37, 0x00, 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, 0x3f, 0x46, 0x4d, 0x54, 0x5b, 0x62, 0x69, 0x70, 0x77, 0x7e, 0x85, 0x8c, 0x93, 0x9a, 0xa1, 0xa8, 0xaf, 0xb6, 0xbd, 0xc4, 0xcb, 0xd2, 0xd9, 0xe0, 0xe7, 0xee, 0xf5, 0xfc, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x49, 0x50, 0x57, 0x5e, 0x65, 0x6c, 0x73, 0x00, 0x0d, 0x1a, 0x27, 0x34, 0x41, 0x4e, 0x5b, 0x68, 0x75, 0x82, 0x8f, 0x9c, 0xa9, 0xb6, 0xc3, 0xd0, 0xdd, 0xea, 0xf7, 0x04, 0x11, 0x1e, 0x2b, 0x38, 0x45, 0x52, 0x5f, 0x6c, 0x79, 0x86, 0x93, 0xa0, 0xad, 0xba, 0xc7, 0xd4, 0xe1, 0xee, 0xfb, 0x08, 0x15, 0x22, 0x2f, 0x3c, 0x49, 0x56, 0x63, 0x70, 0x7d, 0x8a, 0x97, 0xa4, 0xb1, 0xbe, 0xcb, 0xd8, 0xe5, 0xf2, 0xff]; +pub global PS_SIG_STRUCTURE_SHA256: [u8; 32] = [0x12, 0x3e, 0x50, 0x6a, 0x3c, 0xc3, 0x6d, 0x5b, 0xca, 0x70, 0xf4, 0xee, 0x53, 0x00, 0x30, 0x1b, 0xef, 0x63, 0x29, 0x49, 0xd7, 0x3e, 0x40, 0xc9, 0x40, 0xc0, 0x44, 0xe8, 0x90, 0x01, 0xf8, 0xb0]; +pub global PS_CLAIM_LEN: u32 = 96; +pub global PS_CLAIM: [u8; 96] = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x61, 0xed, 0x99, 0xe4, 0x37, 0x4a, 0xb0, 0xb9, 0x92, 0x4c, 0x17, 0x96, 0xe3, 0x44, 0xe3, 0x3d, 0x3a, 0x1d, 0x07, 0x14, 0xcf, 0x74, 0x78, 0xca, 0x2e, 0x6f, 0xd0, 0xd2, 0xf8, 0x25, 0x1d, 0x37, 0x00, 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, 0x3f, 0x46, 0x4d, 0x54, 0x5b, 0x62, 0x69, 0x70, 0x77, 0x7e, 0x85, 0x8c, 0x93, 0x9a, 0xa1, 0xa8, 0xaf, 0xb6, 0xbd, 0xc4, 0xcb, 0xd2, 0xd9, 0xe0, 0xe7, 0xee, 0xf5, 0xfc, 0x03, 0x0a, 0x11, 0x18, 0x1f, 0x26, 0x2d, 0x34, 0x3b, 0x42, 0x49, 0x50, 0x57, 0x5e, 0x65, 0x6c, 0x73]; +pub global PS_CLAIM_OFFSET_IN_SIG: u32 = 48; +pub global PS_CLAIM_SHA256: [u8; 32] = [0x53, 0x25, 0xa0, 0xb1, 0x40, 0xe8, 0xd1, 0xde, 0xa4, 0x30, 0x45, 0x61, 0x22, 0xee, 0x57, 0xd7, 0x31, 0xb7, 0xfa, 0x46, 0xcf, 0xcc, 0x71, 0x73, 0x9e, 0x59, 0x20, 0x3e, 0xf8, 0x46, 0x93, 0x7d]; +pub global PS_CONTENT_HASH_OFFSET: u32 = 10; +pub global PS_CONTENT_HASH: [u8; 32] = [0x61, 0xed, 0x99, 0xe4, 0x37, 0x4a, 0xb0, 0xb9, 0x92, 0x4c, 0x17, 0x96, 0xe3, 0x44, 0xe3, 0x3d, 0x3a, 0x1d, 0x07, 0x14, 0xcf, 0x74, 0x78, 0xca, 0x2e, 0x6f, 0xd0, 0xd2, 0xf8, 0x25, 0x1d, 0x37]; +pub global PS_SIG: [u8; 256] = [0x53, 0x32, 0x99, 0x56, 0xb5, 0x33, 0x1f, 0xda, 0xaa, 0xa3, 0xc9, 0xf1, 0x36, 0x1c, 0xca, 0x81, 0x09, 0x96, 0x88, 0x2c, 0xe8, 0x54, 0x0e, 0x31, 0xcf, 0xd9, 0x7f, 0xc9, 0xdd, 0x84, 0x35, 0xb4, 0x1e, 0x94, 0x76, 0x04, 0xdb, 0xa2, 0x36, 0x6f, 0x08, 0x09, 0xa2, 0x4a, 0xc2, 0xdc, 0x16, 0xb7, 0x01, 0x35, 0x93, 0x21, 0x65, 0xac, 0x3f, 0x30, 0x2f, 0x4d, 0x77, 0xa7, 0xac, 0xb0, 0x72, 0x52, 0x23, 0x4c, 0x46, 0xe8, 0x41, 0x82, 0x7e, 0xeb, 0xe2, 0x77, 0x6f, 0x53, 0xd8, 0xca, 0xee, 0xcd, 0x56, 0x70, 0x04, 0x33, 0x0c, 0x46, 0x64, 0x12, 0xa2, 0xc4, 0xec, 0x5a, 0xe1, 0x60, 0x67, 0x7a, 0x05, 0x0c, 0xc7, 0x4e, 0xf7, 0x41, 0xd4, 0x39, 0x03, 0xdb, 0xfb, 0x39, 0x9f, 0x85, 0x6a, 0xec, 0x8a, 0xd8, 0x54, 0x10, 0x6c, 0x27, 0x7d, 0xab, 0xcb, 0x20, 0x4f, 0x5e, 0x85, 0x06, 0x84, 0x2b, 0x9d, 0x2b, 0x7c, 0x80, 0x66, 0xfe, 0x44, 0xd8, 0x26, 0xf9, 0xa5, 0x9f, 0x2a, 0x37, 0x62, 0xb5, 0x5f, 0x71, 0x55, 0x64, 0xfa, 0x68, 0x69, 0xbf, 0x80, 0x0f, 0x54, 0x77, 0x72, 0xd4, 0x0b, 0xa1, 0x29, 0x4e, 0x37, 0xba, 0xae, 0x76, 0x14, 0xba, 0x9d, 0x63, 0xfd, 0x86, 0xd7, 0xd0, 0xcd, 0xa6, 0x7b, 0x9d, 0xd4, 0x52, 0x6e, 0x6c, 0x8c, 0x36, 0x98, 0x10, 0xfd, 0x71, 0x06, 0x0e, 0x22, 0xb7, 0xa5, 0x19, 0x22, 0x1c, 0x6a, 0x35, 0xbc, 0x61, 0xff, 0xd7, 0xa3, 0x61, 0xf5, 0xa5, 0x99, 0x92, 0xd1, 0xec, 0x3a, 0x86, 0xb0, 0x2c, 0x94, 0xa2, 0x08, 0x56, 0x72, 0xab, 0xae, 0xa2, 0x28, 0x6a, 0xca, 0x51, 0x90, 0x14, 0x26, 0x45, 0x72, 0x40, 0xe9, 0x96, 0x41, 0xd7, 0x90, 0xdb, 0x94, 0xb4, 0x63, 0xb4, 0xdf, 0x87, 0x46, 0x5d, 0x12, 0x57, 0x02, 0x4b, 0x20, 0xbb, 0x17, 0x15, 0xbf, 0xa1]; diff --git a/proof_b_ps256_v2/Nargo.toml b/proof_b_ps256_v2/Nargo.toml new file mode 100644 index 0000000..b00cb51 --- /dev/null +++ b/proof_b_ps256_v2/Nargo.toml @@ -0,0 +1,19 @@ +[package] +name = "apertrue_proof_b_ps256_v2" +type = "bin" +authors = ["Apertrue"] +compiler_version = ">=1.0.0" +description = "ProofB PS256 v2: RSA-2048 PSS COSE signature by the leaf key, nullifier over the full modulus" + +[dependencies] +# RSA key hashing shared with ProofA v2 (full-modulus key hash) +cert_binding = { path = "../cert_binding" } +# Shared ProofB v2 helpers (claim embedding, content hash, Merkle, packing) +proof_b_es256_v2_core = { path = "../proof_b_es256_v2_core" } +# RSA verification (zkpassport fork with PSS support) +noir_rsa = { tag = "v0.10.0", git = "https://github.com/zkpassport/noir_rsa" } +bignum = { tag = "v0.9.2", git = "https://github.com/noir-lang/noir-bignum" } +# SHA-256 for hash verification (sig_structure, claim hash) +sha256 = { tag = "v0.3.0", git = "https://github.com/noir-lang/sha256" } +# Poseidon2 for claim hash commitment verification +poseidon = { tag = "v0.1.1", git = "https://github.com/noir-lang/poseidon" } diff --git a/proof_b_ps256_v2/src/main.nr b/proof_b_ps256_v2/src/main.nr new file mode 100644 index 0000000..19ca48a --- /dev/null +++ b/proof_b_ps256_v2/src/main.nr @@ -0,0 +1,362 @@ +/// Apertrue ProofB PS256 v2 - RSA-PSS COSE Signature Verification +/// +/// For C2PA claims signed PS256 (RSASSA-PSS, SHA-256, MGF1-SHA-256) by an +/// RSA-2048 leaf key with e = 65537 (e.g. Adobe). Pairs with ProofA v2 RSA +/// variants (proof_a_rsa_2048_v2, proof_a_rsa_4096_v2), which take the leaf +/// modulus from the CA-signed leaf TBSCertificate and derive the same +/// nullifier. +/// +/// Versus proof_b_ps256 (v1): +/// - The leaf key is the 256-byte big-endian modulus; limbs are derived +/// in-circuit (range-safe), not supplied as free u128 limbs. +/// - The nullifier key hash covers ALL 18 modulus limbs +/// (cert_binding::rsa_key_hash). v1 hashed only the 8 low limbs, which an +/// attacker can match with a 2048-bit modulus they can factor. +/// - cert_not_before / cert_not_after are removed; ProofA v2 checks +/// proof_timestamp against the dates parsed from the signed leaf TBS. +/// +/// This proves: +/// 1. A valid PS256 signature by the leaf key over SHA-256(sig_structure) +/// 2. claim_bytes are embedded in sig_structure at claim_offset_in_sig +/// 3. claim_hash = SHA-256(claim_bytes), and its Poseidon2 packing is public +/// 4. Optional: content_hash appears in the claim at content_hash_offset +/// 5. The intermediate leaf is in the trust list (Merkle membership) +/// 6. nullifier = pedersen_hash([content_hash, rsa_key_hash(leaf_modulus)]) +/// 7. Returns link_commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]) +/// +/// PUBLIC LAYOUT (index: name; one Field each) - same as proof_b_es256_v2 +/// 0 trust_list_root +/// 1 content_hash +/// 2 nullifier pedersen_hash([content_hash, rsa_key_hash(modulus)]) +/// 3 proof_timestamp (range checked to u64 only) +/// 4 claim_hash_commitment Poseidon2(bytes32_to_field_array(claim_hash)) +/// 5 content_hash_offset (0 = content hash not embedded in the claim) +/// Return value: +/// 6 link_commit pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]) +/// Total 7. +/// +/// Buffers: MAX_SIG_STRUCTURE_SIZE 8192 (RSA chains in the protected header +/// are large), MAX_CLAIM_SIZE 2048, as in v1. + +use std::hash::pedersen_hash; +use sha256::sha256_var; +use poseidon::poseidon2::Poseidon2; +use noir_rsa::rsa::verify_sha256_pss; +use noir_rsa::types::RBN2048; +use bignum::params::BigNumParams; +use cert_binding::{be_bytes_to_limbs, rsa_key_hash}; +use proof_b_es256_v2_core::{ + bytes_to_field, bytes32_to_field_array, compute_merkle_root, verify_bytes_embedded, + verify_content_hash_in_claim, MERKLE_TREE_DEPTH, +}; + +/// Maximum size of COSE Sig_structure (CBOR encoded) +global MAX_SIG_STRUCTURE_SIZE: u32 = 8192; + +/// Maximum size of C2PA claim (CBOR encoded) +global MAX_CLAIM_SIZE: u32 = 2048; + +/// RSA-2048 uses 18 limbs of 120 bits +global RSA_NUM_LIMBS: u32 = 18; + +fn main( + // === PUBLIC INPUTS (shared with ProofA) === + trust_list_root: pub Field, + content_hash: pub Field, + nullifier: pub Field, + proof_timestamp: pub Field, + + // === PUBLIC INPUT: Claim Hash Commitment (must match ProofA) === + claim_hash_commitment: pub Field, + + // === PRIVATE: RSA-PSS COSE SIGNATURE === + cose_signature_rsa: [u8; 256], // big-endian signature + leaf_rsa_modulus: [u8; 256], // big-endian modulus (must be 2048 bits) + leaf_rsa_redc_limbs: [u128; RSA_NUM_LIMBS], // Barrett parameter floor(2^4102 / n) + pss_salt_len: u32, // 32 for SHA-256 (RFC 8230); 20 is seen too + + // === PRIVATE: COSE MESSAGE HASH === + cose_message_hash: [u8; 32], + + // === PRIVATE: LINKING WITNESS === + intermediate_leaf: Field, + link_blind: Field, + + // === PRIVATE: MERKLE MEMBERSHIP === + merkle_path: [Field; MERKLE_TREE_DEPTH], + merkle_indices: [Field; MERKLE_TREE_DEPTH], + + // === PRIVATE: SIG_STRUCTURE VERIFICATION === + sig_structure_bytes: [u8; MAX_SIG_STRUCTURE_SIZE], + sig_structure_length: u32, + + // === PRIVATE: CLAIM VERIFICATION === + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + claim_offset_in_sig: u32, + claim_hash: [u8; 32], + + // === PUBLIC: CONTENT HASH BINDING === + content_hash_offset: pub u32, +) -> pub Field { + verify_proof_b_ps256( + trust_list_root, + content_hash, + nullifier, + proof_timestamp, + claim_hash_commitment, + cose_signature_rsa, + leaf_rsa_modulus, + leaf_rsa_redc_limbs, + pss_salt_len, + cose_message_hash, + intermediate_leaf, + link_blind, + merkle_path, + merkle_indices, + sig_structure_bytes, + sig_structure_length, + claim_bytes, + claim_length, + claim_offset_in_sig, + claim_hash, + content_hash_offset, + ) +} + +/// Full ProofB PS256 v2 check, generic over buffer sizes. Returns link_commit. +fn verify_proof_b_ps256( + trust_list_root: Field, + content_hash: Field, + nullifier: Field, + proof_timestamp: Field, + claim_hash_commitment: Field, + cose_signature_rsa: [u8; 256], + leaf_rsa_modulus: [u8; 256], + leaf_rsa_redc_limbs: [u128; RSA_NUM_LIMBS], + pss_salt_len: u32, + cose_message_hash: [u8; 32], + intermediate_leaf: Field, + link_blind: Field, + merkle_path: [Field; MERKLE_TREE_DEPTH], + merkle_indices: [Field; MERKLE_TREE_DEPTH], + sig_structure_bytes: [u8; S], + sig_structure_length: u32, + claim_bytes: [u8; C], + claim_length: u32, + claim_offset_in_sig: u32, + claim_hash: [u8; 32], + content_hash_offset: u32, +) -> Field { + // STEP 0: claim hash commitment (public packing of claim_hash) + let computed_claim_commitment = Poseidon2::hash(bytes32_to_field_array(claim_hash), 2); + assert(computed_claim_commitment == claim_hash_commitment, "Claim hash commitment mismatch"); + + // STEP 1: PS256 COSE signature by the leaf key (e = 65537) + assert(leaf_rsa_modulus[0] >= 0x80, "RSA modulus is not 2048 bits"); + let modulus_limbs: [u128; RSA_NUM_LIMBS] = be_bytes_to_limbs(leaf_rsa_modulus); + let params: BigNumParams<18, 2048> = BigNumParams::new(false, modulus_limbs, leaf_rsa_redc_limbs); + let signature: RBN2048 = RBN2048::from_be_bytes(params, cose_signature_rsa); + let rsa_valid = verify_sha256_pss(cose_message_hash, signature, 65537, pss_salt_len); + assert(rsa_valid, "Invalid RSA COSE signature (PS256)"); + + // STEP 2: the signed hash is SHA-256(sig_structure) + assert(sig_structure_length <= S, "sig_structure_length exceeds buffer"); + let computed_sig_hash = sha256_var(sig_structure_bytes, sig_structure_length); + assert(computed_sig_hash == cose_message_hash, "Sig_structure hash does not match COSE message hash"); + + // STEP 3: claim_bytes embedded in sig_structure + verify_bytes_embedded( + sig_structure_bytes, + sig_structure_length, + claim_bytes, + claim_length, + claim_offset_in_sig, + ); + + // STEP 4: claim_hash = SHA-256(claim_bytes) + assert(claim_length <= C, "claim_length exceeds buffer"); + let computed_claim_hash = sha256_var(claim_bytes, claim_length); + assert(computed_claim_hash == claim_hash, "Claim hash mismatch - claim_bytes integrity violated"); + + // STEP 4b: optional content_hash binding (offset 0 = not embedded) + if content_hash_offset != 0 { + verify_content_hash_in_claim(claim_bytes, content_hash_offset, content_hash); + } + + // STEP 5: intermediate in trust list + let computed_root = compute_merkle_root(intermediate_leaf, merkle_path, merkle_indices); + assert(computed_root == trust_list_root, "Intermediate not in trust list"); + + // STEP 6: link commitment (returned) + let claim_hash_field = bytes_to_field(claim_hash); + let link_commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + + // STEP 7: nullifier from the FULL leaf modulus + let leaf_key_hash = rsa_key_hash::<256, 18>(leaf_rsa_modulus); + let expected_nullifier = pedersen_hash([content_hash, leaf_key_hash]); + assert(nullifier == expected_nullifier, "Invalid nullifier"); + + // STEP 8: proof_timestamp is shared with ProofA v2, which checks it + // against the bound certificate dates. Here it is only range checked. + assert(proof_timestamp as u64 as Field == proof_timestamp, "proof_timestamp exceeds u64"); + + link_commit +} + +// ==================================================================== +// TESTS (synthetic PS256 vector at a small size class) +// ==================================================================== + +mod e2e { + use super::{verify_proof_b_ps256, RSA_NUM_LIMBS}; + use cert_binding::rsa_key_hash; + use cert_binding::rsa_vectors as rv; + use proof_b_es256_v2_core::{bytes_to_field, bytes32_to_field_array, compute_merkle_root, MERKLE_TREE_DEPTH}; + use std::hash::pedersen_hash; + use poseidon::poseidon2::Poseidon2; + + global S: u32 = 512; + global C: u32 = 256; + + pub struct Case { + trust_list_root: Field, + content_hash: Field, + nullifier: Field, + proof_timestamp: Field, + claim_hash_commitment: Field, + sig: [u8; 256], + modulus: [u8; 256], + redc: [u128; RSA_NUM_LIMBS], + salt_len: u32, + msg_hash: [u8; 32], + intermediate_leaf: Field, + link_blind: Field, + path: [Field; MERKLE_TREE_DEPTH], + indices: [Field; MERKLE_TREE_DEPTH], + sig_structure: [u8; S], + sig_structure_len: u32, + claim: [u8; C], + claim_len: u32, + claim_offset: u32, + claim_hash: [u8; 32], + content_hash_offset: u32, + } + + fn pad(a: [u8; M]) -> [u8; B] { + let mut out: [u8; B] = [0; B]; + for i in 0..M { + out[i] = a[i]; + } + out + } + + fn good() -> Case { + let intermediate_leaf = pedersen_hash([7, 8]); + let path: [Field; MERKLE_TREE_DEPTH] = [11, 12, 13, 14, 15, 16, 17, 18]; + let indices: [Field; MERKLE_TREE_DEPTH] = [1, 0, 1, 1, 0, 0, 1, 0]; + let content_hash = bytes_to_field(rv::PS_CONTENT_HASH); + let leaf_hash = rsa_key_hash::<256, 18>(rv::SYN_RSA_LEAF_MODULUS); + Case { + trust_list_root: compute_merkle_root(intermediate_leaf, path, indices), + content_hash, + nullifier: pedersen_hash([content_hash, leaf_hash]), + proof_timestamp: 1761572000, + claim_hash_commitment: Poseidon2::hash(bytes32_to_field_array(rv::PS_CLAIM_SHA256), 2), + sig: rv::PS_SIG, + modulus: rv::SYN_RSA_LEAF_MODULUS, + redc: rv::SYN_RSA_LEAF_REDC, + salt_len: 32, + msg_hash: rv::PS_SIG_STRUCTURE_SHA256, + intermediate_leaf, + link_blind: 424242, + path, + indices, + sig_structure: pad(rv::PS_SIG_STRUCTURE), + sig_structure_len: rv::PS_SIG_STRUCTURE_LEN, + claim: pad(rv::PS_CLAIM), + claim_len: rv::PS_CLAIM_LEN, + claim_offset: rv::PS_CLAIM_OFFSET_IN_SIG, + claim_hash: rv::PS_CLAIM_SHA256, + content_hash_offset: rv::PS_CONTENT_HASH_OFFSET, + } + } + + fn run(c: Case) -> Field { + verify_proof_b_ps256( + c.trust_list_root, + c.content_hash, + c.nullifier, + c.proof_timestamp, + c.claim_hash_commitment, + c.sig, + c.modulus, + c.redc, + c.salt_len, + c.msg_hash, + c.intermediate_leaf, + c.link_blind, + c.path, + c.indices, + c.sig_structure, + c.sig_structure_len, + c.claim, + c.claim_len, + c.claim_offset, + c.claim_hash, + c.content_hash_offset, + ) + } + + #[test] + fn test_valid_vector_returns_link_commit() { + let c = good(); + let expected = pedersen_hash([c.intermediate_leaf, bytes_to_field(c.claim_hash), c.link_blind]); + assert(run(c) == expected); + } + + // noir_rsa's PSS decoding fails an unlabelled internal assertion (e.g. the + // 0xbc trailer) before returning false, so these use plain should_fail. + #[test(should_fail)] + fn test_other_leaf_key_rejected() { + // Another RSA-2048 key did not make this signature. + let mut c = good(); + c.modulus = rv::SYN_OTHER_RSA2048_MODULUS; + c.redc = rv::SYN_OTHER_RSA2048_REDC; + let _ = run(c); + } + + #[test(should_fail_with = "Invalid nullifier")] + fn test_nullifier_from_low_limbs_only_rejected() { + // A nullifier built the v1 way (8 low limbs) does not match. + let mut c = good(); + let l: [u128; 18] = cert_binding::be_bytes_to_limbs(rv::SYN_RSA_LEAF_MODULUS); + let v1_hash = pedersen_hash([ + l[0] as Field, l[1] as Field, l[2] as Field, l[3] as Field, + l[4] as Field, l[5] as Field, l[6] as Field, l[7] as Field, + ]); + c.nullifier = pedersen_hash([c.content_hash, v1_hash]); + let _ = run(c); + } + + #[test(should_fail_with = "Sig_structure hash does not match COSE message hash")] + fn test_tampered_sig_structure_rejected() { + let mut c = good(); + c.sig_structure[100] = c.sig_structure[100] ^ 0x01; + let _ = run(c); + } + + #[test(should_fail)] + fn test_wrong_salt_len_rejected() { + let mut c = good(); + c.salt_len = 20; + let _ = run(c); + } + + #[test(should_fail_with = "Content hash binding failed")] + fn test_wrong_content_hash_rejected() { + let mut c = good(); + c.content_hash = c.content_hash + 1; + let _ = run(c); + } +} From bc9b43b02b62ee5e8262128272a9025640851b6f Mon Sep 17 00:00:00 2001 From: Jamie Newton <33573418+newtsjamie@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:54:57 +0000 Subject: [PATCH 4/7] Add ProofA RSA-2048 v2 with bound P-256 or RSA-2048 leaf key The leaf TBS is hashed (SHA-256) and DER-walked in-circuit, the TBS signature algorithm must be sha256WithRSAEncryption, and the RSA-2048 intermediate's PKCS#1 v1.5 signature is verified over that digest. The leaf key type comes from the SPKI DER; the nullifier uses pedersen_hash([x, y]) for P-256 and the full-modulus key hash for RSA, matching proof_b_es256_v2 and proof_b_ps256_v2. The intermediate modulus and signature are bytes, and intermediate_leaf hashes all 18 limbs. Public layout matches the v2 templates (52 values). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + proof_a_rsa_2048_v2/Nargo.toml | 17 + proof_a_rsa_2048_v2/src/hash_chain.nr | 548 +++++++++++++++++++ proof_a_rsa_2048_v2/src/main.nr | 727 ++++++++++++++++++++++++++ 4 files changed, 1293 insertions(+) create mode 100644 proof_a_rsa_2048_v2/Nargo.toml create mode 100644 proof_a_rsa_2048_v2/src/hash_chain.nr create mode 100644 proof_a_rsa_2048_v2/src/main.nr diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6422323..0f95cfd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,7 @@ jobs: - proof_a_ecdsa_p384_v2 - proof_a_ecdsa_p384_sha384_v2 - proof_a_skip_v2 + - proof_a_rsa_2048_v2 - proof_b_es256_v2_core - proof_b_es256_v2 - proof_b_es256_v2_large diff --git a/proof_a_rsa_2048_v2/Nargo.toml b/proof_a_rsa_2048_v2/Nargo.toml new file mode 100644 index 0000000..33b3612 --- /dev/null +++ b/proof_a_rsa_2048_v2/Nargo.toml @@ -0,0 +1,17 @@ +[package] +name = "apertrue_proof_a_rsa_2048_v2" +type = "bin" +authors = ["Apertrue"] +compiler_version = ">=1.0.0" +description = "ProofA RSA-2048 v2: P-256 or RSA-2048 leaf key and validity bound to the TBS signed by an RSA-2048 intermediate" + +[dependencies] +# Leaf TBSCertificate hashing, DER walk, RSA/P-256 key extraction +cert_binding = { path = "../cert_binding" } +# RSA verification (zkpassport fork) +noir_rsa = { tag = "v0.10.0", git = "https://github.com/zkpassport/noir_rsa" } +bignum = { tag = "v0.9.2", git = "https://github.com/noir-lang/noir-bignum" } +# SHA-256 for hash chain verification +sha256 = { tag = "v0.3.0", git = "https://github.com/noir-lang/sha256" } +# Poseidon for commitment schemes +poseidon = { tag = "v0.1.1", git = "https://github.com/noir-lang/poseidon" } diff --git a/proof_a_rsa_2048_v2/src/hash_chain.nr b/proof_a_rsa_2048_v2/src/hash_chain.nr new file mode 100644 index 0000000..d7fe6d5 --- /dev/null +++ b/proof_a_rsa_2048_v2/src/hash_chain.nr @@ -0,0 +1,548 @@ +/** + * Hash Chain Verification for Trustless Metadata Binding + * + * This module verifies that extracted metadata values (GPS, timestamp) actually + * came from the signed C2PA claim, preventing substitution attacks. + * + * The verification chain: + * 1. COSE Signature -> COSE Payload (which is claim_hash or claim_bytes) + * 2. SHA256(claim_bytes) -> claim_hash (verified via signature) + * 3. claim_bytes contains assertion_hash at known offset + * 4. SHA256(assertion_bytes) == assertion_hash + * 5. assertion_bytes contain the metadata values at known offsets + * + * Without this verification, a malicious client could: + * - Extract real GPS from signed image + * - Replace with fake GPS + * - Generate valid proof with fake location + * + * With hash chain verification, the circuit ensures: + * - The metadata values are cryptographically bound to the signature + * - Substitution of any value invalidates the proof + * + * CONSTRAINT BUDGET: + * - SHA256 in Noir: ~15k constraints per KB hashed + * - Claim bytes: typically 1-5 KB -> 15-75k constraints + * - Assertion bytes: typically 200B-2KB -> 3-30k constraints + * - Total budget: ~100k constraints for hash chain + * + * OPTIMIZATION STRATEGIES: + * 1. Use pre-computed claim_hash when claim is large (skip in-circuit hashing) + * 2. Only verify assertion hash for assertions containing sensitive data + * 3. For small claims/assertions, in-circuit SHA256 is acceptable + */ + +// SHA256 from stdlib - use digest function with generic size parameter + +/// Maximum size of claim bytes we'll hash in-circuit +/// Claims larger than this should use the pre-computed hash approach +/// RESTORED to 2048 for full cryptographic hash chain verification +/// ProofMode claims are ~1299 bytes, so 2048 provides sufficient headroom +pub global MAX_CLAIM_SIZE: u32 = 2048; + +/// Maximum size of EXIF assertion bytes we'll hash in-circuit +/// RESTORED to 1024 for full assertion hash verification +pub global MAX_EXIF_ASSERTION_SIZE: u32 = 1024; + +/// Maximum size of c2pa.actions assertion bytes we'll hash in-circuit +/// Actions assertions contain edit history (c2pa.created, c2pa.edited, etc.) +/// and AI generation indicators (digitalSourceType: trainedAlgorithmicMedia) +/// NOTE: Adobe Photoshop actions assertions can be 1200-1500 bytes, so 2048 provides headroom +pub global MAX_ACTIONS_ASSERTION_SIZE: u32 = 2048; + +/// SHA256 hash output size +pub global HASH_SIZE: u32 = 32; + +/** + * Verify that claim_hash matches SHA256(claim_bytes) + * + * This binds the claim content to the signature. + * The signature verifies over claim_hash, so if this passes, + * we know claim_bytes are authentic. + * + * IMPORTANT: Uses sha256_var to hash only the first claim_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * claim bytes, not the padded version. + * + * @param claim_bytes Raw CBOR claim bytes (padded to MAX_CLAIM_SIZE) + * @param claim_length Actual length of claim bytes + * @param expected_claim_hash Pre-computed SHA256(claim_bytes) - same as signature input + */ +pub fn verify_claim_hash( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32] +) { + // Bounds check: claim_length must not exceed buffer size + assert(claim_length <= MAX_CLAIM_SIZE, "claim_length exceeds MAX_CLAIM_SIZE"); + + // Compute SHA256 of the ACTUAL claim bytes (not padded) + // sha256_var hashes only the first claim_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(claim_bytes, claim_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_claim_hash[i], + "Claim hash verification failed: claim_bytes do not match expected hash" + ); + } +} + +/** + * Extract assertion hash from claim_bytes at a known offset + * + * The claim contains references to assertions with their expected hashes. + * This function extracts the 32-byte hash at the specified offset. + * + * @param claim_bytes Raw CBOR claim bytes + * @param hash_offset Byte offset where assertion hash appears in claim + * @returns The 32-byte assertion hash from the claim + */ +pub fn extract_assertion_hash_from_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + hash_offset: u32 +) -> [u8; 32] { + let mut assertion_hash: [u8; 32] = [0; 32]; + + // Bounds check + assert( + hash_offset + 32 <= MAX_CLAIM_SIZE, + "Assertion hash offset out of bounds" + ); + + // Extract 32 bytes starting at hash_offset + for i in 0..32 { + assertion_hash[i] = claim_bytes[hash_offset + i]; + } + + assertion_hash +} + +/** + * Verify that assertion_hash matches SHA256(assertion_bytes) + * + * This binds the assertion content to the claim. + * Combined with verify_claim_hash, this creates a complete chain: + * Signature -> Claim -> Assertion -> Metadata + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR or JSON, padded) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_assertion_hash( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_EXIF_ASSERTION_SIZE, "assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Extract a u64 timestamp value from CBOR-encoded assertion bytes + * + * CBOR timestamp encoding (simplified): + * - For small values (0-23): single byte 0x00-0x17 + * - For u8: 0x18 + 1 byte + * - For u16: 0x19 + 2 bytes (big-endian) + * - For u32: 0x1a + 4 bytes (big-endian) + * - For u64: 0x1b + 8 bytes (big-endian) + * + * We extract the raw bytes and convert to u64. + * The offset should point to the START of the CBOR value (type byte). + * + * @param assertion_bytes Raw assertion bytes + * @param timestamp_offset Byte offset where timestamp CBOR value starts + * @returns Extracted timestamp as u64 + */ +pub fn extract_timestamp_from_cbor( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + timestamp_offset: u32 +) -> u64 { + let type_byte = assertion_bytes[timestamp_offset]; + + // Check CBOR type - we expect unsigned integer (major type 0) + let major_type = type_byte >> 5; + let additional_info = type_byte & 0x1f; + + // Major type 0 = unsigned integer + assert(major_type == 0, "Expected CBOR unsigned integer for timestamp"); + + let mut timestamp: u64 = 0; + + if additional_info <= 23 { + // Inline value + timestamp = additional_info as u64; + } else if additional_info == 24 { + // u8 follows - need 2 bytes total + assert(timestamp_offset + 2 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u8 timestamp exceeds buffer"); + timestamp = assertion_bytes[timestamp_offset + 1] as u64; + } else if additional_info == 25 { + // u16 follows (big-endian) - need 3 bytes total + assert(timestamp_offset + 3 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u16 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 2] as u64); + } else if additional_info == 26 { + // u32 follows (big-endian) - need 5 bytes total + assert(timestamp_offset + 5 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u32 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 24; + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 2] as u64) << 16); + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 3] as u64) << 8); + timestamp = timestamp + (assertion_bytes[timestamp_offset + 4] as u64); + } else if additional_info == 27 { + // u64 follows (big-endian) - need 9 bytes total + assert(timestamp_offset + 9 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u64 timestamp exceeds buffer"); + for i in 0..8 { + timestamp = timestamp << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 1 + i] as u64); + } + } else { + // additional_info 28-30 are reserved per CBOR RFC 8949, 31 is indefinite-length + assert(false, "Reserved or unsupported CBOR integer encoding for timestamp"); + } + + timestamp +} + +/** + * GPS BINDING SECURITY MODEL + * ========================== + * + * This module does NOT implement byte-level GPS extraction from CBOR assertions. + * This is a deliberate design choice, not a missing feature. + * + * SECURITY RATIONALE: + * ------------------- + * GPS coordinates are cryptographically bound through the hash chain: + * + * 1. verify_assertion_hash() proves: SHA256(assertion_bytes) == hash_in_claim + * 2. verify_claim_hash() proves: SHA256(claim_bytes) == signed_hash + * 3. COSE signature proves: claim was signed by trusted certificate + * + * Therefore, if the assertion bytes pass hash verification, their ENTIRE CONTENT + * is cryptographically bound to the signature. Any modification to the GPS values + * would change the hash and break verification. + * + * WHY NOT PARSE CBOR IN-CIRCUIT? + * ------------------------------ + * C2PA EXIF GPS coordinates are stored as CBOR rational number arrays: + * { "EXIF:GPSLatitude": [{n: 51, d: 1}, {n: 30, d: 1}, {n: 0, d: 1}] } // 51d 30m 0s + * + * Parsing this requires: + * - Variable-length CBOR decoding (~200+ constraints per value) + * - Rational number arithmetic (degree + minute/60 + second/3600) + * - Sign handling from GPSLatitudeRef/GPSLongitudeRef strings + * + * Total cost: ~500-1000 additional constraints for minimal security gain. + * + * The hash chain already guarantees that the client cannot substitute GPS values + * without invalidating the proof. Adding in-circuit parsing would only catch + * bugs in the client extractor, not malicious tampering. + * + * TRUST MODEL: + * ------------ + * - The CIRCUIT trusts that assertion_bytes were correctly passed from the client + * - The HASH CHAIN proves assertion_bytes match what was signed + * - The CLIENT extracts GPS from the verified bytes + * - Any GPS tampering would require finding a hash collision (computationally infeasible) + * + * For applications requiring stronger guarantees, the circuit could be extended + * to parse CBOR at specific known offsets. This is left as a future enhancement. + */ + +// NOTE: verify_gps_binding() has been intentionally removed. +// GPS binding is provided by verify_assertion_hash() in the hash chain. +// See the SECURITY RATIONALE above for details. + +/** + * Combined hash chain verification + * + * Performs the complete verification: + * 1. SHA256(claim_bytes) == expected_claim_hash (signature input) + * 2. Extract assertion_hash from claim at known offset + * 3. SHA256(assertion_bytes) == assertion_hash + * + * If all pass, we know the assertion_bytes are authentic and + * any values extracted from them are cryptographically bound to the signature. + * + * @param claim_bytes Raw claim bytes (padded) + * @param claim_length Actual claim length + * @param expected_claim_hash SHA256 of claim (same as signature message hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes (padded) + * @param assertion_length Actual assertion length + */ +pub fn verify_full_hash_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Step 1: Verify claim hash + verify_claim_hash(claim_bytes, claim_length, expected_claim_hash); + + // Step 2: Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Step 3: Verify assertion hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // At this point, we've proven: + // - claim_bytes hash to the signed value + // - assertion_bytes hash to a reference in the signed claim + // - Therefore, assertion_bytes are authentic + // - Any values in assertion_bytes are cryptographically bound + + // Silence unused warnings + let _ = claim_length; + let _ = assertion_length; +} + +/** + * Verify timestamp is bound to assertion via hash chain + * + * Combines hash chain verification with timestamp extraction. + * Proves that exact_timestamp actually came from the signed assertion. + * + * @param claim_bytes Raw claim bytes + * @param claim_length Actual claim length + * @param expected_claim_hash Expected claim hash (signature input) + * @param assertion_hash_offset Offset of assertion hash in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + * @param timestamp_offset Offset of timestamp in assertion + * @param expected_timestamp The timestamp value the circuit is using + */ +pub fn verify_timestamp_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + timestamp_offset: u32, + expected_timestamp: u64 +) { + // First verify the hash chain + verify_full_hash_chain( + claim_bytes, + claim_length, + expected_claim_hash, + assertion_hash_offset, + assertion_bytes, + assertion_length + ); + + // Then extract and verify the timestamp + let extracted_timestamp = extract_timestamp_from_cbor(assertion_bytes, timestamp_offset); + + assert( + extracted_timestamp == expected_timestamp, + "Timestamp binding failed: extracted timestamp does not match expected value" + ); +} + +/** + * Verify content hash exists in claim at specified offset + * + * SECURITY: This binds the public content_hash to the signed claim. + * Without this verification, a malicious client could substitute + * a different image's content_hash while keeping the valid signature. + * + * @param claim_bytes Raw claim bytes (CBOR encoded) + * @param content_hash_offset Byte offset where content hash appears in claim + * @param expected_content_hash The content hash (Field) to verify + */ +pub fn verify_content_hash_in_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + // Bounds check + assert( + content_hash_offset + 32 <= MAX_CLAIM_SIZE, + "Content hash offset out of bounds" + ); + + // Extract 32 bytes from claim at offset and convert to Field + let mut extracted_hash: Field = 0; + for i in 0..32 { + extracted_hash = extracted_hash * 256 + claim_bytes[content_hash_offset + i] as Field; + } + + // Verify the extracted content hash matches the public input + assert( + extracted_hash == expected_content_hash, + "Content hash binding failed: public content_hash does not match value in signed claim" + ); +} + +/** + * Verify assertion hash chain (without redundant claim hash check) + * + * Use this when claim_hash has already been verified separately. + * Verifies: SHA256(assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + */ +pub fn verify_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // Silence unused warning + let _ = assertion_length; +} + +/** + * Verify actions assertion hash matches SHA256(actions_assertion_bytes) + * + * This is the same as verify_assertion_hash but for the larger actions buffer. + * Actions assertions (c2pa.actions.v2) can be up to 2048 bytes (Adobe Photoshop). + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR, padded to MAX_ACTIONS_ASSERTION_SIZE) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_actions_assertion_hash( + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_ACTIONS_ASSERTION_SIZE, "actions_assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Actions assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Verify actions assertion hash chain (without redundant claim hash check) + * + * Use this for c2pa.actions.v2 assertions which can be up to 2048 bytes. + * Verifies: SHA256(actions_assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw actions assertion bytes (up to 2048 bytes) + * @param assertion_length Actual assertion length + */ +pub fn verify_actions_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_actions_assertion_hash(assertion_bytes, assertion_length, assertion_hash); +} + +// Tests +#[test] +fn test_content_hash_binding() { + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a known content hash at offset 100 + // Content hash as bytes: 0x0000...0001 (just 1 for simplicity) + claim_bytes[131] = 1; // Last byte = 1 + + // Expected field value is 1 + let expected_hash: Field = 1; + + // This should pass + verify_content_hash_in_claim(claim_bytes, 100, expected_hash); +} + +#[test] +fn test_extract_assertion_hash() { + // Create test claim bytes with a known hash at offset 10 + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a test hash at offset 10 + let test_hash: [u8; 32] = [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 + ]; + + for i in 0..32 { + claim_bytes[10 + i] = test_hash[i]; + } + + let extracted = extract_assertion_hash_from_claim(claim_bytes, 10); + + for i in 0..32 { + assert(extracted[i] == test_hash[i]); + } +} + +#[test] +fn test_extract_cbor_timestamp_inline() { + // Test inline value (0-23) + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x17; // Inline value 23 + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 23); +} + +#[test] +fn test_extract_cbor_timestamp_u32() { + // Test u32 value + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x1a; // u32 follows + // Value: 1700000000 (0x6553F100) - a Unix timestamp + assertion_bytes[1] = 0x65; + assertion_bytes[2] = 0x53; + assertion_bytes[3] = 0xF1; + assertion_bytes[4] = 0x00; + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 1700000000); +} diff --git a/proof_a_rsa_2048_v2/src/main.nr b/proof_a_rsa_2048_v2/src/main.nr new file mode 100644 index 0000000..0cbad2d --- /dev/null +++ b/proof_a_rsa_2048_v2/src/main.nr @@ -0,0 +1,727 @@ +/// Apertrue ProofA RSA-2048 v2 - Certificate Chain Verification +/// +/// For a leaf certificate issued by an RSA-2048 intermediate that signs with +/// sha256WithRSAEncryption (PKCS#1 v1.5, e = 65537). The leaf key may be +/// uncompressed P-256 (e.g. Truepic, ES256 claims; pair with proof_b_es256_v2*) +/// or RSA-2048/65537 (e.g. Adobe, PS256 claims; pair with proof_b_ps256_v2). +/// The key type is read from the leaf SPKI DER, not chosen by the prover. +/// +/// v2 binds the leaf key and validity dates to the CA-signed certificate: the +/// full leaf TBSCertificate is a private input, hashed with SHA-256 and +/// DER-walked from offset 0 (cert_binding::bind_leaf_cert_rsa_signed), the TBS +/// signature algorithm must be sha256WithRSAEncryption, and the intermediate's +/// RSA signature is verified over that digest. +/// +/// Versus proof_a_rsa_2048 (v1): +/// - TBS hash, leaf key and dates are no longer free inputs. +/// - The intermediate modulus and the signature are big-endian bytes; limbs +/// are derived in-circuit (range-safe). +/// - intermediate_leaf = cert_binding::rsa_key_hash over ALL 18 modulus limbs. +/// v1 hashed only the 8 low limbs, so an attacker could pick a modulus they +/// can factor with the same low 960 bits and sign any TBS. The trust-list +/// leaf for RSA intermediates must be recomputed this way. +/// - Leaf key hash: P-256 = pedersen_hash([x, y]); RSA = rsa_key_hash over +/// all 18 limbs (v1: 8 low limbs). +/// +/// This circuit proves: +/// 1. The intermediate CA signed (RSA-2048, SHA-256) the leaf TBSCertificate +/// 2. The intermediate CA is in the Oracle's promoted trust list (Merkle membership) +/// 3. The nullifier is derived from the leaf key found in that TBSCertificate +/// 4. proof_timestamp lies within that certificate's validity (dates private) +/// 5. Time range proof (graduated time disclosure) +/// 6. Location range proof (privacy circles) +/// 7. Hash chain verification (claim and assertion integrity) +/// 8. Poseidon commitments for optional future reveal +/// +/// Supported leaf: TBS <= 1280 B. Claim/assertion size classes follow v1 +/// proof_a_rsa_2048 (claim 2048, exif 1024, actions 2048; Adobe actions +/// assertions are 1200-1500 bytes). +/// +/// PUBLIC LAYOUT (index: name; one Field each unless noted) +/// 0 trust_list_root +/// 1 content_hash +/// 2 nullifier pedersen_hash([content_hash, leaf_key_hash]) +/// 3 proof_timestamp +/// 4 time_min +/// 5 time_max +/// 6 edit_time_min +/// 7 edit_time_max +/// 8 center_lat_scaled +/// 9 center_lon_scaled +/// 10 location_flags +/// 11 radius_squared_scaled +/// 12 claim_hash_commitment +/// 13 content_hash_offset +/// 14 skip_content_hash_binding +/// 15 skip_assertion_hash_verification +/// Return values: +/// 16 link_commit pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]) +/// 17 location_commitment +/// 18 time_commitment +/// 19 edit_time_commitment +/// 20..51 actions_assertion_hash (32 x u8) +/// Total 52. Versus v1: cert_not_before (4), cert_not_after (5) and +/// tbs_hash_commitment (14) are removed; every later index shifts down. +/// +/// Shared with ProofB v2 (must be equal across the pair): trust_list_root, +/// content_hash, nullifier, proof_timestamp, claim_hash_commitment, +/// content_hash_offset, link_commit. + +use bignum::params::BigNumParams; +use noir_rsa::rsa::verify_sha256_pkcs1v15; +use std::hash::pedersen_hash; +use dep::poseidon::poseidon2::Poseidon2; +use dep::cert_binding::{bind_leaf_cert_rsa_signed, be_bytes_to_limbs, rsa_key_hash, LeafCertAnyKey}; + +mod hash_chain; + +use hash_chain::{ + MAX_CLAIM_SIZE, + MAX_EXIF_ASSERTION_SIZE, + MAX_ACTIONS_ASSERTION_SIZE, + verify_claim_hash, + verify_content_hash_in_claim, + verify_assertion_chain, + verify_actions_assertion_chain, +}; + +/// Maximum leaf TBSCertificate size (DER bytes) +global MAX_TBS_SIZE: u32 = 1280; + +/// RSA-2048 uses 18 limbs of 120 bits +global RSA_NUM_LIMBS: u32 = 18; + +/// ProofA RSA-2048 v2 main entry point +fn main( + // === PUBLIC INPUTS (shared with ProofB) === + trust_list_root: pub Field, + content_hash: pub Field, + nullifier: pub Field, + proof_timestamp: pub Field, + + // === PUBLIC INPUTS: TIME RANGE BOUNDS (for graduated time disclosure) === + time_min: pub Field, + time_max: pub Field, + + // === PUBLIC INPUTS: EDIT TIME RANGE BOUNDS (for edited images) === + // When a photo is edited (e.g., Leica capture -> Lightroom export), the capture + // and edit timestamps differ. These bounds constrain the edit/signing timestamp. + // Set to 0 when no edit occurred (direct camera capture). + edit_time_min: pub Field, // Minimum edit timestamp bound (0 if no edit) + edit_time_max: pub Field, // Maximum edit timestamp bound (0 if no edit) + + // === PUBLIC INPUTS: LOCATION PRIVACY CIRCLE (for graduated location disclosure) === + center_lat_scaled: pub Field, + center_lon_scaled: pub Field, + location_flags: pub u8, // bit 0 = lat negative (South), bit 1 = lon negative (West) + radius_squared_scaled: pub Field, + + // === PUBLIC INPUT: Claim Hash Commitment (packed from 32 bytes to 1 Field) === + // This is Poseidon2(bytes32_to_field_array(claim_hash)). Saves 31 public input fields. + claim_hash_commitment: pub Field, + + // === PUBLIC INPUT: Content Hash Offset (for content binding) === + content_hash_offset: pub u32, + + // === PRIVATE: LEAF TBSCertificate (DER, zero padded past tbs_len) === + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + + // === PRIVATE: CLAIM HASH BYTES (unpacked from commitment) === + claim_hash: [u8; 32], + + // === PRIVATE: SKIP FLAGS === + skip_content_hash_binding: pub u8, + skip_assertion_hash_verification: pub u8, + + // === PRIVATE: RSA-2048 CERTIFICATE SIGNATURE & KEY (big-endian bytes) === + cert_signature_rsa: [u8; 256], + intermediate_rsa_modulus: [u8; 256], + intermediate_rsa_redc_limbs: [u128; RSA_NUM_LIMBS], // floor(2^(2*2048+6) / n) + + // === PRIVATE: LINKING WITNESS === + intermediate_leaf: Field, + link_blind: Field, + + // === PRIVATE: MERKLE MEMBERSHIP (trust list verification) === + merkle_path: [Field; 8], + merkle_indices: [Field; 8], + + // === PRIVATE: EXACT TIMESTAMP (for time range proof) === + exact_timestamp: Field, + + // === PRIVATE: EXACT GPS LOCATION (for location range proof) === + exact_lat_scaled: Field, + exact_lon_scaled: Field, + exact_lat_is_negative: u8, + exact_lon_is_negative: u8, + + // === PRIVATE: HASH CHAIN DATA === + enable_hash_chain_verification: u8, + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + exif_assertion_hash_offset: u32, + exif_assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + exif_assertion_length: u32, + + // === PRIVATE: ACTIONS ASSERTION === + actions_assertion_hash_offset: u32, + actions_assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + actions_assertion_length: u32, + + // === PRIVATE: COMMITMENT SALTS === + location_salt: Field, + time_salt: Field, + + // === PRIVATE: EDIT TIMESTAMP & SALT (for separate edit time commitment) === + exact_edit_timestamp: Field, // Edit/signing timestamp (0 if no edit) + edit_time_salt: Field // Salt for edit time commitment +) -> pub (Field, Field, Field, Field, [u8; 32]) { // Returns (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) + // ================================================================ + // STEP 0: Verify claim hash commitment packing + // ================================================================ + let computed_claim_commitment = Poseidon2::hash(bytes32_to_field_array(claim_hash), 2); + assert(computed_claim_commitment == claim_hash_commitment, "Claim hash commitment mismatch"); + + // ================================================================ + // STEP 1: Hash + DER-walk the leaf TBS; intermediate signs that hash + // ================================================================ + let leaf = verify_leaf_certificate( + tbs_certificate, + tbs_len, + cert_signature_rsa, + intermediate_rsa_modulus, + intermediate_rsa_redc_limbs + ); + + // ================================================================ + // STEP 2: Derive Leaf Key Hash (key taken from the signed TBS) + // ================================================================ + // P-256: pedersen_hash([x, y]); RSA-2048: rsa_key_hash (18 limbs) + let computed_leaf_key_hash = leaf.key_hash; + + // ================================================================ + // STEP 3: Verify Nullifier Derivation + // ================================================================ + let expected_nullifier = pedersen_hash([content_hash, computed_leaf_key_hash]); + assert(nullifier == expected_nullifier, "Invalid nullifier (leaf key binding failed)"); + + // ================================================================ + // STEP 4: Compute Link Commitment (returned as output) + // ================================================================ + let claim_hash_field = bytes_to_field(claim_hash); + let link_commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + + // ================================================================ + // STEP 4b: Verify Intermediate Leaf Formulation + // ================================================================ + let computed_intermediate_hash = rsa_key_hash::<256, 18>(intermediate_rsa_modulus); + + assert( + intermediate_leaf == computed_intermediate_hash, + "Intermediate Leaf witnessing mismatch (Self-Signing Attack prevention)" + ); + + // ================================================================ + // STEP 4c: Merkle Membership (Trust List Verification) + // ================================================================ + let computed_root = compute_merkle_root(intermediate_leaf, merkle_path, merkle_indices); + assert(computed_root == trust_list_root, "Intermediate CA not in trust list"); + + // ================================================================ + // STEP 5: Certificate Validity (Time) + // ================================================================ + // Dates come from the signed TBS and stay private. + assert(proof_timestamp as u64 as Field == proof_timestamp, "proof_timestamp exceeds u64"); + let ts = proof_timestamp as u64; + let not_before = leaf.not_before; + let not_after = leaf.not_after; + assert(ts >= not_before, "Certificate not yet valid at proof time"); + assert(ts <= not_after, "Certificate expired at proof time"); + + // ================================================================ + // STEP 6: Time Range Proof (Graduated Time Disclosure) + // ================================================================ + assert(exact_timestamp as u64 as Field == exact_timestamp, "exact_timestamp exceeds u64"); + assert(time_min as u64 as Field == time_min, "time_min exceeds u64"); + assert(time_max as u64 as Field == time_max, "time_max exceeds u64"); + let exact_ts = exact_timestamp as u64; + let min_ts = time_min as u64; + let max_ts = time_max as u64; + + assert(exact_ts >= min_ts, "Exact timestamp is before disclosed time_min"); + assert(exact_ts <= max_ts, "Exact timestamp is after disclosed time_max"); + + // ================================================================ + // STEP 6b: Edit Time Range Proof (0 = no edit, skip) + // ================================================================ + // When a photo is edited (capture -> export), exact_edit_timestamp is the + // signing/export time. For direct camera captures, it's 0 (sentinel). + if exact_edit_timestamp != 0 { + assert(exact_edit_timestamp as u64 as Field == exact_edit_timestamp, "exact_edit_timestamp exceeds u64"); + assert(edit_time_min as u64 as Field == edit_time_min, "edit_time_min exceeds u64"); + assert(edit_time_max as u64 as Field == edit_time_max, "edit_time_max exceeds u64"); + let edit_ts = exact_edit_timestamp as u64; + let edit_min = edit_time_min as u64; + let edit_max = edit_time_max as u64; + assert(edit_ts >= edit_min, "Edit timestamp before edit_time_min"); + assert(edit_ts <= edit_max, "Edit timestamp after edit_time_max"); + } else { + assert(edit_time_min == 0, "edit_time_min must be 0 when no edit"); + assert(edit_time_max == 0, "edit_time_max must be 0 when no edit"); + } + + // ================================================================ + // STEP 7: Location Range Proof (Graduated Location Disclosure) + // ================================================================ + // Unpack location_flags: bit 0 = lat negative, bit 1 = lon negative + // Reject if unused high bits (2-7) are set - prevents flag stuffing + assert(location_flags <= 3, "location_flags has invalid high bits set (must be 0-3)"); + let center_lat_is_negative = location_flags & 1; + let center_lon_is_negative = (location_flags >> 1) & 1; + + assert(exact_lat_is_negative <= 1, "exact_lat_is_negative must be 0 or 1"); + assert(exact_lon_is_negative <= 1, "exact_lon_is_negative must be 0 or 1"); + assert(skip_content_hash_binding <= 1, "skip_content_hash_binding must be 0 or 1"); + assert(skip_assertion_hash_verification <= 1, "skip_assertion_hash_verification must be 0 or 1"); + + assert(exact_lat_scaled as u64 as Field == exact_lat_scaled, "exact_lat_scaled exceeds u64"); + assert(center_lat_scaled as u64 as Field == center_lat_scaled, "center_lat_scaled exceeds u64"); + assert(exact_lon_scaled as u64 as Field == exact_lon_scaled, "exact_lon_scaled exceeds u64"); + assert(center_lon_scaled as u64 as Field == center_lon_scaled, "center_lon_scaled exceeds u64"); + + { + let lat_same_sign = (exact_lat_is_negative == center_lat_is_negative); + let d_lat = if lat_same_sign { + if exact_lat_scaled as u64 > center_lat_scaled as u64 { + exact_lat_scaled - center_lat_scaled + } else { + center_lat_scaled - exact_lat_scaled + } + } else { + exact_lat_scaled + center_lat_scaled + }; + + let lon_same_sign = (exact_lon_is_negative == center_lon_is_negative); + let d_lon = if lon_same_sign { + if exact_lon_scaled as u64 > center_lon_scaled as u64 { + exact_lon_scaled - center_lon_scaled + } else { + center_lon_scaled - exact_lon_scaled + } + } else { + exact_lon_scaled + center_lon_scaled + }; + + // NOTE: Euclidean distance in coordinate space. At high latitudes, + // 1 deg lon < 1 deg lat in real-world distance, so this circle is elliptical. + // The client-side radius computation (metersToScaledRadius) compensates + // by using the longitude conversion at the user's latitude, ensuring the + // privacy circle covers at least the requested radius in ALL directions. + let distance_squared = d_lat * d_lat + d_lon * d_lon; + assert(distance_squared as u64 as Field == distance_squared, "distance_squared exceeds u64"); + assert(radius_squared_scaled as u64 as Field == radius_squared_scaled, "radius_squared_scaled exceeds u64"); + + assert( + distance_squared as u64 <= radius_squared_scaled as u64, + "Exact GPS location is outside disclosed privacy circle" + ); + } + + // ================================================================ + // STEP 8: Hash Chain Verification (Trustless Metadata Binding) + // ================================================================ + assert( + enable_hash_chain_verification == 1, + "Hash chain verification must be enabled" + ); + + // Step 8a: Verify claim_hash = SHA256(claim_bytes) + verify_claim_hash(claim_bytes, claim_length, claim_hash); + + // Step 8b: Verify content_hash exists in claim_bytes + if skip_content_hash_binding == 0 { + verify_content_hash_binding(claim_bytes, content_hash_offset, content_hash); + } + + // Step 8c: Verify assertion hash chain + if skip_assertion_hash_verification == 0 { + verify_assertion_chain( + claim_bytes, + exif_assertion_hash_offset, + exif_assertion_bytes, + exif_assertion_length + ); + } + + // Step 8d: Verify actions assertion hash chain (optional) + let actions_assertion_hash: [u8; 32] = if actions_assertion_hash_offset > 0 { + verify_actions_assertion_chain( + claim_bytes, + actions_assertion_hash_offset, + actions_assertion_bytes, + actions_assertion_length + ); + let hash_result: [u8; 32] = dep::sha256::sha256_var( + actions_assertion_bytes, + actions_assertion_length as u32 + ); + hash_result + } else { + [0u8; 32] + }; + + // ================================================================ + // STEP 9: Compute Poseidon Commitments (Optional Future Reveal) + // ================================================================ + let lat_sign_field = exact_lat_is_negative as Field; + let lon_sign_field = exact_lon_is_negative as Field; + + let location_commitment = Poseidon2::hash( + [exact_lat_scaled, exact_lon_scaled, lat_sign_field, lon_sign_field, location_salt], + 5 + ); + + let time_commitment = Poseidon2::hash( + [exact_timestamp, time_salt], + 2 + ); + + // Edit time commitment: Poseidon2([edit_timestamp, salt]) or 0 sentinel + // Poseidon2 never outputs 0 for valid inputs, so 0 is safe as "no edit" sentinel + let edit_time_commitment = if exact_edit_timestamp == 0 { + 0 // Sentinel: no edit happened + } else { + Poseidon2::hash([exact_edit_timestamp, edit_time_salt], 2) + }; + + // Return public outputs + (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) +} + +/// Hash and DER-walk the leaf TBSCertificate (sha256WithRSAEncryption), +/// then check that the intermediate's RSA-2048 PKCS#1 v1.5 signature covers +/// exactly that SHA-256. +fn verify_leaf_certificate( + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + sig: [u8; 256], + intermediate_modulus: [u8; 256], + intermediate_redc: [u128; RSA_NUM_LIMBS] +) -> LeafCertAnyKey { + let leaf = bind_leaf_cert_rsa_signed(tbs_certificate, tbs_len); + assert(intermediate_modulus[0] >= 0x80, "RSA intermediate modulus is not 2048 bits"); + let limbs: [u128; RSA_NUM_LIMBS] = be_bytes_to_limbs(intermediate_modulus); + let params: BigNumParams = BigNumParams::new(false, limbs, intermediate_redc); + let signature = bignum::RuntimeBigNum::from_be_bytes(params, sig); + let valid = verify_sha256_pkcs1v15(leaf.sha256, signature, 65537); + assert(valid, "RSA-2048 certificate verification failed"); + leaf +} + +/// Convert 32 bytes to Field (big-endian) +fn bytes_to_field(bytes: [u8; 32]) -> Field { + let mut result: Field = 0; + for i in 0..32 { + result = result * 256 + bytes[i] as Field; + } + result +} + +/// Convert 32 bytes to 2 Field elements for Poseidon2 hashing +/// Splits into two 16-byte (128-bit) chunks that fit within the BN254 field +fn bytes32_to_field_array(bytes: [u8; 32]) -> [Field; 2] { + // First 16 bytes -> Field 0 + let mut f0: Field = 0; + for i in 0..16 { + f0 = f0 * 256 + bytes[i] as Field; + } + // Last 16 bytes -> Field 1 + let mut f1: Field = 0; + for i in 16..32 { + f1 = f1 * 256 + bytes[i] as Field; + } + [f0, f1] +} + +/// Verify content hash exists in claim at offset +fn verify_content_hash_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + verify_content_hash_in_claim(claim_bytes, content_hash_offset, expected_content_hash); +} + +/// Compute Merkle root from leaf and proof +fn compute_merkle_root( + leaf: Field, + path: [Field; 8], + indices: [Field; 8] +) -> Field { + let mut current = leaf; + + for i in 0..8 { + assert((indices[i] == 0) | (indices[i] == 1), "Merkle index must be 0 or 1"); + let path_element = path[i]; + let is_right = indices[i]; + let left = if is_right == 0 { current } else { path_element }; + let right = if is_right == 0 { path_element } else { current }; + current = pedersen_hash([left, right]); + } + + current +} + +// ==================================================================== +// TESTS +// ==================================================================== + +#[test] +fn test_merkle_root_computation() { + let leaf: Field = 12345; + let path: [Field; 8] = [0; 8]; + let indices: [Field; 8] = [0; 8]; + + let root = compute_merkle_root(leaf, path, indices); + assert(root != leaf, "Merkle root should not equal leaf"); + + let root2 = compute_merkle_root(leaf, path, indices); + assert(root == root2, "Merkle root should be deterministic"); +} + +#[test] +fn test_merkle_different_leaves() { + let path: [Field; 8] = [0; 8]; + let indices: [Field; 8] = [0; 8]; + + let root1 = compute_merkle_root(111, path, indices); + let root2 = compute_merkle_root(222, path, indices); + + assert(root1 != root2, "Different leaves should produce different roots"); +} + +#[test] +fn test_time_range_exact_bounds() { + let exact: u64 = 1000; + let min: u64 = 1000; + let max: u64 = 2000; + + assert(exact >= min, "Timestamp at min bound should pass"); + assert(exact <= max, "Timestamp within range should pass"); +} + +#[test] +fn test_location_same_point() { + let exact_lat: Field = 510000000; + let exact_lon: Field = 100000000; + let center_lat: Field = 510000000; + let center_lon: Field = 100000000; + + let d_lat = if exact_lat as u64 > center_lat as u64 { + exact_lat - center_lat + } else { + center_lat - exact_lat + }; + + let d_lon = if exact_lon as u64 > center_lon as u64 { + exact_lon - center_lon + } else { + center_lon - exact_lon + }; + + let distance_squared = d_lat * d_lat + d_lon * d_lon; + assert(distance_squared == 0, "Same point should have zero distance"); +} + +#[test] +fn test_bytes_to_field() { + let mut bytes: [u8; 32] = [0; 32]; + bytes[31] = 1; + let field = bytes_to_field(bytes); + assert(field == 1); + + bytes[31] = 255; + let field2 = bytes_to_field(bytes); + assert(field2 == 255); +} + +#[test] +fn test_nullifier_derivation_ecdsa() { + let content_hash: Field = 111; + let leaf_key_hash: Field = 222; + let nullifier = pedersen_hash([content_hash, leaf_key_hash]); + + let different_content: Field = 333; + let different_nullifier = pedersen_hash([different_content, leaf_key_hash]); + assert(nullifier != different_nullifier); +} + +#[test] +fn test_link_commitment_with_claim_hash() { + let intermediate_leaf: Field = 12345; + let claim_hash_field: Field = 99999; + let link_blind: Field = 67890; + + let commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + let commit2 = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + assert(commit == commit2); + + let different_claim: Field = 11111; + let commit3 = pedersen_hash([intermediate_leaf, different_claim, link_blind]); + assert(commit != commit3); +} + +// ==================================================================== +// CERTIFICATE TESTS (synthetic chains: RSA-2048 CA, sha256WithRSAEncryption) +// ==================================================================== + +mod cert_tests { + use super::{verify_leaf_certificate, MAX_TBS_SIZE}; + use dep::cert_binding::rsa_vectors as rv; + use dep::cert_binding::test_vectors as tv; + use dep::cert_binding::{bind_leaf_cert_rsa_signed, p256_key_hash, rsa_key_hash}; + + fn pad(a: [u8; M]) -> [u8; MAX_TBS_SIZE] { + let mut out: [u8; MAX_TBS_SIZE] = [0; MAX_TBS_SIZE]; + for i in 0..M { + out[i] = a[i]; + } + out + } + + #[test] + fn test_p256_leaf_verifies_and_binds_key() { + let leaf = verify_leaf_certificate( + pad(rv::SYN_P256_LEAF_BY_RSA2048_TBS), + rv::SYN_P256_LEAF_BY_RSA2048_TBS_LEN, + rv::SYN_P256_LEAF_BY_RSA2048_SIG, + rv::SYN_RSA2048_CA_MODULUS, + rv::SYN_RSA2048_CA_REDC, + ); + assert(leaf.key_type == 0); + assert(leaf.key_hash == p256_key_hash(rv::SYN_EC_LEAF_PUB_X, rv::SYN_EC_LEAF_PUB_Y)); + assert(leaf.not_before == rv::SYN_P256_LEAF_BY_RSA2048_NOT_BEFORE); + assert(leaf.not_after == rv::SYN_P256_LEAF_BY_RSA2048_NOT_AFTER); + } + + // noir_rsa's PKCS#1 v1.5 check fails unlabelled assertions rather than + // returning false, so the negatives use plain should_fail. Each tampered + // TBS has a positive twin showing it still parses (DER walk, algorithm and + // key checks pass), so the failure is the CA signature check. + + fn key_swapped() -> [u8; MAX_TBS_SIZE] { + let mut t = pad(rv::SYN_P256_LEAF_BY_RSA2048_TBS); + let mut off: u32 = 0; + for i in 0..400 { + if (off == 0) & (t[i] == 0x30) & (t[i + 1] == 0x59) & (t[i + 2] == 0x30) & (t[i + 3] == 0x13) { + off = i; + } + } + assert(off != 0); + for i in 0..32 { + t[off + 27 + i] = tv::LEICA_LEAF_PUB_X[i]; + t[off + 59 + i] = tv::LEICA_LEAF_PUB_Y[i]; + } + t + } + + #[test] + fn test_key_swapped_tbs_parses_to_other_key() { + let c = bind_leaf_cert_rsa_signed(key_swapped(), rv::SYN_P256_LEAF_BY_RSA2048_TBS_LEN); + assert(c.key_hash == p256_key_hash(tv::LEICA_LEAF_PUB_X, tv::LEICA_LEAF_PUB_Y)); + } + + #[test(should_fail)] + fn test_substituted_leaf_key_rejected() { + // Genuine CA signature, another P-256 key in the SPKI. + let _ = verify_leaf_certificate(key_swapped(), rv::SYN_P256_LEAF_BY_RSA2048_TBS_LEN, rv::SYN_P256_LEAF_BY_RSA2048_SIG, rv::SYN_RSA2048_CA_MODULUS, rv::SYN_RSA2048_CA_REDC); + } + + fn date_pushed() -> [u8; MAX_TBS_SIZE] { + // Extend notAfter by a decade (UTCTime "34" -> "44"). + let mut t = pad(rv::SYN_P256_LEAF_BY_RSA2048_TBS); + let mut first: u32 = 0; + let mut second: u32 = 0; + for i in 0..300 { + if (t[i] == 0x17) & (t[i + 1] == 0x0d) { + if first == 0 { + first = i; + } else if second == 0 { + second = i; + } + } + } + assert(second != 0); + t[second + 2] = 0x34; + t + } + + #[test] + fn test_date_pushed_tbs_parses_to_later_date() { + let c = bind_leaf_cert_rsa_signed(date_pushed(), rv::SYN_P256_LEAF_BY_RSA2048_TBS_LEN); + assert(c.not_after > rv::SYN_P256_LEAF_BY_RSA2048_NOT_AFTER); + } + + #[test(should_fail)] + fn test_tampered_not_after_rejected() { + let _ = verify_leaf_certificate(date_pushed(), rv::SYN_P256_LEAF_BY_RSA2048_TBS_LEN, rv::SYN_P256_LEAF_BY_RSA2048_SIG, rv::SYN_RSA2048_CA_MODULUS, rv::SYN_RSA2048_CA_REDC); + } + + #[test] + fn test_rsa_leaf_verifies_and_binds_modulus() { + let leaf = verify_leaf_certificate( + pad(rv::SYN_RSA_LEAF_BY_RSA2048_TBS), + rv::SYN_RSA_LEAF_BY_RSA2048_TBS_LEN, + rv::SYN_RSA_LEAF_BY_RSA2048_SIG, + rv::SYN_RSA2048_CA_MODULUS, + rv::SYN_RSA2048_CA_REDC, + ); + assert(leaf.key_type == 1); + assert(leaf.key_hash == rsa_key_hash::<256, 18>(rv::SYN_RSA_LEAF_MODULUS)); + } + + fn modulus_swapped() -> [u8; MAX_TBS_SIZE] { + let mut t = pad(rv::SYN_RSA_LEAF_BY_RSA2048_TBS); + let mut off: u32 = 0; + for i in 0..400 { + if (off == 0) & (t[i] == 0x30) & (t[i + 1] == 0x82) & (t[i + 2] == 0x01) & (t[i + 3] == 0x22) { + off = i; + } + } + assert(off != 0); + for i in 0..256 { + t[off + 33 + i] = rv::SYN_OTHER_RSA2048_MODULUS[i]; + } + t + } + + #[test] + fn test_modulus_swapped_tbs_parses_to_other_key() { + let c = bind_leaf_cert_rsa_signed(modulus_swapped(), rv::SYN_RSA_LEAF_BY_RSA2048_TBS_LEN); + assert(c.key_hash == rsa_key_hash::<256, 18>(rv::SYN_OTHER_RSA2048_MODULUS)); + } + + #[test(should_fail)] + fn test_substituted_rsa_leaf_modulus_rejected() { + let _ = verify_leaf_certificate( + modulus_swapped(), + rv::SYN_RSA_LEAF_BY_RSA2048_TBS_LEN, + rv::SYN_RSA_LEAF_BY_RSA2048_SIG, + rv::SYN_RSA2048_CA_MODULUS, + rv::SYN_RSA2048_CA_REDC, + ); + } + + #[test(should_fail)] + fn test_other_ca_rejected() { + // A different RSA-2048 key did not sign this leaf. + let _ = verify_leaf_certificate( + pad(rv::SYN_P256_LEAF_BY_RSA2048_TBS), + rv::SYN_P256_LEAF_BY_RSA2048_TBS_LEN, + rv::SYN_P256_LEAF_BY_RSA2048_SIG, + rv::SYN_OTHER_RSA2048_MODULUS, + rv::SYN_OTHER_RSA2048_REDC, + ); + } +} From 888d9838b63cca6048fe277d2e9b682ff440f198 Mon Sep 17 00:00:00 2001 From: Jamie Newton <33573418+newtsjamie@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:56:10 +0000 Subject: [PATCH 5/7] Add ProofA RSA-4096 v2 with bound leaf key Same structure as proof_a_rsa_2048_v2 with a 512-byte intermediate modulus and signature (35 limbs). intermediate_leaf hashes all 35 limbs. Public layout matches the v2 templates (52 values). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + proof_a_rsa_4096_v2/Nargo.toml | 17 + proof_a_rsa_4096_v2/src/hash_chain.nr | 548 +++++++++++++++++++++ proof_a_rsa_4096_v2/src/main.nr | 678 ++++++++++++++++++++++++++ 4 files changed, 1244 insertions(+) create mode 100644 proof_a_rsa_4096_v2/Nargo.toml create mode 100644 proof_a_rsa_4096_v2/src/hash_chain.nr create mode 100644 proof_a_rsa_4096_v2/src/main.nr diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0f95cfd..1b0db5a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,7 @@ jobs: - proof_a_ecdsa_p384_sha384_v2 - proof_a_skip_v2 - proof_a_rsa_2048_v2 + - proof_a_rsa_4096_v2 - proof_b_es256_v2_core - proof_b_es256_v2 - proof_b_es256_v2_large diff --git a/proof_a_rsa_4096_v2/Nargo.toml b/proof_a_rsa_4096_v2/Nargo.toml new file mode 100644 index 0000000..4f025a3 --- /dev/null +++ b/proof_a_rsa_4096_v2/Nargo.toml @@ -0,0 +1,17 @@ +[package] +name = "apertrue_proof_a_rsa_4096_v2" +type = "bin" +authors = ["Apertrue"] +compiler_version = ">=1.0.0" +description = "ProofA RSA-4096 v2: P-256 or RSA-2048 leaf key and validity bound to the TBS signed by an RSA-4096 intermediate" + +[dependencies] +# Leaf TBSCertificate hashing, DER walk, RSA/P-256 key extraction +cert_binding = { path = "../cert_binding" } +# RSA verification (zkpassport fork) +noir_rsa = { tag = "v0.10.0", git = "https://github.com/zkpassport/noir_rsa" } +bignum = { tag = "v0.9.2", git = "https://github.com/noir-lang/noir-bignum" } +# SHA-256 for hash chain verification +sha256 = { tag = "v0.3.0", git = "https://github.com/noir-lang/sha256" } +# Poseidon for commitment schemes +poseidon = { tag = "v0.1.1", git = "https://github.com/noir-lang/poseidon" } diff --git a/proof_a_rsa_4096_v2/src/hash_chain.nr b/proof_a_rsa_4096_v2/src/hash_chain.nr new file mode 100644 index 0000000..d7fe6d5 --- /dev/null +++ b/proof_a_rsa_4096_v2/src/hash_chain.nr @@ -0,0 +1,548 @@ +/** + * Hash Chain Verification for Trustless Metadata Binding + * + * This module verifies that extracted metadata values (GPS, timestamp) actually + * came from the signed C2PA claim, preventing substitution attacks. + * + * The verification chain: + * 1. COSE Signature -> COSE Payload (which is claim_hash or claim_bytes) + * 2. SHA256(claim_bytes) -> claim_hash (verified via signature) + * 3. claim_bytes contains assertion_hash at known offset + * 4. SHA256(assertion_bytes) == assertion_hash + * 5. assertion_bytes contain the metadata values at known offsets + * + * Without this verification, a malicious client could: + * - Extract real GPS from signed image + * - Replace with fake GPS + * - Generate valid proof with fake location + * + * With hash chain verification, the circuit ensures: + * - The metadata values are cryptographically bound to the signature + * - Substitution of any value invalidates the proof + * + * CONSTRAINT BUDGET: + * - SHA256 in Noir: ~15k constraints per KB hashed + * - Claim bytes: typically 1-5 KB -> 15-75k constraints + * - Assertion bytes: typically 200B-2KB -> 3-30k constraints + * - Total budget: ~100k constraints for hash chain + * + * OPTIMIZATION STRATEGIES: + * 1. Use pre-computed claim_hash when claim is large (skip in-circuit hashing) + * 2. Only verify assertion hash for assertions containing sensitive data + * 3. For small claims/assertions, in-circuit SHA256 is acceptable + */ + +// SHA256 from stdlib - use digest function with generic size parameter + +/// Maximum size of claim bytes we'll hash in-circuit +/// Claims larger than this should use the pre-computed hash approach +/// RESTORED to 2048 for full cryptographic hash chain verification +/// ProofMode claims are ~1299 bytes, so 2048 provides sufficient headroom +pub global MAX_CLAIM_SIZE: u32 = 2048; + +/// Maximum size of EXIF assertion bytes we'll hash in-circuit +/// RESTORED to 1024 for full assertion hash verification +pub global MAX_EXIF_ASSERTION_SIZE: u32 = 1024; + +/// Maximum size of c2pa.actions assertion bytes we'll hash in-circuit +/// Actions assertions contain edit history (c2pa.created, c2pa.edited, etc.) +/// and AI generation indicators (digitalSourceType: trainedAlgorithmicMedia) +/// NOTE: Adobe Photoshop actions assertions can be 1200-1500 bytes, so 2048 provides headroom +pub global MAX_ACTIONS_ASSERTION_SIZE: u32 = 2048; + +/// SHA256 hash output size +pub global HASH_SIZE: u32 = 32; + +/** + * Verify that claim_hash matches SHA256(claim_bytes) + * + * This binds the claim content to the signature. + * The signature verifies over claim_hash, so if this passes, + * we know claim_bytes are authentic. + * + * IMPORTANT: Uses sha256_var to hash only the first claim_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * claim bytes, not the padded version. + * + * @param claim_bytes Raw CBOR claim bytes (padded to MAX_CLAIM_SIZE) + * @param claim_length Actual length of claim bytes + * @param expected_claim_hash Pre-computed SHA256(claim_bytes) - same as signature input + */ +pub fn verify_claim_hash( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32] +) { + // Bounds check: claim_length must not exceed buffer size + assert(claim_length <= MAX_CLAIM_SIZE, "claim_length exceeds MAX_CLAIM_SIZE"); + + // Compute SHA256 of the ACTUAL claim bytes (not padded) + // sha256_var hashes only the first claim_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(claim_bytes, claim_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_claim_hash[i], + "Claim hash verification failed: claim_bytes do not match expected hash" + ); + } +} + +/** + * Extract assertion hash from claim_bytes at a known offset + * + * The claim contains references to assertions with their expected hashes. + * This function extracts the 32-byte hash at the specified offset. + * + * @param claim_bytes Raw CBOR claim bytes + * @param hash_offset Byte offset where assertion hash appears in claim + * @returns The 32-byte assertion hash from the claim + */ +pub fn extract_assertion_hash_from_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + hash_offset: u32 +) -> [u8; 32] { + let mut assertion_hash: [u8; 32] = [0; 32]; + + // Bounds check + assert( + hash_offset + 32 <= MAX_CLAIM_SIZE, + "Assertion hash offset out of bounds" + ); + + // Extract 32 bytes starting at hash_offset + for i in 0..32 { + assertion_hash[i] = claim_bytes[hash_offset + i]; + } + + assertion_hash +} + +/** + * Verify that assertion_hash matches SHA256(assertion_bytes) + * + * This binds the assertion content to the claim. + * Combined with verify_claim_hash, this creates a complete chain: + * Signature -> Claim -> Assertion -> Metadata + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR or JSON, padded) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_assertion_hash( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_EXIF_ASSERTION_SIZE, "assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Extract a u64 timestamp value from CBOR-encoded assertion bytes + * + * CBOR timestamp encoding (simplified): + * - For small values (0-23): single byte 0x00-0x17 + * - For u8: 0x18 + 1 byte + * - For u16: 0x19 + 2 bytes (big-endian) + * - For u32: 0x1a + 4 bytes (big-endian) + * - For u64: 0x1b + 8 bytes (big-endian) + * + * We extract the raw bytes and convert to u64. + * The offset should point to the START of the CBOR value (type byte). + * + * @param assertion_bytes Raw assertion bytes + * @param timestamp_offset Byte offset where timestamp CBOR value starts + * @returns Extracted timestamp as u64 + */ +pub fn extract_timestamp_from_cbor( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + timestamp_offset: u32 +) -> u64 { + let type_byte = assertion_bytes[timestamp_offset]; + + // Check CBOR type - we expect unsigned integer (major type 0) + let major_type = type_byte >> 5; + let additional_info = type_byte & 0x1f; + + // Major type 0 = unsigned integer + assert(major_type == 0, "Expected CBOR unsigned integer for timestamp"); + + let mut timestamp: u64 = 0; + + if additional_info <= 23 { + // Inline value + timestamp = additional_info as u64; + } else if additional_info == 24 { + // u8 follows - need 2 bytes total + assert(timestamp_offset + 2 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u8 timestamp exceeds buffer"); + timestamp = assertion_bytes[timestamp_offset + 1] as u64; + } else if additional_info == 25 { + // u16 follows (big-endian) - need 3 bytes total + assert(timestamp_offset + 3 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u16 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 2] as u64); + } else if additional_info == 26 { + // u32 follows (big-endian) - need 5 bytes total + assert(timestamp_offset + 5 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u32 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 24; + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 2] as u64) << 16); + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 3] as u64) << 8); + timestamp = timestamp + (assertion_bytes[timestamp_offset + 4] as u64); + } else if additional_info == 27 { + // u64 follows (big-endian) - need 9 bytes total + assert(timestamp_offset + 9 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u64 timestamp exceeds buffer"); + for i in 0..8 { + timestamp = timestamp << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 1 + i] as u64); + } + } else { + // additional_info 28-30 are reserved per CBOR RFC 8949, 31 is indefinite-length + assert(false, "Reserved or unsupported CBOR integer encoding for timestamp"); + } + + timestamp +} + +/** + * GPS BINDING SECURITY MODEL + * ========================== + * + * This module does NOT implement byte-level GPS extraction from CBOR assertions. + * This is a deliberate design choice, not a missing feature. + * + * SECURITY RATIONALE: + * ------------------- + * GPS coordinates are cryptographically bound through the hash chain: + * + * 1. verify_assertion_hash() proves: SHA256(assertion_bytes) == hash_in_claim + * 2. verify_claim_hash() proves: SHA256(claim_bytes) == signed_hash + * 3. COSE signature proves: claim was signed by trusted certificate + * + * Therefore, if the assertion bytes pass hash verification, their ENTIRE CONTENT + * is cryptographically bound to the signature. Any modification to the GPS values + * would change the hash and break verification. + * + * WHY NOT PARSE CBOR IN-CIRCUIT? + * ------------------------------ + * C2PA EXIF GPS coordinates are stored as CBOR rational number arrays: + * { "EXIF:GPSLatitude": [{n: 51, d: 1}, {n: 30, d: 1}, {n: 0, d: 1}] } // 51d 30m 0s + * + * Parsing this requires: + * - Variable-length CBOR decoding (~200+ constraints per value) + * - Rational number arithmetic (degree + minute/60 + second/3600) + * - Sign handling from GPSLatitudeRef/GPSLongitudeRef strings + * + * Total cost: ~500-1000 additional constraints for minimal security gain. + * + * The hash chain already guarantees that the client cannot substitute GPS values + * without invalidating the proof. Adding in-circuit parsing would only catch + * bugs in the client extractor, not malicious tampering. + * + * TRUST MODEL: + * ------------ + * - The CIRCUIT trusts that assertion_bytes were correctly passed from the client + * - The HASH CHAIN proves assertion_bytes match what was signed + * - The CLIENT extracts GPS from the verified bytes + * - Any GPS tampering would require finding a hash collision (computationally infeasible) + * + * For applications requiring stronger guarantees, the circuit could be extended + * to parse CBOR at specific known offsets. This is left as a future enhancement. + */ + +// NOTE: verify_gps_binding() has been intentionally removed. +// GPS binding is provided by verify_assertion_hash() in the hash chain. +// See the SECURITY RATIONALE above for details. + +/** + * Combined hash chain verification + * + * Performs the complete verification: + * 1. SHA256(claim_bytes) == expected_claim_hash (signature input) + * 2. Extract assertion_hash from claim at known offset + * 3. SHA256(assertion_bytes) == assertion_hash + * + * If all pass, we know the assertion_bytes are authentic and + * any values extracted from them are cryptographically bound to the signature. + * + * @param claim_bytes Raw claim bytes (padded) + * @param claim_length Actual claim length + * @param expected_claim_hash SHA256 of claim (same as signature message hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes (padded) + * @param assertion_length Actual assertion length + */ +pub fn verify_full_hash_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Step 1: Verify claim hash + verify_claim_hash(claim_bytes, claim_length, expected_claim_hash); + + // Step 2: Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Step 3: Verify assertion hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // At this point, we've proven: + // - claim_bytes hash to the signed value + // - assertion_bytes hash to a reference in the signed claim + // - Therefore, assertion_bytes are authentic + // - Any values in assertion_bytes are cryptographically bound + + // Silence unused warnings + let _ = claim_length; + let _ = assertion_length; +} + +/** + * Verify timestamp is bound to assertion via hash chain + * + * Combines hash chain verification with timestamp extraction. + * Proves that exact_timestamp actually came from the signed assertion. + * + * @param claim_bytes Raw claim bytes + * @param claim_length Actual claim length + * @param expected_claim_hash Expected claim hash (signature input) + * @param assertion_hash_offset Offset of assertion hash in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + * @param timestamp_offset Offset of timestamp in assertion + * @param expected_timestamp The timestamp value the circuit is using + */ +pub fn verify_timestamp_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + timestamp_offset: u32, + expected_timestamp: u64 +) { + // First verify the hash chain + verify_full_hash_chain( + claim_bytes, + claim_length, + expected_claim_hash, + assertion_hash_offset, + assertion_bytes, + assertion_length + ); + + // Then extract and verify the timestamp + let extracted_timestamp = extract_timestamp_from_cbor(assertion_bytes, timestamp_offset); + + assert( + extracted_timestamp == expected_timestamp, + "Timestamp binding failed: extracted timestamp does not match expected value" + ); +} + +/** + * Verify content hash exists in claim at specified offset + * + * SECURITY: This binds the public content_hash to the signed claim. + * Without this verification, a malicious client could substitute + * a different image's content_hash while keeping the valid signature. + * + * @param claim_bytes Raw claim bytes (CBOR encoded) + * @param content_hash_offset Byte offset where content hash appears in claim + * @param expected_content_hash The content hash (Field) to verify + */ +pub fn verify_content_hash_in_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + // Bounds check + assert( + content_hash_offset + 32 <= MAX_CLAIM_SIZE, + "Content hash offset out of bounds" + ); + + // Extract 32 bytes from claim at offset and convert to Field + let mut extracted_hash: Field = 0; + for i in 0..32 { + extracted_hash = extracted_hash * 256 + claim_bytes[content_hash_offset + i] as Field; + } + + // Verify the extracted content hash matches the public input + assert( + extracted_hash == expected_content_hash, + "Content hash binding failed: public content_hash does not match value in signed claim" + ); +} + +/** + * Verify assertion hash chain (without redundant claim hash check) + * + * Use this when claim_hash has already been verified separately. + * Verifies: SHA256(assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + */ +pub fn verify_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // Silence unused warning + let _ = assertion_length; +} + +/** + * Verify actions assertion hash matches SHA256(actions_assertion_bytes) + * + * This is the same as verify_assertion_hash but for the larger actions buffer. + * Actions assertions (c2pa.actions.v2) can be up to 2048 bytes (Adobe Photoshop). + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR, padded to MAX_ACTIONS_ASSERTION_SIZE) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_actions_assertion_hash( + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_ACTIONS_ASSERTION_SIZE, "actions_assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Actions assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Verify actions assertion hash chain (without redundant claim hash check) + * + * Use this for c2pa.actions.v2 assertions which can be up to 2048 bytes. + * Verifies: SHA256(actions_assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw actions assertion bytes (up to 2048 bytes) + * @param assertion_length Actual assertion length + */ +pub fn verify_actions_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_actions_assertion_hash(assertion_bytes, assertion_length, assertion_hash); +} + +// Tests +#[test] +fn test_content_hash_binding() { + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a known content hash at offset 100 + // Content hash as bytes: 0x0000...0001 (just 1 for simplicity) + claim_bytes[131] = 1; // Last byte = 1 + + // Expected field value is 1 + let expected_hash: Field = 1; + + // This should pass + verify_content_hash_in_claim(claim_bytes, 100, expected_hash); +} + +#[test] +fn test_extract_assertion_hash() { + // Create test claim bytes with a known hash at offset 10 + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a test hash at offset 10 + let test_hash: [u8; 32] = [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 + ]; + + for i in 0..32 { + claim_bytes[10 + i] = test_hash[i]; + } + + let extracted = extract_assertion_hash_from_claim(claim_bytes, 10); + + for i in 0..32 { + assert(extracted[i] == test_hash[i]); + } +} + +#[test] +fn test_extract_cbor_timestamp_inline() { + // Test inline value (0-23) + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x17; // Inline value 23 + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 23); +} + +#[test] +fn test_extract_cbor_timestamp_u32() { + // Test u32 value + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x1a; // u32 follows + // Value: 1700000000 (0x6553F100) - a Unix timestamp + assertion_bytes[1] = 0x65; + assertion_bytes[2] = 0x53; + assertion_bytes[3] = 0xF1; + assertion_bytes[4] = 0x00; + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 1700000000); +} diff --git a/proof_a_rsa_4096_v2/src/main.nr b/proof_a_rsa_4096_v2/src/main.nr new file mode 100644 index 0000000..77071e0 --- /dev/null +++ b/proof_a_rsa_4096_v2/src/main.nr @@ -0,0 +1,678 @@ +/// Apertrue ProofA RSA-4096 v2 - Certificate Chain Verification +/// +/// For a leaf certificate issued by an RSA-4096 intermediate that signs with +/// sha256WithRSAEncryption (PKCS#1 v1.5, e = 65537). The leaf key may be +/// uncompressed P-256 (e.g. Truepic, ES256 claims; pair with proof_b_es256_v2*) +/// or RSA-2048/65537 (e.g. Adobe, PS256 claims; pair with proof_b_ps256_v2). +/// The key type is read from the leaf SPKI DER, not chosen by the prover. +/// +/// v2 binds the leaf key and validity dates to the CA-signed certificate: the +/// full leaf TBSCertificate is a private input, hashed with SHA-256 and +/// DER-walked from offset 0 (cert_binding::bind_leaf_cert_rsa_signed), the TBS +/// signature algorithm must be sha256WithRSAEncryption, and the intermediate's +/// RSA signature is verified over that digest. +/// +/// Versus proof_a_rsa_4096 (v1): +/// - TBS hash, leaf key and dates are no longer free inputs. +/// - The intermediate modulus and the signature are big-endian bytes; limbs +/// are derived in-circuit (range-safe). +/// - intermediate_leaf = cert_binding::rsa_key_hash over ALL 35 modulus limbs. +/// v1 hashed only the 8 low limbs, so an attacker could pick a modulus they +/// can factor with the same low 960 bits and sign any TBS. The trust-list +/// leaf for RSA intermediates must be recomputed this way. +/// - Leaf key hash: P-256 = pedersen_hash([x, y]); RSA = rsa_key_hash over +/// all 18 limbs (v1: 8 low limbs). +/// +/// This circuit proves: +/// 1. The intermediate CA signed (RSA-4096, SHA-256) the leaf TBSCertificate +/// 2. The intermediate CA is in the Oracle's promoted trust list (Merkle membership) +/// 3. The nullifier is derived from the leaf key found in that TBSCertificate +/// 4. proof_timestamp lies within that certificate's validity (dates private) +/// 5. Time range proof (graduated time disclosure) +/// 6. Location range proof (privacy circles) +/// 7. Hash chain verification (claim and assertion integrity) +/// 8. Poseidon commitments for optional future reveal +/// +/// Supported leaf: TBS <= 1280 B. Claim/assertion size classes follow v1 +/// proof_a_rsa_4096 (claim 2048, exif 1024, actions 2048; Adobe actions +/// assertions are 1200-1500 bytes). +/// +/// PUBLIC LAYOUT (index: name; one Field each unless noted) +/// 0 trust_list_root +/// 1 content_hash +/// 2 nullifier pedersen_hash([content_hash, leaf_key_hash]) +/// 3 proof_timestamp +/// 4 time_min +/// 5 time_max +/// 6 edit_time_min +/// 7 edit_time_max +/// 8 center_lat_scaled +/// 9 center_lon_scaled +/// 10 location_flags +/// 11 radius_squared_scaled +/// 12 claim_hash_commitment +/// 13 content_hash_offset +/// 14 skip_content_hash_binding +/// 15 skip_assertion_hash_verification +/// Return values: +/// 16 link_commit pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]) +/// 17 location_commitment +/// 18 time_commitment +/// 19 edit_time_commitment +/// 20..51 actions_assertion_hash (32 x u8) +/// Total 52. Versus v1: cert_not_before (4), cert_not_after (5) and +/// tbs_hash_commitment (14) are removed; every later index shifts down. +/// +/// Shared with ProofB v2 (must be equal across the pair): trust_list_root, +/// content_hash, nullifier, proof_timestamp, claim_hash_commitment, +/// content_hash_offset, link_commit. + +use bignum::params::BigNumParams; +use noir_rsa::rsa::verify_sha256_pkcs1v15; +use std::hash::pedersen_hash; +use dep::poseidon::poseidon2::Poseidon2; +use dep::cert_binding::{bind_leaf_cert_rsa_signed, be_bytes_to_limbs, rsa_key_hash, LeafCertAnyKey}; + +mod hash_chain; + +use hash_chain::{ + MAX_CLAIM_SIZE, + MAX_EXIF_ASSERTION_SIZE, + MAX_ACTIONS_ASSERTION_SIZE, + verify_claim_hash, + verify_content_hash_in_claim, + verify_assertion_chain, + verify_actions_assertion_chain, +}; + +/// Maximum leaf TBSCertificate size (DER bytes) +global MAX_TBS_SIZE: u32 = 1280; + +/// RSA-4096 uses 35 limbs of 120 bits +global RSA_NUM_LIMBS: u32 = 35; + +/// ProofA RSA-4096 v2 main entry point +fn main( + // === PUBLIC INPUTS (shared with ProofB) === + trust_list_root: pub Field, + content_hash: pub Field, + nullifier: pub Field, + proof_timestamp: pub Field, + + // === PUBLIC INPUTS: TIME RANGE BOUNDS (for graduated time disclosure) === + time_min: pub Field, + time_max: pub Field, + + // === PUBLIC INPUTS: EDIT TIME RANGE BOUNDS (for edited images) === + // When a photo is edited (e.g., Leica capture -> Lightroom export), the capture + // and edit timestamps differ. These bounds constrain the edit/signing timestamp. + // Set to 0 when no edit occurred (direct camera capture). + edit_time_min: pub Field, // Minimum edit timestamp bound (0 if no edit) + edit_time_max: pub Field, // Maximum edit timestamp bound (0 if no edit) + + // === PUBLIC INPUTS: LOCATION PRIVACY CIRCLE (for graduated location disclosure) === + center_lat_scaled: pub Field, + center_lon_scaled: pub Field, + location_flags: pub u8, // bit 0 = lat negative (South), bit 1 = lon negative (West) + radius_squared_scaled: pub Field, + + // === PUBLIC INPUT: Claim Hash Commitment (packed from 32 bytes to 1 Field) === + // This is Poseidon2(bytes32_to_field_array(claim_hash)). Saves 31 public input fields. + claim_hash_commitment: pub Field, + + // === PUBLIC INPUT: Content Hash Offset (for content binding) === + content_hash_offset: pub u32, + + // === PRIVATE: LEAF TBSCertificate (DER, zero padded past tbs_len) === + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + + // === PRIVATE: CLAIM HASH BYTES (unpacked from commitment) === + claim_hash: [u8; 32], + + // === PRIVATE: SKIP FLAGS === + skip_content_hash_binding: pub u8, + skip_assertion_hash_verification: pub u8, + + // === PRIVATE: RSA-4096 CERTIFICATE SIGNATURE & KEY (big-endian bytes) === + cert_signature_rsa: [u8; 512], + intermediate_rsa_modulus: [u8; 512], + intermediate_rsa_redc_limbs: [u128; RSA_NUM_LIMBS], // floor(2^(2*4096+6) / n) + + // === PRIVATE: LINKING WITNESS === + intermediate_leaf: Field, + link_blind: Field, + + // === PRIVATE: MERKLE MEMBERSHIP (trust list verification) === + merkle_path: [Field; 8], + merkle_indices: [Field; 8], + + // === PRIVATE: EXACT TIMESTAMP (for time range proof) === + exact_timestamp: Field, + + // === PRIVATE: EXACT GPS LOCATION (for location range proof) === + exact_lat_scaled: Field, + exact_lon_scaled: Field, + exact_lat_is_negative: u8, + exact_lon_is_negative: u8, + + // === PRIVATE: HASH CHAIN DATA === + enable_hash_chain_verification: u8, + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + exif_assertion_hash_offset: u32, + exif_assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + exif_assertion_length: u32, + + // === PRIVATE: ACTIONS ASSERTION === + actions_assertion_hash_offset: u32, + actions_assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + actions_assertion_length: u32, + + // === PRIVATE: COMMITMENT SALTS === + location_salt: Field, + time_salt: Field, + + // === PRIVATE: EDIT TIMESTAMP & SALT (for separate edit time commitment) === + exact_edit_timestamp: Field, // Edit/signing timestamp (0 if no edit) + edit_time_salt: Field // Salt for edit time commitment +) -> pub (Field, Field, Field, Field, [u8; 32]) { // Returns (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) + // ================================================================ + // STEP 0: Verify claim hash commitment packing + // ================================================================ + let computed_claim_commitment = Poseidon2::hash(bytes32_to_field_array(claim_hash), 2); + assert(computed_claim_commitment == claim_hash_commitment, "Claim hash commitment mismatch"); + + // ================================================================ + // STEP 1: Hash + DER-walk the leaf TBS; intermediate signs that hash + // ================================================================ + let leaf = verify_leaf_certificate( + tbs_certificate, + tbs_len, + cert_signature_rsa, + intermediate_rsa_modulus, + intermediate_rsa_redc_limbs + ); + + // ================================================================ + // STEP 2: Derive Leaf Key Hash (key taken from the signed TBS) + // ================================================================ + // P-256: pedersen_hash([x, y]); RSA-2048: rsa_key_hash (18 limbs) + let computed_leaf_key_hash = leaf.key_hash; + + // ================================================================ + // STEP 3: Verify Nullifier Derivation + // ================================================================ + let expected_nullifier = pedersen_hash([content_hash, computed_leaf_key_hash]); + assert(nullifier == expected_nullifier, "Invalid nullifier (leaf key binding failed)"); + + // ================================================================ + // STEP 4: Compute Link Commitment (returned as output) + // ================================================================ + let claim_hash_field = bytes_to_field(claim_hash); + let link_commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + + // ================================================================ + // STEP 4b: Verify Intermediate Leaf Formulation + // ================================================================ + let computed_intermediate_hash = rsa_key_hash::<512, 35>(intermediate_rsa_modulus); + + assert( + intermediate_leaf == computed_intermediate_hash, + "Intermediate Leaf witnessing mismatch (Self-Signing Attack prevention)" + ); + + // ================================================================ + // STEP 4c: Merkle Membership (Trust List Verification) + // ================================================================ + let computed_root = compute_merkle_root(intermediate_leaf, merkle_path, merkle_indices); + assert(computed_root == trust_list_root, "Intermediate CA not in trust list"); + + // ================================================================ + // STEP 5: Certificate Validity (Time) + // ================================================================ + // Dates come from the signed TBS and stay private. + assert(proof_timestamp as u64 as Field == proof_timestamp, "proof_timestamp exceeds u64"); + let ts = proof_timestamp as u64; + let not_before = leaf.not_before; + let not_after = leaf.not_after; + assert(ts >= not_before, "Certificate not yet valid at proof time"); + assert(ts <= not_after, "Certificate expired at proof time"); + + // ================================================================ + // STEP 6: Time Range Proof (Graduated Time Disclosure) + // ================================================================ + assert(exact_timestamp as u64 as Field == exact_timestamp, "exact_timestamp exceeds u64"); + assert(time_min as u64 as Field == time_min, "time_min exceeds u64"); + assert(time_max as u64 as Field == time_max, "time_max exceeds u64"); + let exact_ts = exact_timestamp as u64; + let min_ts = time_min as u64; + let max_ts = time_max as u64; + + assert(exact_ts >= min_ts, "Exact timestamp is before disclosed time_min"); + assert(exact_ts <= max_ts, "Exact timestamp is after disclosed time_max"); + + // ================================================================ + // STEP 6b: Edit Time Range Proof (0 = no edit, skip) + // ================================================================ + // When a photo is edited (capture -> export), exact_edit_timestamp is the + // signing/export time. For direct camera captures, it's 0 (sentinel). + if exact_edit_timestamp != 0 { + assert(exact_edit_timestamp as u64 as Field == exact_edit_timestamp, "exact_edit_timestamp exceeds u64"); + assert(edit_time_min as u64 as Field == edit_time_min, "edit_time_min exceeds u64"); + assert(edit_time_max as u64 as Field == edit_time_max, "edit_time_max exceeds u64"); + let edit_ts = exact_edit_timestamp as u64; + let edit_min = edit_time_min as u64; + let edit_max = edit_time_max as u64; + assert(edit_ts >= edit_min, "Edit timestamp before edit_time_min"); + assert(edit_ts <= edit_max, "Edit timestamp after edit_time_max"); + } else { + assert(edit_time_min == 0, "edit_time_min must be 0 when no edit"); + assert(edit_time_max == 0, "edit_time_max must be 0 when no edit"); + } + + // ================================================================ + // STEP 7: Location Range Proof (Graduated Location Disclosure) + // ================================================================ + // Unpack location_flags: bit 0 = lat negative, bit 1 = lon negative + // Reject if unused high bits (2-7) are set - prevents flag stuffing + assert(location_flags <= 3, "location_flags has invalid high bits set (must be 0-3)"); + let center_lat_is_negative = location_flags & 1; + let center_lon_is_negative = (location_flags >> 1) & 1; + + assert(exact_lat_is_negative <= 1, "exact_lat_is_negative must be 0 or 1"); + assert(exact_lon_is_negative <= 1, "exact_lon_is_negative must be 0 or 1"); + assert(skip_content_hash_binding <= 1, "skip_content_hash_binding must be 0 or 1"); + assert(skip_assertion_hash_verification <= 1, "skip_assertion_hash_verification must be 0 or 1"); + + assert(exact_lat_scaled as u64 as Field == exact_lat_scaled, "exact_lat_scaled exceeds u64"); + assert(center_lat_scaled as u64 as Field == center_lat_scaled, "center_lat_scaled exceeds u64"); + assert(exact_lon_scaled as u64 as Field == exact_lon_scaled, "exact_lon_scaled exceeds u64"); + assert(center_lon_scaled as u64 as Field == center_lon_scaled, "center_lon_scaled exceeds u64"); + + { + let lat_same_sign = (exact_lat_is_negative == center_lat_is_negative); + let d_lat = if lat_same_sign { + if exact_lat_scaled as u64 > center_lat_scaled as u64 { + exact_lat_scaled - center_lat_scaled + } else { + center_lat_scaled - exact_lat_scaled + } + } else { + exact_lat_scaled + center_lat_scaled + }; + + let lon_same_sign = (exact_lon_is_negative == center_lon_is_negative); + let d_lon = if lon_same_sign { + if exact_lon_scaled as u64 > center_lon_scaled as u64 { + exact_lon_scaled - center_lon_scaled + } else { + center_lon_scaled - exact_lon_scaled + } + } else { + exact_lon_scaled + center_lon_scaled + }; + + // NOTE: Euclidean distance in coordinate space. At high latitudes, + // 1 deg lon < 1 deg lat in real-world distance, so this circle is elliptical. + // The client-side radius computation (metersToScaledRadius) compensates + // by using the longitude conversion at the user's latitude, ensuring the + // privacy circle covers at least the requested radius in ALL directions. + let distance_squared = d_lat * d_lat + d_lon * d_lon; + assert(distance_squared as u64 as Field == distance_squared, "distance_squared exceeds u64"); + assert(radius_squared_scaled as u64 as Field == radius_squared_scaled, "radius_squared_scaled exceeds u64"); + + assert( + distance_squared as u64 <= radius_squared_scaled as u64, + "Exact GPS location is outside disclosed privacy circle" + ); + } + + // ================================================================ + // STEP 8: Hash Chain Verification (Trustless Metadata Binding) + // ================================================================ + assert( + enable_hash_chain_verification == 1, + "Hash chain verification must be enabled" + ); + + // Step 8a: Verify claim_hash = SHA256(claim_bytes) + verify_claim_hash(claim_bytes, claim_length, claim_hash); + + // Step 8b: Verify content_hash exists in claim_bytes + if skip_content_hash_binding == 0 { + verify_content_hash_binding(claim_bytes, content_hash_offset, content_hash); + } + + // Step 8c: Verify assertion hash chain + if skip_assertion_hash_verification == 0 { + verify_assertion_chain( + claim_bytes, + exif_assertion_hash_offset, + exif_assertion_bytes, + exif_assertion_length + ); + } + + // Step 8d: Verify actions assertion hash chain (optional) + let actions_assertion_hash: [u8; 32] = if actions_assertion_hash_offset > 0 { + verify_actions_assertion_chain( + claim_bytes, + actions_assertion_hash_offset, + actions_assertion_bytes, + actions_assertion_length + ); + let hash_result: [u8; 32] = dep::sha256::sha256_var( + actions_assertion_bytes, + actions_assertion_length as u32 + ); + hash_result + } else { + [0u8; 32] + }; + + // ================================================================ + // STEP 9: Compute Poseidon Commitments (Optional Future Reveal) + // ================================================================ + let lat_sign_field = exact_lat_is_negative as Field; + let lon_sign_field = exact_lon_is_negative as Field; + + let location_commitment = Poseidon2::hash( + [exact_lat_scaled, exact_lon_scaled, lat_sign_field, lon_sign_field, location_salt], + 5 + ); + + let time_commitment = Poseidon2::hash( + [exact_timestamp, time_salt], + 2 + ); + + // Edit time commitment: Poseidon2([edit_timestamp, salt]) or 0 sentinel + // Poseidon2 never outputs 0 for valid inputs, so 0 is safe as "no edit" sentinel + let edit_time_commitment = if exact_edit_timestamp == 0 { + 0 // Sentinel: no edit happened + } else { + Poseidon2::hash([exact_edit_timestamp, edit_time_salt], 2) + }; + + // Return public outputs + (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) +} + +/// Hash and DER-walk the leaf TBSCertificate (sha256WithRSAEncryption), +/// then check that the intermediate's RSA-4096 PKCS#1 v1.5 signature covers +/// exactly that SHA-256. +fn verify_leaf_certificate( + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + sig: [u8; 512], + intermediate_modulus: [u8; 512], + intermediate_redc: [u128; RSA_NUM_LIMBS] +) -> LeafCertAnyKey { + let leaf = bind_leaf_cert_rsa_signed(tbs_certificate, tbs_len); + assert(intermediate_modulus[0] >= 0x80, "RSA intermediate modulus is not 4096 bits"); + let limbs: [u128; RSA_NUM_LIMBS] = be_bytes_to_limbs(intermediate_modulus); + let params: BigNumParams = BigNumParams::new(false, limbs, intermediate_redc); + let signature = bignum::RuntimeBigNum::from_be_bytes(params, sig); + let valid = verify_sha256_pkcs1v15(leaf.sha256, signature, 65537); + assert(valid, "RSA-4096 certificate verification failed"); + leaf +} + +/// Convert 32 bytes to Field (big-endian) +fn bytes_to_field(bytes: [u8; 32]) -> Field { + let mut result: Field = 0; + for i in 0..32 { + result = result * 256 + bytes[i] as Field; + } + result +} + +/// Convert 32 bytes to 2 Field elements for Poseidon2 hashing +/// Splits into two 16-byte (128-bit) chunks that fit within the BN254 field +fn bytes32_to_field_array(bytes: [u8; 32]) -> [Field; 2] { + // First 16 bytes -> Field 0 + let mut f0: Field = 0; + for i in 0..16 { + f0 = f0 * 256 + bytes[i] as Field; + } + // Last 16 bytes -> Field 1 + let mut f1: Field = 0; + for i in 16..32 { + f1 = f1 * 256 + bytes[i] as Field; + } + [f0, f1] +} + +/// Verify content hash exists in claim at offset +fn verify_content_hash_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + verify_content_hash_in_claim(claim_bytes, content_hash_offset, expected_content_hash); +} + +/// Compute Merkle root from leaf and proof +fn compute_merkle_root( + leaf: Field, + path: [Field; 8], + indices: [Field; 8] +) -> Field { + let mut current = leaf; + + for i in 0..8 { + assert((indices[i] == 0) | (indices[i] == 1), "Merkle index must be 0 or 1"); + let path_element = path[i]; + let is_right = indices[i]; + let left = if is_right == 0 { current } else { path_element }; + let right = if is_right == 0 { path_element } else { current }; + current = pedersen_hash([left, right]); + } + + current +} + +// ==================================================================== +// TESTS +// ==================================================================== + +#[test] +fn test_merkle_root_computation() { + let leaf: Field = 12345; + let path: [Field; 8] = [0; 8]; + let indices: [Field; 8] = [0; 8]; + + let root = compute_merkle_root(leaf, path, indices); + assert(root != leaf, "Merkle root should not equal leaf"); + + let root2 = compute_merkle_root(leaf, path, indices); + assert(root == root2, "Merkle root should be deterministic"); +} + +#[test] +fn test_merkle_different_leaves() { + let path: [Field; 8] = [0; 8]; + let indices: [Field; 8] = [0; 8]; + + let root1 = compute_merkle_root(111, path, indices); + let root2 = compute_merkle_root(222, path, indices); + + assert(root1 != root2, "Different leaves should produce different roots"); +} + +#[test] +fn test_time_range_exact_bounds() { + let exact: u64 = 1000; + let min: u64 = 1000; + let max: u64 = 2000; + + assert(exact >= min, "Timestamp at min bound should pass"); + assert(exact <= max, "Timestamp within range should pass"); +} + +#[test] +fn test_location_same_point() { + let exact_lat: Field = 510000000; + let exact_lon: Field = 100000000; + let center_lat: Field = 510000000; + let center_lon: Field = 100000000; + + let d_lat = if exact_lat as u64 > center_lat as u64 { + exact_lat - center_lat + } else { + center_lat - exact_lat + }; + + let d_lon = if exact_lon as u64 > center_lon as u64 { + exact_lon - center_lon + } else { + center_lon - exact_lon + }; + + let distance_squared = d_lat * d_lat + d_lon * d_lon; + assert(distance_squared == 0, "Same point should have zero distance"); +} + +#[test] +fn test_bytes_to_field() { + let mut bytes: [u8; 32] = [0; 32]; + bytes[31] = 1; + let field = bytes_to_field(bytes); + assert(field == 1); + + bytes[31] = 255; + let field2 = bytes_to_field(bytes); + assert(field2 == 255); +} + +#[test] +fn test_nullifier_derivation_ecdsa() { + let content_hash: Field = 111; + let leaf_key_hash: Field = 222; + let nullifier = pedersen_hash([content_hash, leaf_key_hash]); + + let different_content: Field = 333; + let different_nullifier = pedersen_hash([different_content, leaf_key_hash]); + assert(nullifier != different_nullifier); +} + +#[test] +fn test_link_commitment_with_claim_hash() { + let intermediate_leaf: Field = 12345; + let claim_hash_field: Field = 99999; + let link_blind: Field = 67890; + + let commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + let commit2 = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + assert(commit == commit2); + + let different_claim: Field = 11111; + let commit3 = pedersen_hash([intermediate_leaf, different_claim, link_blind]); + assert(commit != commit3); +} + +// ==================================================================== +// CERTIFICATE TESTS (synthetic chains: RSA-4096 CA, sha256WithRSAEncryption) +// ==================================================================== + +mod cert_tests { + use super::{verify_leaf_certificate, MAX_TBS_SIZE}; + use dep::cert_binding::rsa_vectors as rv; + use dep::cert_binding::test_vectors as tv; + use dep::cert_binding::{bind_leaf_cert_rsa_signed, p256_key_hash, rsa_key_hash}; + + fn pad(a: [u8; M]) -> [u8; MAX_TBS_SIZE] { + let mut out: [u8; MAX_TBS_SIZE] = [0; MAX_TBS_SIZE]; + for i in 0..M { + out[i] = a[i]; + } + out + } + + #[test] + fn test_p256_leaf_verifies_and_binds_key() { + let leaf = verify_leaf_certificate( + pad(rv::SYN_P256_LEAF_BY_RSA4096_TBS), + rv::SYN_P256_LEAF_BY_RSA4096_TBS_LEN, + rv::SYN_P256_LEAF_BY_RSA4096_SIG, + rv::SYN_RSA4096_CA_MODULUS, + rv::SYN_RSA4096_CA_REDC, + ); + assert(leaf.key_type == 0); + assert(leaf.key_hash == p256_key_hash(rv::SYN_EC_LEAF_PUB_X, rv::SYN_EC_LEAF_PUB_Y)); + assert(leaf.not_before == rv::SYN_P256_LEAF_BY_RSA4096_NOT_BEFORE); + assert(leaf.not_after == rv::SYN_P256_LEAF_BY_RSA4096_NOT_AFTER); + } + + // noir_rsa's PKCS#1 v1.5 check fails unlabelled assertions rather than + // returning false, so the negatives use plain should_fail. Each tampered + // TBS has a positive twin showing it still parses (DER walk, algorithm and + // key checks pass), so the failure is the CA signature check. + + fn key_swapped() -> [u8; MAX_TBS_SIZE] { + let mut t = pad(rv::SYN_P256_LEAF_BY_RSA4096_TBS); + let mut off: u32 = 0; + for i in 0..400 { + if (off == 0) & (t[i] == 0x30) & (t[i + 1] == 0x59) & (t[i + 2] == 0x30) & (t[i + 3] == 0x13) { + off = i; + } + } + assert(off != 0); + for i in 0..32 { + t[off + 27 + i] = tv::LEICA_LEAF_PUB_X[i]; + t[off + 59 + i] = tv::LEICA_LEAF_PUB_Y[i]; + } + t + } + + #[test] + fn test_key_swapped_tbs_parses_to_other_key() { + let c = bind_leaf_cert_rsa_signed(key_swapped(), rv::SYN_P256_LEAF_BY_RSA4096_TBS_LEN); + assert(c.key_hash == p256_key_hash(tv::LEICA_LEAF_PUB_X, tv::LEICA_LEAF_PUB_Y)); + } + + #[test(should_fail)] + fn test_substituted_leaf_key_rejected() { + // Genuine CA signature, another P-256 key in the SPKI. + let _ = verify_leaf_certificate(key_swapped(), rv::SYN_P256_LEAF_BY_RSA4096_TBS_LEN, rv::SYN_P256_LEAF_BY_RSA4096_SIG, rv::SYN_RSA4096_CA_MODULUS, rv::SYN_RSA4096_CA_REDC); + } + + fn date_pushed() -> [u8; MAX_TBS_SIZE] { + // Extend notAfter by a decade (UTCTime "34" -> "44"). + let mut t = pad(rv::SYN_P256_LEAF_BY_RSA4096_TBS); + let mut first: u32 = 0; + let mut second: u32 = 0; + for i in 0..300 { + if (t[i] == 0x17) & (t[i + 1] == 0x0d) { + if first == 0 { + first = i; + } else if second == 0 { + second = i; + } + } + } + assert(second != 0); + t[second + 2] = 0x34; + t + } + + #[test] + fn test_date_pushed_tbs_parses_to_later_date() { + let c = bind_leaf_cert_rsa_signed(date_pushed(), rv::SYN_P256_LEAF_BY_RSA4096_TBS_LEN); + assert(c.not_after > rv::SYN_P256_LEAF_BY_RSA4096_NOT_AFTER); + } + + #[test(should_fail)] + fn test_tampered_not_after_rejected() { + let _ = verify_leaf_certificate(date_pushed(), rv::SYN_P256_LEAF_BY_RSA4096_TBS_LEN, rv::SYN_P256_LEAF_BY_RSA4096_SIG, rv::SYN_RSA4096_CA_MODULUS, rv::SYN_RSA4096_CA_REDC); + } + + #[test] + fn test_rsa_key_hash_4096_uses_all_limbs() { + let h1 = rsa_key_hash::<512, 35>(rv::SYN_RSA4096_CA_MODULUS); + let mut m = rv::SYN_RSA4096_CA_MODULUS; + m[0] = m[0] ^ 0x01; + assert(h1 != rsa_key_hash::<512, 35>(m)); + } +} From a32985979ed600ed31f89f7a67e2fe0559e46dcc Mon Sep 17 00:00:00 2001 From: Jamie Newton <33573418+newtsjamie@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:42:09 +0000 Subject: [PATCH 6/7] Add ProofA RSA-2048 SHA-384 v2 for leaves signed sha384WithRSAEncryption The Truepic CA behind ChatGPT images signs leaf certificates with sha384WithRSAEncryption, which proof_a_rsa_2048_v2 does not accept. This variant hashes the leaf TBS with SHA-384 and verifies the intermediate's PKCS#1 v1.5 signature over it; everything else matches proof_a_rsa_2048_v2. Tested against the real ChatGPT chain. cert_binding gains bind_leaf_cert_rsa_signed_sha384; existing circuits compile to the same bytecode. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + cert_binding/src/lib.nr | 37 + proof_a_rsa_2048_sha384_v2/Nargo.toml | 17 + .../src/chatgpt_vectors.nr | 12 + proof_a_rsa_2048_sha384_v2/src/hash_chain.nr | 548 ++++++++++++++ proof_a_rsa_2048_sha384_v2/src/main.nr | 677 ++++++++++++++++++ 6 files changed, 1292 insertions(+) create mode 100644 proof_a_rsa_2048_sha384_v2/Nargo.toml create mode 100644 proof_a_rsa_2048_sha384_v2/src/chatgpt_vectors.nr create mode 100644 proof_a_rsa_2048_sha384_v2/src/hash_chain.nr create mode 100644 proof_a_rsa_2048_sha384_v2/src/main.nr diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1b0db5a..571bc66 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,7 @@ jobs: - proof_a_ecdsa_p384_sha384_v2 - proof_a_skip_v2 - proof_a_rsa_2048_v2 + - proof_a_rsa_2048_sha384_v2 - proof_a_rsa_4096_v2 - proof_b_es256_v2_core - proof_b_es256_v2 diff --git a/cert_binding/src/lib.nr b/cert_binding/src/lib.nr index f802753..6461056 100644 --- a/cert_binding/src/lib.nr +++ b/cert_binding/src/lib.nr @@ -378,6 +378,43 @@ pub fn bind_leaf_cert_rsa_signed(tbs: [u8; N], tbs_len: u32) -> Leaf LeafCertAnyKey { sha256, key_type, key_hash, not_before: w.not_before, not_after: w.not_after } } +/// DER content of AlgorithmIdentifier sha384WithRSAEncryption +/// (OID 1.2.840.113549.1.1.12, NULL parameters). +pub global ALG_RSA_SHA384: [u8; 13] = + [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0c, 0x05, 0x00]; + +/// A P-256 or RSA-2048 leaf whose issuer signed with sha384WithRSAEncryption. +pub struct LeafCertAnyKeySha384 { + pub sha384: [u8; 48], + /// 0 = P-256 (key_hash = p256_key_hash), 1 = RSA-2048 (key_hash = rsa_key_hash, 18 limbs) + pub key_type: u8, + pub key_hash: Field, + pub not_before: u64, + pub not_after: u64, +} + +/// As bind_leaf_cert_rsa_signed, for a TBSCertificate signed with +/// sha384WithRSAEncryption (e.g. the Truepic CA behind ChatGPT images). The +/// digest is SHA-384 and the key type is read from the SPKI DER. +pub fn bind_leaf_cert_rsa_signed_sha384(tbs: [u8; N], tbs_len: u32) -> LeafCertAnyKeySha384 { + assert(tbs_len <= N, "tbs_len exceeds buffer"); + let sha384 = tbs_sha384(tbs, tbs_len); + let w = walk_tbs(tbs, tbs_len); + assert_sig_alg(tbs, w, ALG_RSA_SHA384); + let is_p256 = tbs[w.spki_start + 1] == 0x59; + let mut key_hash: Field = 0; + let mut key_type: u8 = 0; + if is_p256 { + let (x, y) = read_p256_spki(tbs, tbs_len, w.spki_start); + key_hash = p256_key_hash(x, y); + } else { + let m = read_rsa2048_spki(tbs, tbs_len, w.spki_start); + key_hash = rsa_key_hash::<256, 18>(m); + key_type = 1; + } + LeafCertAnyKeySha384 { sha384, key_type, key_hash, not_before: w.not_before, not_after: w.not_after } +} + /// Hash and parse a DER TBSCertificate whose subject key is P-256. /// This body is kept as originally written (rather than calling walk_tbs) /// so the compiled v2 circuits, and their verification keys, do not change. diff --git a/proof_a_rsa_2048_sha384_v2/Nargo.toml b/proof_a_rsa_2048_sha384_v2/Nargo.toml new file mode 100644 index 0000000..2a4e82f --- /dev/null +++ b/proof_a_rsa_2048_sha384_v2/Nargo.toml @@ -0,0 +1,17 @@ +[package] +name = "apertrue_proof_a_rsa_2048_sha384_v2" +type = "bin" +authors = ["Apertrue"] +compiler_version = ">=1.0.0" +description = "ProofA RSA-2048 SHA-384 v2: P-256 or RSA-2048 leaf key and validity bound to the TBS signed sha384WithRSAEncryption by an RSA-2048 intermediate" + +[dependencies] +# Leaf TBSCertificate hashing, DER walk, RSA/P-256 key extraction +cert_binding = { path = "../cert_binding" } +# RSA verification (zkpassport fork) +noir_rsa = { tag = "v0.10.0", git = "https://github.com/zkpassport/noir_rsa" } +bignum = { tag = "v0.9.2", git = "https://github.com/noir-lang/noir-bignum" } +# SHA-256 for hash chain verification +sha256 = { tag = "v0.3.0", git = "https://github.com/noir-lang/sha256" } +# Poseidon for commitment schemes +poseidon = { tag = "v0.1.1", git = "https://github.com/noir-lang/poseidon" } diff --git a/proof_a_rsa_2048_sha384_v2/src/chatgpt_vectors.nr b/proof_a_rsa_2048_sha384_v2/src/chatgpt_vectors.nr new file mode 100644 index 0000000..90850d1 --- /dev/null +++ b/proof_a_rsa_2048_sha384_v2/src/chatgpt_vectors.nr @@ -0,0 +1,12 @@ +// Real ChatGPT (Truepic) C2PA chain, taken from a public ChatGPT image. +// Leaf CN=Truepic Lens CLI in ChatGPT, P-256 key, signed +// sha384WithRSAEncryption by CN=WebClaimSigningCA (RSA-2048, e = 65537). +// REDC = floor(2^(2*2048+6) / n) as 120-bit limbs, least significant first. + +pub global CHATGPT_LEAF_TBS_LEN: u32 = 543; +pub global CHATGPT_LEAF_TBS: [u8; 543] = [0x30, 0x82, 0x02, 0x1b, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x14, 0x6e, 0xae, 0x28, 0xa3, 0xee, 0xc5, 0xb8, 0xe4, 0x2a, 0x36, 0xfa, 0x1d, 0xe6, 0x41, 0x15, 0xae, 0x62, 0x16, 0x1b, 0x3b, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0c, 0x05, 0x00, 0x30, 0x4a, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x57, 0x65, 0x62, 0x43, 0x6c, 0x61, 0x69, 0x6d, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x41, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x04, 0x4c, 0x65, 0x6e, 0x73, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x07, 0x54, 0x72, 0x75, 0x65, 0x70, 0x69, 0x63, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x35, 0x30, 0x31, 0x31, 0x33, 0x32, 0x30, 0x33, 0x36, 0x34, 0x36, 0x5a, 0x17, 0x0d, 0x32, 0x36, 0x30, 0x31, 0x31, 0x33, 0x32, 0x30, 0x33, 0x36, 0x34, 0x35, 0x5a, 0x30, 0x56, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x06, 0x4f, 0x70, 0x65, 0x6e, 0x41, 0x49, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x07, 0x43, 0x68, 0x61, 0x74, 0x47, 0x50, 0x54, 0x31, 0x24, 0x30, 0x22, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1b, 0x54, 0x72, 0x75, 0x65, 0x70, 0x69, 0x63, 0x20, 0x4c, 0x65, 0x6e, 0x73, 0x20, 0x43, 0x4c, 0x49, 0x20, 0x69, 0x6e, 0x20, 0x43, 0x68, 0x61, 0x74, 0x47, 0x50, 0x54, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x56, 0x1d, 0x78, 0xc7, 0x2a, 0x50, 0x0f, 0x7d, 0xee, 0x04, 0xc8, 0x14, 0xf5, 0xab, 0xa4, 0x76, 0x7b, 0x8b, 0xed, 0xd3, 0xa3, 0x23, 0x3d, 0xd5, 0xa6, 0x42, 0x33, 0xd9, 0x4c, 0x29, 0x09, 0x42, 0x31, 0x30, 0x08, 0x4b, 0xa5, 0x35, 0x95, 0xe8, 0x91, 0xe3, 0x2e, 0xf0, 0xda, 0x9a, 0xa3, 0xac, 0x01, 0x0a, 0xee, 0x02, 0xd9, 0x89, 0x5f, 0x0c, 0xd5, 0x2d, 0xbb, 0x2e, 0x16, 0x9a, 0x37, 0xe8, 0xa3, 0x81, 0xcf, 0x30, 0x81, 0xcc, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x5a, 0x1f, 0x6b, 0x66, 0xd3, 0x94, 0xe7, 0xb0, 0x41, 0x83, 0x7d, 0x9c, 0x0c, 0x7b, 0x5d, 0xc5, 0x73, 0x4b, 0x4b, 0xb3, 0x30, 0x4d, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01, 0x04, 0x41, 0x30, 0x3f, 0x30, 0x3d, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x86, 0x31, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x76, 0x61, 0x2e, 0x74, 0x72, 0x75, 0x65, 0x70, 0x69, 0x63, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6a, 0x62, 0x63, 0x61, 0x2f, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x77, 0x65, 0x62, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2f, 0x6f, 0x63, 0x73, 0x70, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x04, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x24, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xca, 0x5e, 0x13, 0x2e, 0x2c, 0x1b, 0x35, 0xa2, 0x6d, 0x62, 0x45, 0x4d, 0x33, 0x43, 0x05, 0x62, 0xec, 0x93, 0xf8, 0x2a, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x07, 0x80]; +pub global CHATGPT_LEAF_PUB_X: [u8; 32] = [0x56, 0x1d, 0x78, 0xc7, 0x2a, 0x50, 0x0f, 0x7d, 0xee, 0x04, 0xc8, 0x14, 0xf5, 0xab, 0xa4, 0x76, 0x7b, 0x8b, 0xed, 0xd3, 0xa3, 0x23, 0x3d, 0xd5, 0xa6, 0x42, 0x33, 0xd9, 0x4c, 0x29, 0x09, 0x42]; +pub global CHATGPT_LEAF_PUB_Y: [u8; 32] = [0x31, 0x30, 0x08, 0x4b, 0xa5, 0x35, 0x95, 0xe8, 0x91, 0xe3, 0x2e, 0xf0, 0xda, 0x9a, 0xa3, 0xac, 0x01, 0x0a, 0xee, 0x02, 0xd9, 0x89, 0x5f, 0x0c, 0xd5, 0x2d, 0xbb, 0x2e, 0x16, 0x9a, 0x37, 0xe8]; +pub global CHATGPT_CA_SIG: [u8; 256] = [0x79, 0x68, 0x3e, 0x7b, 0x3d, 0xe3, 0x82, 0xe1, 0xd9, 0x5d, 0xb9, 0xb8, 0x6e, 0xbb, 0xa1, 0xd7, 0x12, 0x44, 0xd0, 0x97, 0x14, 0x29, 0xf5, 0x07, 0x53, 0x2d, 0xd3, 0xf7, 0xfa, 0xa7, 0xd3, 0xf2, 0x3d, 0xe1, 0x11, 0xe9, 0x02, 0xe2, 0x47, 0x1a, 0xd3, 0x91, 0xf3, 0x68, 0x5e, 0x29, 0xfd, 0xea, 0xcd, 0x7c, 0x8a, 0x5e, 0xed, 0xeb, 0x46, 0x1f, 0xf0, 0xe6, 0x41, 0x4a, 0xb9, 0xdc, 0x03, 0x69, 0xaa, 0xaf, 0xc5, 0x5a, 0x43, 0xd9, 0x45, 0xcb, 0x00, 0xaf, 0x8d, 0xf4, 0xdc, 0x6a, 0xaf, 0x4d, 0x8b, 0x2d, 0x8c, 0x9b, 0x00, 0x9f, 0x33, 0xd3, 0x83, 0xeb, 0xbd, 0x2d, 0xe9, 0x58, 0xa6, 0x37, 0x17, 0x93, 0xef, 0xa1, 0x5e, 0x67, 0xc4, 0x0f, 0x43, 0xa4, 0x76, 0xc9, 0x55, 0x20, 0x49, 0x06, 0xdf, 0xb1, 0x1a, 0x8d, 0x9a, 0xb7, 0x17, 0x02, 0x1a, 0x7d, 0x03, 0x7a, 0x7c, 0x64, 0x1f, 0xba, 0x51, 0x86, 0xa0, 0xfe, 0x9d, 0x81, 0x62, 0xbe, 0xdc, 0xa9, 0x88, 0x49, 0xee, 0xc0, 0xd1, 0xfc, 0x26, 0xb5, 0x1b, 0x8d, 0x13, 0xc9, 0x6b, 0x4e, 0xe2, 0x30, 0x47, 0xde, 0xf4, 0x8e, 0xd4, 0x11, 0xfb, 0x17, 0x3c, 0x28, 0xac, 0x83, 0x48, 0x71, 0x4c, 0x59, 0x4c, 0x64, 0xf2, 0x64, 0xc6, 0xac, 0xea, 0x03, 0xa3, 0xaf, 0x4b, 0xbd, 0x6a, 0xf8, 0xa4, 0x2a, 0x83, 0x6a, 0x93, 0xce, 0xe6, 0x65, 0x8c, 0x5d, 0x89, 0x21, 0x0b, 0x35, 0x95, 0x6c, 0x91, 0x38, 0x70, 0x70, 0x65, 0x2d, 0xa5, 0x65, 0xba, 0xee, 0xc6, 0xa0, 0xd3, 0x2e, 0xef, 0xae, 0xbd, 0xae, 0x3d, 0x46, 0x0a, 0xbd, 0x5f, 0x04, 0x15, 0xf4, 0x27, 0x9a, 0x10, 0xef, 0x9a, 0x44, 0xa5, 0xb6, 0x41, 0x08, 0x29, 0xfd, 0x2f, 0x88, 0x40, 0x92, 0xbc, 0x2e, 0xfd, 0x14, 0xd4, 0x63, 0x77, 0xa9, 0x68, 0x67, 0x0f, 0x18, 0x01, 0xca]; +pub global CHATGPT_CA_MODULUS: [u8; 256] = [0xc1, 0x16, 0x12, 0xc3, 0xa7, 0x50, 0xc1, 0x98, 0xcc, 0xce, 0x6b, 0xf8, 0x8e, 0xa4, 0xf1, 0xc5, 0x6a, 0xfa, 0x72, 0x96, 0x88, 0xd8, 0x05, 0x33, 0xfb, 0x8a, 0xec, 0x82, 0xf2, 0x65, 0x80, 0xe7, 0x41, 0x9c, 0x9a, 0xc4, 0xe1, 0x60, 0x15, 0xc7, 0x04, 0xe8, 0x28, 0x6b, 0xf5, 0xc7, 0xda, 0xde, 0x0a, 0x8a, 0x22, 0xfa, 0xc5, 0xa7, 0xa3, 0xf6, 0x0a, 0x28, 0xfe, 0x07, 0x62, 0x3b, 0x0a, 0xcb, 0x09, 0x79, 0x65, 0x79, 0x0e, 0x58, 0x9a, 0x94, 0x3c, 0x96, 0x2f, 0x2f, 0x62, 0xd5, 0x16, 0x58, 0xcc, 0x8a, 0xa8, 0x97, 0xca, 0x48, 0x90, 0x02, 0x59, 0xeb, 0x08, 0x36, 0xe7, 0xaf, 0x2f, 0xa5, 0x3d, 0xfb, 0x7f, 0x93, 0xef, 0x77, 0xb1, 0xbe, 0xe8, 0x7a, 0x38, 0xf8, 0x14, 0x1e, 0x44, 0x17, 0x50, 0x68, 0xe1, 0xf9, 0x67, 0xa9, 0x17, 0x49, 0xf5, 0xbf, 0x4d, 0xca, 0xfb, 0xf6, 0xbc, 0x81, 0xa1, 0x9f, 0x64, 0x48, 0xe1, 0x58, 0x08, 0x7a, 0x5c, 0xab, 0x7a, 0x41, 0xfb, 0x86, 0x86, 0x3a, 0x01, 0xa1, 0xee, 0xa6, 0x72, 0xde, 0x20, 0xa2, 0xdd, 0xc2, 0xa8, 0x51, 0x35, 0x9d, 0x8c, 0x97, 0xab, 0x72, 0x74, 0x32, 0xf9, 0x13, 0x9b, 0x9b, 0xfa, 0xbb, 0x59, 0xfd, 0xd4, 0xd8, 0x57, 0x4c, 0xc8, 0xad, 0xef, 0xa1, 0x71, 0x1f, 0x85, 0x6c, 0x1f, 0xe7, 0xd8, 0x1d, 0xf0, 0xbd, 0x2a, 0xe4, 0x34, 0x66, 0x88, 0xbe, 0x99, 0x13, 0xb0, 0x7d, 0xb1, 0xdf, 0x61, 0x6d, 0xcd, 0xbe, 0x6e, 0xd6, 0xf3, 0xdf, 0xe8, 0x33, 0x17, 0x53, 0x2a, 0xff, 0x03, 0x75, 0x96, 0xa3, 0x9a, 0xdb, 0xe7, 0x16, 0x2a, 0x91, 0x1d, 0x18, 0xc7, 0x4b, 0xb6, 0x03, 0x11, 0x54, 0xd6, 0xf3, 0x99, 0xc6, 0x71, 0x8b, 0x93, 0xbe, 0x70, 0x52, 0xb9, 0x12, 0xe5, 0xc6, 0x85, 0x7d, 0x68, 0x18, 0xc1, 0x02, 0xb2, 0x6f]; +pub global CHATGPT_CA_REDC: [u128; 18] = [0x9c2353ca8f855dd407978ff7e3b951, 0x1360c8f58aa2f8829be62e03952870, 0x57223bb7d90eace2fe03db6caee753, 0x26049fccd11a9f489a42c98fc8ff23, 0x459b5798e253298220661633a16851, 0xac0df7fbd2aad351a8647da6d7177b, 0xcb4d0ef82f600fc1eaf2c555a49d82, 0x9de003570e3e815e635a7248e23217, 0x22b6eeb9a14bc83fa8b17952fd6523, 0x241ec3b8f7d6104a0b73052fd30740, 0xf7f13327d58a4f3bc958b93323c02f, 0xb861c8f4a323039244a0e03991aa67, 0x7507ce5f864ea6be1ffdc0e4775ff, 0xfeb78214c4aaa79330191d8e0bd912, 0xdcb4f43fd8d0247039a268b549cb99, 0x3726a65c1e9138084d0c42c058d05c, 0x70c1ca5f464677ba16e025c5bacc75, 0x54da]; diff --git a/proof_a_rsa_2048_sha384_v2/src/hash_chain.nr b/proof_a_rsa_2048_sha384_v2/src/hash_chain.nr new file mode 100644 index 0000000..d7fe6d5 --- /dev/null +++ b/proof_a_rsa_2048_sha384_v2/src/hash_chain.nr @@ -0,0 +1,548 @@ +/** + * Hash Chain Verification for Trustless Metadata Binding + * + * This module verifies that extracted metadata values (GPS, timestamp) actually + * came from the signed C2PA claim, preventing substitution attacks. + * + * The verification chain: + * 1. COSE Signature -> COSE Payload (which is claim_hash or claim_bytes) + * 2. SHA256(claim_bytes) -> claim_hash (verified via signature) + * 3. claim_bytes contains assertion_hash at known offset + * 4. SHA256(assertion_bytes) == assertion_hash + * 5. assertion_bytes contain the metadata values at known offsets + * + * Without this verification, a malicious client could: + * - Extract real GPS from signed image + * - Replace with fake GPS + * - Generate valid proof with fake location + * + * With hash chain verification, the circuit ensures: + * - The metadata values are cryptographically bound to the signature + * - Substitution of any value invalidates the proof + * + * CONSTRAINT BUDGET: + * - SHA256 in Noir: ~15k constraints per KB hashed + * - Claim bytes: typically 1-5 KB -> 15-75k constraints + * - Assertion bytes: typically 200B-2KB -> 3-30k constraints + * - Total budget: ~100k constraints for hash chain + * + * OPTIMIZATION STRATEGIES: + * 1. Use pre-computed claim_hash when claim is large (skip in-circuit hashing) + * 2. Only verify assertion hash for assertions containing sensitive data + * 3. For small claims/assertions, in-circuit SHA256 is acceptable + */ + +// SHA256 from stdlib - use digest function with generic size parameter + +/// Maximum size of claim bytes we'll hash in-circuit +/// Claims larger than this should use the pre-computed hash approach +/// RESTORED to 2048 for full cryptographic hash chain verification +/// ProofMode claims are ~1299 bytes, so 2048 provides sufficient headroom +pub global MAX_CLAIM_SIZE: u32 = 2048; + +/// Maximum size of EXIF assertion bytes we'll hash in-circuit +/// RESTORED to 1024 for full assertion hash verification +pub global MAX_EXIF_ASSERTION_SIZE: u32 = 1024; + +/// Maximum size of c2pa.actions assertion bytes we'll hash in-circuit +/// Actions assertions contain edit history (c2pa.created, c2pa.edited, etc.) +/// and AI generation indicators (digitalSourceType: trainedAlgorithmicMedia) +/// NOTE: Adobe Photoshop actions assertions can be 1200-1500 bytes, so 2048 provides headroom +pub global MAX_ACTIONS_ASSERTION_SIZE: u32 = 2048; + +/// SHA256 hash output size +pub global HASH_SIZE: u32 = 32; + +/** + * Verify that claim_hash matches SHA256(claim_bytes) + * + * This binds the claim content to the signature. + * The signature verifies over claim_hash, so if this passes, + * we know claim_bytes are authentic. + * + * IMPORTANT: Uses sha256_var to hash only the first claim_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * claim bytes, not the padded version. + * + * @param claim_bytes Raw CBOR claim bytes (padded to MAX_CLAIM_SIZE) + * @param claim_length Actual length of claim bytes + * @param expected_claim_hash Pre-computed SHA256(claim_bytes) - same as signature input + */ +pub fn verify_claim_hash( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32] +) { + // Bounds check: claim_length must not exceed buffer size + assert(claim_length <= MAX_CLAIM_SIZE, "claim_length exceeds MAX_CLAIM_SIZE"); + + // Compute SHA256 of the ACTUAL claim bytes (not padded) + // sha256_var hashes only the first claim_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(claim_bytes, claim_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_claim_hash[i], + "Claim hash verification failed: claim_bytes do not match expected hash" + ); + } +} + +/** + * Extract assertion hash from claim_bytes at a known offset + * + * The claim contains references to assertions with their expected hashes. + * This function extracts the 32-byte hash at the specified offset. + * + * @param claim_bytes Raw CBOR claim bytes + * @param hash_offset Byte offset where assertion hash appears in claim + * @returns The 32-byte assertion hash from the claim + */ +pub fn extract_assertion_hash_from_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + hash_offset: u32 +) -> [u8; 32] { + let mut assertion_hash: [u8; 32] = [0; 32]; + + // Bounds check + assert( + hash_offset + 32 <= MAX_CLAIM_SIZE, + "Assertion hash offset out of bounds" + ); + + // Extract 32 bytes starting at hash_offset + for i in 0..32 { + assertion_hash[i] = claim_bytes[hash_offset + i]; + } + + assertion_hash +} + +/** + * Verify that assertion_hash matches SHA256(assertion_bytes) + * + * This binds the assertion content to the claim. + * Combined with verify_claim_hash, this creates a complete chain: + * Signature -> Claim -> Assertion -> Metadata + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR or JSON, padded) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_assertion_hash( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_EXIF_ASSERTION_SIZE, "assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Extract a u64 timestamp value from CBOR-encoded assertion bytes + * + * CBOR timestamp encoding (simplified): + * - For small values (0-23): single byte 0x00-0x17 + * - For u8: 0x18 + 1 byte + * - For u16: 0x19 + 2 bytes (big-endian) + * - For u32: 0x1a + 4 bytes (big-endian) + * - For u64: 0x1b + 8 bytes (big-endian) + * + * We extract the raw bytes and convert to u64. + * The offset should point to the START of the CBOR value (type byte). + * + * @param assertion_bytes Raw assertion bytes + * @param timestamp_offset Byte offset where timestamp CBOR value starts + * @returns Extracted timestamp as u64 + */ +pub fn extract_timestamp_from_cbor( + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + timestamp_offset: u32 +) -> u64 { + let type_byte = assertion_bytes[timestamp_offset]; + + // Check CBOR type - we expect unsigned integer (major type 0) + let major_type = type_byte >> 5; + let additional_info = type_byte & 0x1f; + + // Major type 0 = unsigned integer + assert(major_type == 0, "Expected CBOR unsigned integer for timestamp"); + + let mut timestamp: u64 = 0; + + if additional_info <= 23 { + // Inline value + timestamp = additional_info as u64; + } else if additional_info == 24 { + // u8 follows - need 2 bytes total + assert(timestamp_offset + 2 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u8 timestamp exceeds buffer"); + timestamp = assertion_bytes[timestamp_offset + 1] as u64; + } else if additional_info == 25 { + // u16 follows (big-endian) - need 3 bytes total + assert(timestamp_offset + 3 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u16 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 2] as u64); + } else if additional_info == 26 { + // u32 follows (big-endian) - need 5 bytes total + assert(timestamp_offset + 5 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u32 timestamp exceeds buffer"); + timestamp = (assertion_bytes[timestamp_offset + 1] as u64) << 24; + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 2] as u64) << 16); + timestamp = timestamp + ((assertion_bytes[timestamp_offset + 3] as u64) << 8); + timestamp = timestamp + (assertion_bytes[timestamp_offset + 4] as u64); + } else if additional_info == 27 { + // u64 follows (big-endian) - need 9 bytes total + assert(timestamp_offset + 9 <= MAX_EXIF_ASSERTION_SIZE as u32, "CBOR u64 timestamp exceeds buffer"); + for i in 0..8 { + timestamp = timestamp << 8; + timestamp = timestamp + (assertion_bytes[timestamp_offset + 1 + i] as u64); + } + } else { + // additional_info 28-30 are reserved per CBOR RFC 8949, 31 is indefinite-length + assert(false, "Reserved or unsupported CBOR integer encoding for timestamp"); + } + + timestamp +} + +/** + * GPS BINDING SECURITY MODEL + * ========================== + * + * This module does NOT implement byte-level GPS extraction from CBOR assertions. + * This is a deliberate design choice, not a missing feature. + * + * SECURITY RATIONALE: + * ------------------- + * GPS coordinates are cryptographically bound through the hash chain: + * + * 1. verify_assertion_hash() proves: SHA256(assertion_bytes) == hash_in_claim + * 2. verify_claim_hash() proves: SHA256(claim_bytes) == signed_hash + * 3. COSE signature proves: claim was signed by trusted certificate + * + * Therefore, if the assertion bytes pass hash verification, their ENTIRE CONTENT + * is cryptographically bound to the signature. Any modification to the GPS values + * would change the hash and break verification. + * + * WHY NOT PARSE CBOR IN-CIRCUIT? + * ------------------------------ + * C2PA EXIF GPS coordinates are stored as CBOR rational number arrays: + * { "EXIF:GPSLatitude": [{n: 51, d: 1}, {n: 30, d: 1}, {n: 0, d: 1}] } // 51d 30m 0s + * + * Parsing this requires: + * - Variable-length CBOR decoding (~200+ constraints per value) + * - Rational number arithmetic (degree + minute/60 + second/3600) + * - Sign handling from GPSLatitudeRef/GPSLongitudeRef strings + * + * Total cost: ~500-1000 additional constraints for minimal security gain. + * + * The hash chain already guarantees that the client cannot substitute GPS values + * without invalidating the proof. Adding in-circuit parsing would only catch + * bugs in the client extractor, not malicious tampering. + * + * TRUST MODEL: + * ------------ + * - The CIRCUIT trusts that assertion_bytes were correctly passed from the client + * - The HASH CHAIN proves assertion_bytes match what was signed + * - The CLIENT extracts GPS from the verified bytes + * - Any GPS tampering would require finding a hash collision (computationally infeasible) + * + * For applications requiring stronger guarantees, the circuit could be extended + * to parse CBOR at specific known offsets. This is left as a future enhancement. + */ + +// NOTE: verify_gps_binding() has been intentionally removed. +// GPS binding is provided by verify_assertion_hash() in the hash chain. +// See the SECURITY RATIONALE above for details. + +/** + * Combined hash chain verification + * + * Performs the complete verification: + * 1. SHA256(claim_bytes) == expected_claim_hash (signature input) + * 2. Extract assertion_hash from claim at known offset + * 3. SHA256(assertion_bytes) == assertion_hash + * + * If all pass, we know the assertion_bytes are authentic and + * any values extracted from them are cryptographically bound to the signature. + * + * @param claim_bytes Raw claim bytes (padded) + * @param claim_length Actual claim length + * @param expected_claim_hash SHA256 of claim (same as signature message hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes (padded) + * @param assertion_length Actual assertion length + */ +pub fn verify_full_hash_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Step 1: Verify claim hash + verify_claim_hash(claim_bytes, claim_length, expected_claim_hash); + + // Step 2: Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Step 3: Verify assertion hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // At this point, we've proven: + // - claim_bytes hash to the signed value + // - assertion_bytes hash to a reference in the signed claim + // - Therefore, assertion_bytes are authentic + // - Any values in assertion_bytes are cryptographically bound + + // Silence unused warnings + let _ = claim_length; + let _ = assertion_length; +} + +/** + * Verify timestamp is bound to assertion via hash chain + * + * Combines hash chain verification with timestamp extraction. + * Proves that exact_timestamp actually came from the signed assertion. + * + * @param claim_bytes Raw claim bytes + * @param claim_length Actual claim length + * @param expected_claim_hash Expected claim hash (signature input) + * @param assertion_hash_offset Offset of assertion hash in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + * @param timestamp_offset Offset of timestamp in assertion + * @param expected_timestamp The timestamp value the circuit is using + */ +pub fn verify_timestamp_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + expected_claim_hash: [u8; 32], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32, + timestamp_offset: u32, + expected_timestamp: u64 +) { + // First verify the hash chain + verify_full_hash_chain( + claim_bytes, + claim_length, + expected_claim_hash, + assertion_hash_offset, + assertion_bytes, + assertion_length + ); + + // Then extract and verify the timestamp + let extracted_timestamp = extract_timestamp_from_cbor(assertion_bytes, timestamp_offset); + + assert( + extracted_timestamp == expected_timestamp, + "Timestamp binding failed: extracted timestamp does not match expected value" + ); +} + +/** + * Verify content hash exists in claim at specified offset + * + * SECURITY: This binds the public content_hash to the signed claim. + * Without this verification, a malicious client could substitute + * a different image's content_hash while keeping the valid signature. + * + * @param claim_bytes Raw claim bytes (CBOR encoded) + * @param content_hash_offset Byte offset where content hash appears in claim + * @param expected_content_hash The content hash (Field) to verify + */ +pub fn verify_content_hash_in_claim( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + // Bounds check + assert( + content_hash_offset + 32 <= MAX_CLAIM_SIZE, + "Content hash offset out of bounds" + ); + + // Extract 32 bytes from claim at offset and convert to Field + let mut extracted_hash: Field = 0; + for i in 0..32 { + extracted_hash = extracted_hash * 256 + claim_bytes[content_hash_offset + i] as Field; + } + + // Verify the extracted content hash matches the public input + assert( + extracted_hash == expected_content_hash, + "Content hash binding failed: public content_hash does not match value in signed claim" + ); +} + +/** + * Verify assertion hash chain (without redundant claim hash check) + * + * Use this when claim_hash has already been verified separately. + * Verifies: SHA256(assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw assertion bytes + * @param assertion_length Actual assertion length + */ +pub fn verify_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_assertion_hash(assertion_bytes, assertion_length, assertion_hash); + + // Silence unused warning + let _ = assertion_length; +} + +/** + * Verify actions assertion hash matches SHA256(actions_assertion_bytes) + * + * This is the same as verify_assertion_hash but for the larger actions buffer. + * Actions assertions (c2pa.actions.v2) can be up to 2048 bytes (Adobe Photoshop). + * + * IMPORTANT: Uses sha256_var to hash only the first assertion_length bytes, + * not the full padded array. The expected hash is SHA256 of the actual + * assertion bytes, not the padded version. + * + * @param assertion_bytes Raw assertion bytes (CBOR, padded to MAX_ACTIONS_ASSERTION_SIZE) + * @param assertion_length Actual length of assertion bytes + * @param expected_hash Hash extracted from claim's assertion reference + */ +pub fn verify_actions_assertion_hash( + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32, + expected_hash: [u8; 32] +) { + // Bounds check: assertion_length must not exceed buffer size + assert(assertion_length <= MAX_ACTIONS_ASSERTION_SIZE, "actions_assertion_length exceeds buffer"); + + // Compute SHA256 of the ACTUAL assertion bytes (not padded) + // sha256_var hashes only the first assertion_length bytes + let computed_hash: [u8; 32] = dep::sha256::sha256_var(assertion_bytes, assertion_length as u32); + + // Verify match + for i in 0..32 { + assert( + computed_hash[i] == expected_hash[i], + "Actions assertion hash verification failed: assertion_bytes do not match expected hash" + ); + } +} + +/** + * Verify actions assertion hash chain (without redundant claim hash check) + * + * Use this for c2pa.actions.v2 assertions which can be up to 2048 bytes. + * Verifies: SHA256(actions_assertion_bytes) == hash in claim at offset + * + * @param claim_bytes Raw claim bytes (already verified via claim_hash) + * @param assertion_hash_offset Where assertion hash appears in claim + * @param assertion_bytes Raw actions assertion bytes (up to 2048 bytes) + * @param assertion_length Actual assertion length + */ +pub fn verify_actions_assertion_chain( + claim_bytes: [u8; MAX_CLAIM_SIZE], + assertion_hash_offset: u32, + assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + assertion_length: u32 +) { + // Extract assertion hash from claim + let assertion_hash = extract_assertion_hash_from_claim(claim_bytes, assertion_hash_offset); + + // Verify assertion bytes hash to the expected hash + verify_actions_assertion_hash(assertion_bytes, assertion_length, assertion_hash); +} + +// Tests +#[test] +fn test_content_hash_binding() { + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a known content hash at offset 100 + // Content hash as bytes: 0x0000...0001 (just 1 for simplicity) + claim_bytes[131] = 1; // Last byte = 1 + + // Expected field value is 1 + let expected_hash: Field = 1; + + // This should pass + verify_content_hash_in_claim(claim_bytes, 100, expected_hash); +} + +#[test] +fn test_extract_assertion_hash() { + // Create test claim bytes with a known hash at offset 10 + let mut claim_bytes: [u8; MAX_CLAIM_SIZE] = [0; MAX_CLAIM_SIZE]; + + // Place a test hash at offset 10 + let test_hash: [u8; 32] = [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 + ]; + + for i in 0..32 { + claim_bytes[10 + i] = test_hash[i]; + } + + let extracted = extract_assertion_hash_from_claim(claim_bytes, 10); + + for i in 0..32 { + assert(extracted[i] == test_hash[i]); + } +} + +#[test] +fn test_extract_cbor_timestamp_inline() { + // Test inline value (0-23) + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x17; // Inline value 23 + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 23); +} + +#[test] +fn test_extract_cbor_timestamp_u32() { + // Test u32 value + let mut assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE] = [0; MAX_EXIF_ASSERTION_SIZE]; + assertion_bytes[0] = 0x1a; // u32 follows + // Value: 1700000000 (0x6553F100) - a Unix timestamp + assertion_bytes[1] = 0x65; + assertion_bytes[2] = 0x53; + assertion_bytes[3] = 0xF1; + assertion_bytes[4] = 0x00; + + let timestamp = extract_timestamp_from_cbor(assertion_bytes, 0); + assert(timestamp == 1700000000); +} diff --git a/proof_a_rsa_2048_sha384_v2/src/main.nr b/proof_a_rsa_2048_sha384_v2/src/main.nr new file mode 100644 index 0000000..eb17995 --- /dev/null +++ b/proof_a_rsa_2048_sha384_v2/src/main.nr @@ -0,0 +1,677 @@ +/// Apertrue ProofA RSA-2048 SHA-384 v2 - Certificate Chain Verification +/// +/// For a leaf certificate issued by an RSA-2048 intermediate that signs with +/// sha384WithRSAEncryption (PKCS#1 v1.5, e = 65537), such as the Truepic +/// WebClaimSigningCA behind ChatGPT images. The leaf key may be uncompressed +/// P-256 (pair with proof_b_es256_v2*) or RSA-2048/65537 (pair with +/// proof_b_ps256_v2). The key type is read from the leaf SPKI DER. +/// +/// Identical to proof_a_rsa_2048_v2 except for the digest: the full leaf +/// TBSCertificate is hashed with SHA-384, its signature algorithm must be +/// sha384WithRSAEncryption (cert_binding::bind_leaf_cert_rsa_signed_sha384), +/// and the intermediate's signature is verified over that SHA-384. +/// intermediate_leaf = cert_binding::rsa_key_hash over all 18 modulus limbs. +/// +/// This circuit proves: +/// 1. The intermediate CA signed (RSA-2048, SHA-384) the leaf TBSCertificate +/// 2. The intermediate CA is in the Oracle's promoted trust list (Merkle membership) +/// 3. The nullifier is derived from the leaf key found in that TBSCertificate +/// 4. proof_timestamp lies within that certificate's validity (dates private) +/// 5. Time range proof (graduated time disclosure) +/// 6. Location range proof (privacy circles) +/// 7. Hash chain verification (claim and assertion integrity) +/// 8. Poseidon commitments for optional future reveal +/// +/// Supported leaf: TBS <= 1280 B. Claim/assertion size classes as +/// proof_a_rsa_2048_v2 (claim 2048, exif 1024, actions 2048). +/// +/// PUBLIC LAYOUT (index: name; one Field each unless noted) +/// 0 trust_list_root +/// 1 content_hash +/// 2 nullifier pedersen_hash([content_hash, leaf_key_hash]) +/// 3 proof_timestamp +/// 4 time_min +/// 5 time_max +/// 6 edit_time_min +/// 7 edit_time_max +/// 8 center_lat_scaled +/// 9 center_lon_scaled +/// 10 location_flags +/// 11 radius_squared_scaled +/// 12 claim_hash_commitment +/// 13 content_hash_offset +/// 14 skip_content_hash_binding +/// 15 skip_assertion_hash_verification +/// Return values: +/// 16 link_commit pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]) +/// 17 location_commitment +/// 18 time_commitment +/// 19 edit_time_commitment +/// 20..51 actions_assertion_hash (32 x u8) +/// Total 52. Versus v1: cert_not_before (4), cert_not_after (5) and +/// tbs_hash_commitment (14) are removed; every later index shifts down. +/// +/// Shared with ProofB v2 (must be equal across the pair): trust_list_root, +/// content_hash, nullifier, proof_timestamp, claim_hash_commitment, +/// content_hash_offset, link_commit. + +use bignum::params::BigNumParams; +use noir_rsa::rsa::verify_sha384_pkcs1v15; +use std::hash::pedersen_hash; +use dep::poseidon::poseidon2::Poseidon2; +use dep::cert_binding::{bind_leaf_cert_rsa_signed_sha384, be_bytes_to_limbs, rsa_key_hash, LeafCertAnyKeySha384}; + +mod hash_chain; + +use hash_chain::{ + MAX_CLAIM_SIZE, + MAX_EXIF_ASSERTION_SIZE, + MAX_ACTIONS_ASSERTION_SIZE, + verify_claim_hash, + verify_content_hash_in_claim, + verify_assertion_chain, + verify_actions_assertion_chain, +}; + +/// Maximum leaf TBSCertificate size (DER bytes) +global MAX_TBS_SIZE: u32 = 1280; + +/// RSA-2048 uses 18 limbs of 120 bits +global RSA_NUM_LIMBS: u32 = 18; + +/// ProofA RSA-2048 v2 main entry point +fn main( + // === PUBLIC INPUTS (shared with ProofB) === + trust_list_root: pub Field, + content_hash: pub Field, + nullifier: pub Field, + proof_timestamp: pub Field, + + // === PUBLIC INPUTS: TIME RANGE BOUNDS (for graduated time disclosure) === + time_min: pub Field, + time_max: pub Field, + + // === PUBLIC INPUTS: EDIT TIME RANGE BOUNDS (for edited images) === + // When a photo is edited (e.g., Leica capture -> Lightroom export), the capture + // and edit timestamps differ. These bounds constrain the edit/signing timestamp. + // Set to 0 when no edit occurred (direct camera capture). + edit_time_min: pub Field, // Minimum edit timestamp bound (0 if no edit) + edit_time_max: pub Field, // Maximum edit timestamp bound (0 if no edit) + + // === PUBLIC INPUTS: LOCATION PRIVACY CIRCLE (for graduated location disclosure) === + center_lat_scaled: pub Field, + center_lon_scaled: pub Field, + location_flags: pub u8, // bit 0 = lat negative (South), bit 1 = lon negative (West) + radius_squared_scaled: pub Field, + + // === PUBLIC INPUT: Claim Hash Commitment (packed from 32 bytes to 1 Field) === + // This is Poseidon2(bytes32_to_field_array(claim_hash)). Saves 31 public input fields. + claim_hash_commitment: pub Field, + + // === PUBLIC INPUT: Content Hash Offset (for content binding) === + content_hash_offset: pub u32, + + // === PRIVATE: LEAF TBSCertificate (DER, zero padded past tbs_len) === + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + + // === PRIVATE: CLAIM HASH BYTES (unpacked from commitment) === + claim_hash: [u8; 32], + + // === PRIVATE: SKIP FLAGS === + skip_content_hash_binding: pub u8, + skip_assertion_hash_verification: pub u8, + + // === PRIVATE: RSA-2048 CERTIFICATE SIGNATURE & KEY (big-endian bytes) === + cert_signature_rsa: [u8; 256], + intermediate_rsa_modulus: [u8; 256], + intermediate_rsa_redc_limbs: [u128; RSA_NUM_LIMBS], // floor(2^(2*2048+6) / n) + + // === PRIVATE: LINKING WITNESS === + intermediate_leaf: Field, + link_blind: Field, + + // === PRIVATE: MERKLE MEMBERSHIP (trust list verification) === + merkle_path: [Field; 8], + merkle_indices: [Field; 8], + + // === PRIVATE: EXACT TIMESTAMP (for time range proof) === + exact_timestamp: Field, + + // === PRIVATE: EXACT GPS LOCATION (for location range proof) === + exact_lat_scaled: Field, + exact_lon_scaled: Field, + exact_lat_is_negative: u8, + exact_lon_is_negative: u8, + + // === PRIVATE: HASH CHAIN DATA === + enable_hash_chain_verification: u8, + claim_bytes: [u8; MAX_CLAIM_SIZE], + claim_length: u32, + exif_assertion_hash_offset: u32, + exif_assertion_bytes: [u8; MAX_EXIF_ASSERTION_SIZE], + exif_assertion_length: u32, + + // === PRIVATE: ACTIONS ASSERTION === + actions_assertion_hash_offset: u32, + actions_assertion_bytes: [u8; MAX_ACTIONS_ASSERTION_SIZE], + actions_assertion_length: u32, + + // === PRIVATE: COMMITMENT SALTS === + location_salt: Field, + time_salt: Field, + + // === PRIVATE: EDIT TIMESTAMP & SALT (for separate edit time commitment) === + exact_edit_timestamp: Field, // Edit/signing timestamp (0 if no edit) + edit_time_salt: Field // Salt for edit time commitment +) -> pub (Field, Field, Field, Field, [u8; 32]) { // Returns (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) + // ================================================================ + // STEP 0: Verify claim hash commitment packing + // ================================================================ + let computed_claim_commitment = Poseidon2::hash(bytes32_to_field_array(claim_hash), 2); + assert(computed_claim_commitment == claim_hash_commitment, "Claim hash commitment mismatch"); + + // ================================================================ + // STEP 1: Hash + DER-walk the leaf TBS; intermediate signs that hash + // ================================================================ + let leaf = verify_leaf_certificate( + tbs_certificate, + tbs_len, + cert_signature_rsa, + intermediate_rsa_modulus, + intermediate_rsa_redc_limbs + ); + + // ================================================================ + // STEP 2: Derive Leaf Key Hash (key taken from the signed TBS) + // ================================================================ + // P-256: pedersen_hash([x, y]); RSA-2048: rsa_key_hash (18 limbs) + let computed_leaf_key_hash = leaf.key_hash; + + // ================================================================ + // STEP 3: Verify Nullifier Derivation + // ================================================================ + let expected_nullifier = pedersen_hash([content_hash, computed_leaf_key_hash]); + assert(nullifier == expected_nullifier, "Invalid nullifier (leaf key binding failed)"); + + // ================================================================ + // STEP 4: Compute Link Commitment (returned as output) + // ================================================================ + let claim_hash_field = bytes_to_field(claim_hash); + let link_commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + + // ================================================================ + // STEP 4b: Verify Intermediate Leaf Formulation + // ================================================================ + let computed_intermediate_hash = rsa_key_hash::<256, 18>(intermediate_rsa_modulus); + + assert( + intermediate_leaf == computed_intermediate_hash, + "Intermediate Leaf witnessing mismatch (Self-Signing Attack prevention)" + ); + + // ================================================================ + // STEP 4c: Merkle Membership (Trust List Verification) + // ================================================================ + let computed_root = compute_merkle_root(intermediate_leaf, merkle_path, merkle_indices); + assert(computed_root == trust_list_root, "Intermediate CA not in trust list"); + + // ================================================================ + // STEP 5: Certificate Validity (Time) + // ================================================================ + // Dates come from the signed TBS and stay private. + assert(proof_timestamp as u64 as Field == proof_timestamp, "proof_timestamp exceeds u64"); + let ts = proof_timestamp as u64; + let not_before = leaf.not_before; + let not_after = leaf.not_after; + assert(ts >= not_before, "Certificate not yet valid at proof time"); + assert(ts <= not_after, "Certificate expired at proof time"); + + // ================================================================ + // STEP 6: Time Range Proof (Graduated Time Disclosure) + // ================================================================ + assert(exact_timestamp as u64 as Field == exact_timestamp, "exact_timestamp exceeds u64"); + assert(time_min as u64 as Field == time_min, "time_min exceeds u64"); + assert(time_max as u64 as Field == time_max, "time_max exceeds u64"); + let exact_ts = exact_timestamp as u64; + let min_ts = time_min as u64; + let max_ts = time_max as u64; + + assert(exact_ts >= min_ts, "Exact timestamp is before disclosed time_min"); + assert(exact_ts <= max_ts, "Exact timestamp is after disclosed time_max"); + + // ================================================================ + // STEP 6b: Edit Time Range Proof (0 = no edit, skip) + // ================================================================ + // When a photo is edited (capture -> export), exact_edit_timestamp is the + // signing/export time. For direct camera captures, it's 0 (sentinel). + if exact_edit_timestamp != 0 { + assert(exact_edit_timestamp as u64 as Field == exact_edit_timestamp, "exact_edit_timestamp exceeds u64"); + assert(edit_time_min as u64 as Field == edit_time_min, "edit_time_min exceeds u64"); + assert(edit_time_max as u64 as Field == edit_time_max, "edit_time_max exceeds u64"); + let edit_ts = exact_edit_timestamp as u64; + let edit_min = edit_time_min as u64; + let edit_max = edit_time_max as u64; + assert(edit_ts >= edit_min, "Edit timestamp before edit_time_min"); + assert(edit_ts <= edit_max, "Edit timestamp after edit_time_max"); + } else { + assert(edit_time_min == 0, "edit_time_min must be 0 when no edit"); + assert(edit_time_max == 0, "edit_time_max must be 0 when no edit"); + } + + // ================================================================ + // STEP 7: Location Range Proof (Graduated Location Disclosure) + // ================================================================ + // Unpack location_flags: bit 0 = lat negative, bit 1 = lon negative + // Reject if unused high bits (2-7) are set - prevents flag stuffing + assert(location_flags <= 3, "location_flags has invalid high bits set (must be 0-3)"); + let center_lat_is_negative = location_flags & 1; + let center_lon_is_negative = (location_flags >> 1) & 1; + + assert(exact_lat_is_negative <= 1, "exact_lat_is_negative must be 0 or 1"); + assert(exact_lon_is_negative <= 1, "exact_lon_is_negative must be 0 or 1"); + assert(skip_content_hash_binding <= 1, "skip_content_hash_binding must be 0 or 1"); + assert(skip_assertion_hash_verification <= 1, "skip_assertion_hash_verification must be 0 or 1"); + + assert(exact_lat_scaled as u64 as Field == exact_lat_scaled, "exact_lat_scaled exceeds u64"); + assert(center_lat_scaled as u64 as Field == center_lat_scaled, "center_lat_scaled exceeds u64"); + assert(exact_lon_scaled as u64 as Field == exact_lon_scaled, "exact_lon_scaled exceeds u64"); + assert(center_lon_scaled as u64 as Field == center_lon_scaled, "center_lon_scaled exceeds u64"); + + { + let lat_same_sign = (exact_lat_is_negative == center_lat_is_negative); + let d_lat = if lat_same_sign { + if exact_lat_scaled as u64 > center_lat_scaled as u64 { + exact_lat_scaled - center_lat_scaled + } else { + center_lat_scaled - exact_lat_scaled + } + } else { + exact_lat_scaled + center_lat_scaled + }; + + let lon_same_sign = (exact_lon_is_negative == center_lon_is_negative); + let d_lon = if lon_same_sign { + if exact_lon_scaled as u64 > center_lon_scaled as u64 { + exact_lon_scaled - center_lon_scaled + } else { + center_lon_scaled - exact_lon_scaled + } + } else { + exact_lon_scaled + center_lon_scaled + }; + + // NOTE: Euclidean distance in coordinate space. At high latitudes, + // 1 deg lon < 1 deg lat in real-world distance, so this circle is elliptical. + // The client-side radius computation (metersToScaledRadius) compensates + // by using the longitude conversion at the user's latitude, ensuring the + // privacy circle covers at least the requested radius in ALL directions. + let distance_squared = d_lat * d_lat + d_lon * d_lon; + assert(distance_squared as u64 as Field == distance_squared, "distance_squared exceeds u64"); + assert(radius_squared_scaled as u64 as Field == radius_squared_scaled, "radius_squared_scaled exceeds u64"); + + assert( + distance_squared as u64 <= radius_squared_scaled as u64, + "Exact GPS location is outside disclosed privacy circle" + ); + } + + // ================================================================ + // STEP 8: Hash Chain Verification (Trustless Metadata Binding) + // ================================================================ + assert( + enable_hash_chain_verification == 1, + "Hash chain verification must be enabled" + ); + + // Step 8a: Verify claim_hash = SHA256(claim_bytes) + verify_claim_hash(claim_bytes, claim_length, claim_hash); + + // Step 8b: Verify content_hash exists in claim_bytes + if skip_content_hash_binding == 0 { + verify_content_hash_binding(claim_bytes, content_hash_offset, content_hash); + } + + // Step 8c: Verify assertion hash chain + if skip_assertion_hash_verification == 0 { + verify_assertion_chain( + claim_bytes, + exif_assertion_hash_offset, + exif_assertion_bytes, + exif_assertion_length + ); + } + + // Step 8d: Verify actions assertion hash chain (optional) + let actions_assertion_hash: [u8; 32] = if actions_assertion_hash_offset > 0 { + verify_actions_assertion_chain( + claim_bytes, + actions_assertion_hash_offset, + actions_assertion_bytes, + actions_assertion_length + ); + let hash_result: [u8; 32] = dep::sha256::sha256_var( + actions_assertion_bytes, + actions_assertion_length as u32 + ); + hash_result + } else { + [0u8; 32] + }; + + // ================================================================ + // STEP 9: Compute Poseidon Commitments (Optional Future Reveal) + // ================================================================ + let lat_sign_field = exact_lat_is_negative as Field; + let lon_sign_field = exact_lon_is_negative as Field; + + let location_commitment = Poseidon2::hash( + [exact_lat_scaled, exact_lon_scaled, lat_sign_field, lon_sign_field, location_salt], + 5 + ); + + let time_commitment = Poseidon2::hash( + [exact_timestamp, time_salt], + 2 + ); + + // Edit time commitment: Poseidon2([edit_timestamp, salt]) or 0 sentinel + // Poseidon2 never outputs 0 for valid inputs, so 0 is safe as "no edit" sentinel + let edit_time_commitment = if exact_edit_timestamp == 0 { + 0 // Sentinel: no edit happened + } else { + Poseidon2::hash([exact_edit_timestamp, edit_time_salt], 2) + }; + + // Return public outputs + (link_commit, location_commitment, time_commitment, edit_time_commitment, actions_assertion_hash) +} + +/// Hash and DER-walk the leaf TBSCertificate (sha384WithRSAEncryption), +/// then check that the intermediate's RSA-2048 PKCS#1 v1.5 signature covers +/// exactly that SHA-384. +fn verify_leaf_certificate( + tbs_certificate: [u8; MAX_TBS_SIZE], + tbs_len: u32, + sig: [u8; 256], + intermediate_modulus: [u8; 256], + intermediate_redc: [u128; RSA_NUM_LIMBS] +) -> LeafCertAnyKeySha384 { + let leaf = bind_leaf_cert_rsa_signed_sha384(tbs_certificate, tbs_len); + assert(intermediate_modulus[0] >= 0x80, "RSA intermediate modulus is not 2048 bits"); + let limbs: [u128; RSA_NUM_LIMBS] = be_bytes_to_limbs(intermediate_modulus); + let params: BigNumParams = BigNumParams::new(false, limbs, intermediate_redc); + let signature = bignum::RuntimeBigNum::from_be_bytes(params, sig); + let valid = verify_sha384_pkcs1v15(leaf.sha384, signature, 65537); + assert(valid, "RSA-2048 certificate verification failed"); + leaf +} + +/// Convert 32 bytes to Field (big-endian) +fn bytes_to_field(bytes: [u8; 32]) -> Field { + let mut result: Field = 0; + for i in 0..32 { + result = result * 256 + bytes[i] as Field; + } + result +} + +/// Convert 32 bytes to 2 Field elements for Poseidon2 hashing +/// Splits into two 16-byte (128-bit) chunks that fit within the BN254 field +fn bytes32_to_field_array(bytes: [u8; 32]) -> [Field; 2] { + // First 16 bytes -> Field 0 + let mut f0: Field = 0; + for i in 0..16 { + f0 = f0 * 256 + bytes[i] as Field; + } + // Last 16 bytes -> Field 1 + let mut f1: Field = 0; + for i in 16..32 { + f1 = f1 * 256 + bytes[i] as Field; + } + [f0, f1] +} + +/// Verify content hash exists in claim at offset +fn verify_content_hash_binding( + claim_bytes: [u8; MAX_CLAIM_SIZE], + content_hash_offset: u32, + expected_content_hash: Field +) { + verify_content_hash_in_claim(claim_bytes, content_hash_offset, expected_content_hash); +} + +/// Compute Merkle root from leaf and proof +fn compute_merkle_root( + leaf: Field, + path: [Field; 8], + indices: [Field; 8] +) -> Field { + let mut current = leaf; + + for i in 0..8 { + assert((indices[i] == 0) | (indices[i] == 1), "Merkle index must be 0 or 1"); + let path_element = path[i]; + let is_right = indices[i]; + let left = if is_right == 0 { current } else { path_element }; + let right = if is_right == 0 { path_element } else { current }; + current = pedersen_hash([left, right]); + } + + current +} + +// ==================================================================== +// TESTS +// ==================================================================== + +#[test] +fn test_merkle_root_computation() { + let leaf: Field = 12345; + let path: [Field; 8] = [0; 8]; + let indices: [Field; 8] = [0; 8]; + + let root = compute_merkle_root(leaf, path, indices); + assert(root != leaf, "Merkle root should not equal leaf"); + + let root2 = compute_merkle_root(leaf, path, indices); + assert(root == root2, "Merkle root should be deterministic"); +} + +#[test] +fn test_merkle_different_leaves() { + let path: [Field; 8] = [0; 8]; + let indices: [Field; 8] = [0; 8]; + + let root1 = compute_merkle_root(111, path, indices); + let root2 = compute_merkle_root(222, path, indices); + + assert(root1 != root2, "Different leaves should produce different roots"); +} + +#[test] +fn test_time_range_exact_bounds() { + let exact: u64 = 1000; + let min: u64 = 1000; + let max: u64 = 2000; + + assert(exact >= min, "Timestamp at min bound should pass"); + assert(exact <= max, "Timestamp within range should pass"); +} + +#[test] +fn test_location_same_point() { + let exact_lat: Field = 510000000; + let exact_lon: Field = 100000000; + let center_lat: Field = 510000000; + let center_lon: Field = 100000000; + + let d_lat = if exact_lat as u64 > center_lat as u64 { + exact_lat - center_lat + } else { + center_lat - exact_lat + }; + + let d_lon = if exact_lon as u64 > center_lon as u64 { + exact_lon - center_lon + } else { + center_lon - exact_lon + }; + + let distance_squared = d_lat * d_lat + d_lon * d_lon; + assert(distance_squared == 0, "Same point should have zero distance"); +} + +#[test] +fn test_bytes_to_field() { + let mut bytes: [u8; 32] = [0; 32]; + bytes[31] = 1; + let field = bytes_to_field(bytes); + assert(field == 1); + + bytes[31] = 255; + let field2 = bytes_to_field(bytes); + assert(field2 == 255); +} + +#[test] +fn test_nullifier_derivation_ecdsa() { + let content_hash: Field = 111; + let leaf_key_hash: Field = 222; + let nullifier = pedersen_hash([content_hash, leaf_key_hash]); + + let different_content: Field = 333; + let different_nullifier = pedersen_hash([different_content, leaf_key_hash]); + assert(nullifier != different_nullifier); +} + +#[test] +fn test_link_commitment_with_claim_hash() { + let intermediate_leaf: Field = 12345; + let claim_hash_field: Field = 99999; + let link_blind: Field = 67890; + + let commit = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + let commit2 = pedersen_hash([intermediate_leaf, claim_hash_field, link_blind]); + assert(commit == commit2); + + let different_claim: Field = 11111; + let commit3 = pedersen_hash([intermediate_leaf, different_claim, link_blind]); + assert(commit != commit3); +} + +// ==================================================================== +// CERTIFICATE TESTS (real ChatGPT chain: Truepic RSA-2048 CA, sha384WithRSAEncryption) +// ==================================================================== + +mod chatgpt_vectors; + +mod cert_tests { + use super::{verify_leaf_certificate, MAX_TBS_SIZE}; + use super::chatgpt_vectors as cv; + use dep::cert_binding::test_vectors as tv; + use dep::cert_binding::rsa_vectors as rv; + use dep::cert_binding::{bind_leaf_cert_rsa_signed_sha384, p256_key_hash}; + + fn pad(a: [u8; M]) -> [u8; MAX_TBS_SIZE] { + let mut out: [u8; MAX_TBS_SIZE] = [0; MAX_TBS_SIZE]; + for i in 0..M { + out[i] = a[i]; + } + out + } + + #[test] + fn test_chatgpt_leaf_verifies_and_binds_key() { + let leaf = verify_leaf_certificate( + pad(cv::CHATGPT_LEAF_TBS), + cv::CHATGPT_LEAF_TBS_LEN, + cv::CHATGPT_CA_SIG, + cv::CHATGPT_CA_MODULUS, + cv::CHATGPT_CA_REDC, + ); + assert(leaf.key_type == 0); + assert(leaf.key_hash == p256_key_hash(cv::CHATGPT_LEAF_PUB_X, cv::CHATGPT_LEAF_PUB_Y)); + assert(leaf.not_before < leaf.not_after); + } + + // noir_rsa's PKCS#1 v1.5 check fails unlabelled assertions rather than + // returning false, so the negatives use plain should_fail. Each tampered + // TBS has a positive twin showing it still parses, so the failure is the + // CA signature check. + + fn key_swapped() -> [u8; MAX_TBS_SIZE] { + let mut t = pad(cv::CHATGPT_LEAF_TBS); + let mut off: u32 = 0; + for i in 0..400 { + if (off == 0) & (t[i] == 0x30) & (t[i + 1] == 0x59) & (t[i + 2] == 0x30) & (t[i + 3] == 0x13) { + off = i; + } + } + assert(off != 0); + for i in 0..32 { + t[off + 27 + i] = tv::LEICA_LEAF_PUB_X[i]; + t[off + 59 + i] = tv::LEICA_LEAF_PUB_Y[i]; + } + t + } + + #[test] + fn test_key_swapped_tbs_parses_to_other_key() { + let c = bind_leaf_cert_rsa_signed_sha384(key_swapped(), cv::CHATGPT_LEAF_TBS_LEN); + assert(c.key_hash == p256_key_hash(tv::LEICA_LEAF_PUB_X, tv::LEICA_LEAF_PUB_Y)); + } + + #[test(should_fail)] + fn test_substituted_leaf_key_rejected() { + let _ = verify_leaf_certificate(key_swapped(), cv::CHATGPT_LEAF_TBS_LEN, cv::CHATGPT_CA_SIG, cv::CHATGPT_CA_MODULUS, cv::CHATGPT_CA_REDC); + } + + fn date_pushed() -> [u8; MAX_TBS_SIZE] { + // Move the second UTCTime (notAfter) a decade later: year digit +1. + let mut t = pad(cv::CHATGPT_LEAF_TBS); + let mut first: u32 = 0; + let mut second: u32 = 0; + for i in 0..300 { + if (t[i] == 0x17) & (t[i + 1] == 0x0d) { + if first == 0 { + first = i; + } else if second == 0 { + second = i; + } + } + } + assert(second != 0); + t[second + 2] = t[second + 2] + 1; + t + } + + #[test] + fn test_date_pushed_tbs_parses_to_later_date() { + let c = bind_leaf_cert_rsa_signed_sha384(date_pushed(), cv::CHATGPT_LEAF_TBS_LEN); + let real = bind_leaf_cert_rsa_signed_sha384(pad(cv::CHATGPT_LEAF_TBS), cv::CHATGPT_LEAF_TBS_LEN); + assert(c.not_after > real.not_after); + } + + #[test(should_fail)] + fn test_tampered_not_after_rejected() { + let _ = verify_leaf_certificate(date_pushed(), cv::CHATGPT_LEAF_TBS_LEN, cv::CHATGPT_CA_SIG, cv::CHATGPT_CA_MODULUS, cv::CHATGPT_CA_REDC); + } + + #[test(should_fail)] + fn test_sha256_signed_leaf_rejected() { + // A leaf signed sha256WithRSAEncryption must use proof_a_rsa_2048_v2. + let _ = bind_leaf_cert_rsa_signed_sha384(pad(rv::SYN_P256_LEAF_BY_RSA2048_TBS), rv::SYN_P256_LEAF_BY_RSA2048_TBS_LEN); + } + + #[test(should_fail)] + fn test_other_ca_rejected() { + let _ = verify_leaf_certificate( + pad(cv::CHATGPT_LEAF_TBS), + cv::CHATGPT_LEAF_TBS_LEN, + cv::CHATGPT_CA_SIG, + rv::SYN_RSA2048_CA_MODULUS, + rv::SYN_RSA2048_CA_REDC, + ); + } +} From 7f86f4ee435412a0a82c9cd4a992e7e7755d94dd Mon Sep 17 00:00:00 2001 From: Jamie Newton <33573418+newtsjamie@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:50:54 +0000 Subject: [PATCH 7/7] Pin the ChatGPT CA trust-list leaf in a test Co-Authored-By: Claude Opus 5.5 --- proof_a_rsa_2048_sha384_v2/src/main.nr | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/proof_a_rsa_2048_sha384_v2/src/main.nr b/proof_a_rsa_2048_sha384_v2/src/main.nr index eb17995..9eae82f 100644 --- a/proof_a_rsa_2048_sha384_v2/src/main.nr +++ b/proof_a_rsa_2048_sha384_v2/src/main.nr @@ -571,7 +571,7 @@ mod cert_tests { use super::chatgpt_vectors as cv; use dep::cert_binding::test_vectors as tv; use dep::cert_binding::rsa_vectors as rv; - use dep::cert_binding::{bind_leaf_cert_rsa_signed_sha384, p256_key_hash}; + use dep::cert_binding::{bind_leaf_cert_rsa_signed_sha384, p256_key_hash, rsa_key_hash}; fn pad(a: [u8; M]) -> [u8; MAX_TBS_SIZE] { let mut out: [u8; MAX_TBS_SIZE] = [0; MAX_TBS_SIZE]; @@ -595,6 +595,13 @@ mod cert_tests { assert(leaf.not_before < leaf.not_after); } + #[test] + fn test_chatgpt_ca_trust_list_leaf() { + // The trust-list bundle v2 leaf for WebClaimSigningCA. + let leaf = rsa_key_hash::<256, 18>(cv::CHATGPT_CA_MODULUS); + assert(leaf == 0x071fa0bd01954392bc85b9fbe4ae6e750382fe394cfe76322ba9aadec8d772d9); + } + // noir_rsa's PKCS#1 v1.5 check fails unlabelled assertions rather than // returning false, so the negatives use plain should_fail. Each tampered // TBS has a positive twin showing it still parses, so the failure is the