Skip to main content

hoike_sign/
ecdsa_bridge.rs

1//! Bridge between ecdsa 0.17 (signature v3 / spki v0.8) and x509-ocsp
2//! (signature v2 / spki v0.7), mirroring `ml_dsa_bridge.rs`.
3//!
4//! `produce_bundle` and the OCSP response builder require `Signer<Sig> +
5//! DynSignatureAlgorithmIdentifier` from signature v2 / spki v0.7. The p256
6//! 0.14 / ecdsa 0.17 line implements signature v3 traits. This module wraps
7//! the v3 types to satisfy the v2 trait bounds.
8//!
9//! Wire compatibility: the signature is embedded as a DER BIT STRING over the
10//! DER-encoded ECDSA-Sig-Value, and the algorithm identifier is
11//! ecdsa-with-SHA256 (1.2.840.10045.4.3.2) with no parameters — the exact
12//! encoding the PKCS#11 bridge and the previous ecdsa 0.16 native impls
13//! produced.
14
15/// OID for ecdsa-with-SHA256 (RFC 5912 / SEC 2).
16pub const ECDSA_WITH_SHA256_OID: &str = "1.2.840.10045.4.3.2";
17
18/// Wrapper around a software P-256 `SigningKey` implementing the signature
19/// v2 / spki v0.7 trait set `produce_bundle` requires.
20#[derive(Clone)]
21pub struct EcdsaP256Signer {
22    inner: p256::ecdsa::SigningKey,
23}
24
25impl EcdsaP256Signer {
26    pub fn new(inner: p256::ecdsa::SigningKey) -> Self {
27        Self { inner }
28    }
29
30    pub fn verifying_key(&self) -> p256::ecdsa::VerifyingKey {
31        *self.inner.verifying_key()
32    }
33}
34
35impl From<p256::ecdsa::SigningKey> for EcdsaP256Signer {
36    fn from(inner: p256::ecdsa::SigningKey) -> Self {
37        Self::new(inner)
38    }
39}
40
41/// DER-encoded ECDSA-Sig-Value wrapper implementing v2
42/// `SignatureBitStringEncoding`.
43#[derive(Clone)]
44pub struct EcdsaSignatureBytes {
45    der_bytes: Vec<u8>,
46}
47
48impl From<EcdsaSignatureBytes> for Vec<u8> {
49    fn from(sig: EcdsaSignatureBytes) -> Vec<u8> {
50        sig.der_bytes
51    }
52}
53
54impl TryFrom<&[u8]> for EcdsaSignatureBytes {
55    type Error = signature::Error;
56
57    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
58        // Reject inputs that are not a valid DER ECDSA-Sig-Value.
59        p256::ecdsa::DerSignature::from_bytes(bytes).map_err(|_| signature::Error::new())?;
60        Ok(EcdsaSignatureBytes {
61            der_bytes: bytes.to_vec(),
62        })
63    }
64}
65
66impl AsRef<[u8]> for EcdsaSignatureBytes {
67    fn as_ref(&self) -> &[u8] {
68        &self.der_bytes
69    }
70}
71
72// ── signature v2 Signer ──────────────────────────────────────────
73
74impl signature::Signer<EcdsaSignatureBytes> for EcdsaP256Signer {
75    fn try_sign(&self, msg: &[u8]) -> Result<EcdsaSignatureBytes, signature::Error> {
76        // ecdsa 0.17 signs via signature v3 (RFC 6979 deterministic nonces).
77        use p256::ecdsa::signature::Signer as SignerV3;
78        let sig: p256::ecdsa::Signature =
79            SignerV3::try_sign(&self.inner, msg).map_err(|_| signature::Error::new())?;
80        let der = sig.to_der();
81        Ok(EcdsaSignatureBytes {
82            der_bytes: der.as_bytes().to_vec(),
83        })
84    }
85}
86
87// ── signature v2 SignatureEncoding ────────────────────────────────
88
89impl signature::SignatureEncoding for EcdsaSignatureBytes {
90    type Repr = Vec<u8>;
91}
92
93// ── spki v0.7 SignatureBitStringEncoding ──────────────────────────
94
95impl spki::SignatureBitStringEncoding for EcdsaSignatureBytes {
96    fn to_bitstring(&self) -> der::Result<der::asn1::BitString> {
97        der::asn1::BitString::from_bytes(&self.der_bytes)
98    }
99}
100
101// ── spki v0.7 DynSignatureAlgorithmIdentifier ────────────────────
102
103impl spki::DynSignatureAlgorithmIdentifier for EcdsaP256Signer {
104    fn signature_algorithm_identifier(&self) -> spki::Result<spki::AlgorithmIdentifierOwned> {
105        Ok(spki::AlgorithmIdentifierOwned {
106            oid: const_oid::ObjectIdentifier::new_unwrap(ECDSA_WITH_SHA256_OID),
107            parameters: None,
108        })
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use p256::ecdsa::signature::Verifier;
116    use signature::Signer as SignerV2;
117
118    #[test]
119    fn signs_and_verifies_with_p256_key() {
120        let key = p256::ecdsa::SigningKey::from_bytes((&[7u8; 32]).into()).unwrap();
121        let signer = EcdsaP256Signer::new(key.clone());
122        let sig = SignerV2::sign(&signer, b"bridge message");
123        key.verifying_key()
124            .verify(
125                b"bridge message",
126                &p256::ecdsa::DerSignature::from_bytes(sig.as_ref()).unwrap(),
127            )
128            .unwrap();
129    }
130
131    #[test]
132    fn algorithm_identifier_is_ecdsa_with_sha256() {
133        use spki::DynSignatureAlgorithmIdentifier;
134        let signer =
135            EcdsaP256Signer::new(p256::ecdsa::SigningKey::from_bytes((&[1u8; 32]).into()).unwrap());
136        let alg = signer.signature_algorithm_identifier().unwrap();
137        assert_eq!(alg.oid.to_string(), ECDSA_WITH_SHA256_OID);
138        assert!(alg.parameters.is_none());
139    }
140
141    #[test]
142    fn bitstring_wraps_der_bytes() {
143        use signature::Signer;
144        use spki::SignatureBitStringEncoding;
145        let signer =
146            EcdsaP256Signer::new(p256::ecdsa::SigningKey::from_bytes((&[2u8; 32]).into()).unwrap());
147        let sig = signer.sign(b"test");
148        let bits = sig.to_bitstring().unwrap();
149        assert_eq!(bits.raw_bytes(), sig.as_ref());
150        // A DER ECDSA-Sig-Value starts with a SEQUENCE tag.
151        assert_eq!(sig.as_ref()[0], 0x30);
152    }
153
154    #[test]
155    fn rejects_non_der_input() {
156        assert!(EcdsaSignatureBytes::try_from(b"not der".as_slice()).is_err());
157    }
158}