Skip to main content

rings_core/ecc/
mod.rs

1//! ECDSA, EdDSA, and ElGamal
2use std::convert::TryFrom;
3use std::str::FromStr;
4
5use ethereum_types::H160;
6use hex;
7use k256::ecdsa::RecoveryId;
8use k256::ecdsa::Signature as K256Signature;
9use k256::ecdsa::SigningKey as K256SigningKey;
10use k256::ecdsa::VerifyingKey as K256VerifyingKey;
11use k256::AffinePoint as K256AffinePoint;
12use k256::PublicKey as K256PublicKey;
13use k256::Scalar as K256Scalar;
14use k256::SecretKey as K256SecretKey;
15use rand::RngCore;
16use serde::Deserialize;
17use serde::Serialize;
18use sha1::Digest;
19use sha1::Sha1;
20use subtle::CtOption;
21use zeroize::Zeroizing;
22
23use crate::error::Error;
24use crate::error::Result;
25use crate::utils::SystemEntropy;
26pub mod elgamal;
27pub mod group;
28pub mod keys;
29pub mod prime_order;
30/// Signature schemes used by DID identity and provider login.
31pub mod signers;
32mod types;
33use elliptic_curve::sec1::FromSec1Point;
34use elliptic_curve::sec1::Sec1Point;
35use elliptic_curve::sec1::ToSec1Point;
36use elliptic_curve::FieldBytes;
37pub use group::*;
38pub use keys::*;
39use p256::NistP256;
40use subtle::Choice;
41pub use types::PublicKey;
42
43/// ref <https://docs.rs/web3/0.18.0/src/web3/signing.rs.html#69>
44///
45/// length r: 32, length s: 32, length v(recovery_id): 1
46pub type SigBytes = [u8; 65];
47/// Alias PublicKey.
48pub type CurveEle<const SIZE: usize> = PublicKey<SIZE>;
49/// PublicKeyAddress is H160.
50pub type PublicKeyAddress = H160;
51
52/// Secp256k1 secret key bytes.
53///
54/// The secret scalar is validated at construction time and serializes to the
55/// canonical external byte format used by existing configs and DIDs.
56#[derive(PartialEq, Eq, Clone)]
57pub struct SecretKey(K256SecretKey);
58
59impl std::fmt::Debug for SecretKey {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        f.debug_tuple("SecretKey").field(&"<redacted>").finish()
62    }
63}
64
65/// Wrap String into HashStr.
66#[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq)]
67pub struct HashStr(String);
68
69/// Compute the Keccak-256 hash of input bytes.
70pub fn keccak256(bytes: &[u8]) -> [u8; 32] {
71    use tiny_keccak::Hasher;
72    use tiny_keccak::Keccak;
73    let mut output = [0u8; 32];
74    let mut hasher = Keccak::v256();
75    hasher.update(bytes);
76    hasher.finalize(&mut output);
77    output
78}
79
80impl HashStr {
81    /// Create a hash string wrapper from an existing string value.
82    pub fn new<T: Into<String>>(s: T) -> Self {
83        HashStr(s.into())
84    }
85
86    /// Compute the SHA-1 digest of raw bytes and encode it as lowercase hex.
87    pub fn from_bytes(bytes: &[u8]) -> Self {
88        let mut hasher = Sha1::new();
89        hasher.update(bytes);
90        HashStr(hex::encode(hasher.finalize()))
91    }
92
93    /// Return the wrapped hash string.
94    pub fn inner(&self) -> String {
95        self.0.clone()
96    }
97}
98
99impl TryFrom<PublicKey<33>> for K256PublicKey {
100    type Error = Error;
101    fn try_from(key: PublicKey<33>) -> Result<Self> {
102        Self::from_sec1_bytes(&key.0).map_err(|_| Error::ECDSAPublicKeyBadFormat)
103    }
104}
105
106impl TryFrom<PublicKey<33>> for ed25519_dalek::VerifyingKey {
107    type Error = Error;
108    fn try_from(key: PublicKey<33>) -> Result<Self> {
109        let [0, bytes @ ..] = key.0 else {
110            return Err(Error::EdDSAPublicKeyBadFormat);
111        };
112        Self::from_bytes(&bytes).map_err(|_| Error::EdDSAPublicKeyBadFormat)
113    }
114}
115
116impl PublicKey<33> {
117    /// Decode the SEC1 §2.3.3 compressed encoding `t ‖ x` into a secp256r1 affine point.
118    ///
119    /// `None` unless `t ∈ {0x02, 0x03}` and `x` is the x-coordinate of a curve point; `0x02`
120    /// selects the even `y`, `0x03` the odd one. The decoding is the library's
121    /// (`FromSec1Point`), as for secp256k1, so both curves share one tag convention. Only the
122    /// curve arithmetic is constant-time: the tag of a public key is public.
123    pub fn ct_into_secp256r1_affine(self) -> CtOption<primeorder::AffinePoint<NistP256>> {
124        match Sec1Point::<NistP256>::from_bytes(self.0) {
125            Ok(encoded) if encoded.is_compressed() => {
126                primeorder::AffinePoint::<NistP256>::from_sec1_point(&encoded).into()
127            }
128            Ok(_) | Err(_) => CtOption::new(primeorder::AffinePoint::IDENTITY, Choice::from(0)),
129        }
130    }
131
132    /// Map a PublicKey into secp256r1 public key,
133    /// This function is an constant-time cryptographic implementations
134    pub fn ct_try_into_secp256r1_pubkey(self) -> CtOption<Result<ecdsa::VerifyingKey<NistP256>>> {
135        let opt_affine: CtOption<primeorder::AffinePoint<NistP256>> =
136            self.ct_into_secp256r1_affine();
137        opt_affine.and_then(|affine| {
138            let ret =
139                ecdsa::VerifyingKey::<NistP256>::from_affine(affine).map_err(Error::ECDSAError);
140            match ret {
141                Ok(_r) => CtOption::new(ret, Choice::from(1)),
142                Err(_) => CtOption::new(ret, Choice::from(0)),
143            }
144        })
145    }
146}
147
148impl From<&SecretKey> for FieldBytes<NistP256> {
149    fn from(val: &SecretKey) -> Self {
150        FieldBytes::<NistP256>::from(*val.ser())
151    }
152}
153
154impl From<ed25519_dalek::VerifyingKey> for PublicKey<33> {
155    fn from(key: ed25519_dalek::VerifyingKey) -> Self {
156        // [u8;32] here
157        // ref: https://docs.rs/ed25519-dalek/latest/ed25519_dalek/struct.VerifyingKey.html
158        let mut data = [0u8; 33];
159        let key_bytes = key.to_bytes();
160        if let Some(suffix) = data.get_mut(1..) {
161            suffix.copy_from_slice(&key_bytes);
162        }
163        Self(data)
164    }
165}
166
167impl TryFrom<PublicKey<33>> for K256AffinePoint {
168    type Error = Error;
169    fn try_from(key: PublicKey<33>) -> Result<Self> {
170        Ok(TryInto::<K256PublicKey>::try_into(key)?
171            .to_projective()
172            .to_affine())
173    }
174}
175
176impl<T> From<T> for HashStr
177where T: Into<String>
178{
179    fn from(s: T) -> Self {
180        let inputs = s.into();
181        HashStr::from_bytes(inputs.as_bytes())
182    }
183}
184
185impl TryFrom<&str> for SecretKey {
186    type Error = Error;
187    fn try_from(s: &str) -> Result<Self> {
188        let key = hex::decode(s)?;
189        let key_arr: [u8; 32] = key.as_slice().try_into()?;
190        Self::from_bytes(key_arr)
191    }
192}
193
194impl std::str::FromStr for SecretKey {
195    type Err = Error;
196
197    fn from_str(s: &str) -> Result<Self> {
198        Self::try_from(s)
199    }
200}
201
202#[allow(clippy::to_string_trait_impl)]
203impl ToString for SecretKey {
204    fn to_string(&self) -> String {
205        let bytes = self.ser();
206        hex::encode(*bytes)
207    }
208}
209
210struct SecretKeyVisitor;
211
212impl<'de> serde::de::Visitor<'de> for SecretKeyVisitor {
213    type Value = SecretKey;
214
215    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
216        formatter.write_str("SecretKey deserializer")
217    }
218    fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
219    where E: serde::de::Error {
220        SecretKey::from_str(value).map_err(|e| serde::de::Error::custom(e))
221    }
222}
223
224impl<'de> Deserialize<'de> for SecretKey {
225    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
226    where D: serde::Deserializer<'de> {
227        deserializer.deserialize_str(SecretKeyVisitor)
228    }
229}
230
231impl Serialize for SecretKey {
232    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
233    where S: serde::Serializer {
234        serializer.serialize_str(self.to_string().as_str())
235    }
236}
237
238fn public_key_address(pubkey: &PublicKey<33>) -> PublicKeyAddress {
239    let hash = match TryInto::<K256PublicKey>::try_into(*pubkey) {
240        // if pubkey is ecdsa key
241        Ok(pk) => {
242            let data = pk.to_sec1_point(false);
243            let data = data.as_bytes();
244            debug_assert_eq!(data.first(), Some(&0x04));
245            keccak256(data.get(1..).unwrap_or_default())
246        }
247        // if pubkey is eddsa key
248        Err(_) => keccak256(pubkey.0.get(1..).unwrap_or_default()),
249    };
250    PublicKeyAddress::from_slice(&hash[12..])
251}
252
253fn secret_key_address(secret_key: &SecretKey) -> PublicKeyAddress {
254    secret_key.pubkey().address()
255}
256
257impl SecretKey {
258    pub(crate) fn from_bytes(bytes: [u8; 32]) -> Result<Self> {
259        let key = K256SecretKey::from_slice(&bytes).map_err(|_| Error::PrivateKeyBadFormat)?;
260        Ok(Self(key))
261    }
262
263    pub(crate) fn secp256k1_scalar(&self) -> K256Scalar {
264        *self.0.to_nonzero_scalar()
265    }
266
267    /// Generate a random secp256k1 secret key from an explicit RNG.
268    pub fn random_with_rng(rng: &mut impl RngCore) -> Self {
269        Self(K256SecretKey::from(uniform_nonzero_scalar(rng)))
270    }
271
272    /// Generate a random secp256k1 secret key.
273    pub fn random() -> Self {
274        Self::random_with_rng(&mut SystemEntropy)
275    }
276
277    /// Derive the Ethereum-style address for this secret key.
278    pub fn address(&self) -> PublicKeyAddress {
279        secret_key_address(self)
280    }
281
282    /// Sign a UTF-8 message after hashing it with Keccak-256.
283    ///
284    /// Always `Ok`: the key is validated at construction and RFC 6979 signing is total.
285    pub fn sign(&self, message: &str) -> Result<SigBytes> {
286        self.sign_raw(message.as_bytes())
287    }
288
289    /// Sign raw message bytes after hashing them with Keccak-256.
290    ///
291    /// Always `Ok`: the key is validated at construction and RFC 6979 signing is total.
292    pub fn sign_raw(&self, message: &[u8]) -> Result<SigBytes> {
293        let message_hash = keccak256(message);
294        self.sign_hash(&message_hash)
295    }
296
297    /// Sign an already computed 32-byte message hash.
298    ///
299    /// Always `Ok`: the key is validated at construction and RFC 6979 signing is total.
300    pub fn sign_hash(&self, message_hash: &[u8; 32]) -> Result<SigBytes> {
301        let signing_key = K256SigningKey::from(&self.0);
302        let (signature, recover_id) = signing_key.sign_prehash_recoverable(message_hash);
303        let mut sig_bytes: SigBytes = [0u8; 65];
304        sig_bytes[0..64].copy_from_slice(signature.to_bytes().as_slice());
305        sig_bytes[64] = recover_id.to_byte();
306        Ok(sig_bytes)
307    }
308
309    /// Derive the compressed public key for this secret key.
310    pub fn pubkey(&self) -> PublicKey<33> {
311        self.0.public_key().into()
312    }
313
314    /// Serialize this secret key into its 32-byte representation.
315    pub fn ser(&self) -> Zeroizing<[u8; 32]> {
316        Zeroizing::new(self.0.to_bytes().into())
317    }
318}
319
320impl PublicKey<33> {
321    /// Derive the Ethereum-style address for this public key.
322    pub fn address(&self) -> PublicKeyAddress {
323        public_key_address(self)
324    }
325}
326
327/// Recover PublicKey from RawMessage using signature.
328pub fn recover<S>(message: &[u8], signature: S) -> Result<PublicKey<33>>
329where S: AsRef<[u8]> {
330    let sig_bytes: SigBytes = signature.as_ref().try_into()?;
331    let message_hash: [u8; 32] = keccak256(message);
332    recover_hash(&message_hash, &sig_bytes)
333}
334
335/// Recover PublicKey from HashMessage using signature.
336pub fn recover_hash(message_hash: &[u8; 32], sig: &[u8; 65]) -> Result<PublicKey<33>> {
337    let r_s_signature: [u8; 64] = sig[..64].try_into()?;
338    let recovery_id: u8 = sig[64];
339    let signature = K256Signature::try_from(r_s_signature.as_slice()).map_err(Error::ECDSAError)?;
340    if signers::ecdsa_signature_s_is_high(&signature) {
341        // k256 rejects this during recovery too; this branch preserves the
342        // crate's explicit canonical-signature error.
343        return Err(Error::NonCanonicalSignature);
344    }
345    let recovery_id =
346        RecoveryId::from_byte(recovery_id).ok_or(Error::InvalidRecoverId(recovery_id))?;
347    Ok(
348        K256VerifyingKey::recover_from_prehash(message_hash, &signature, recovery_id)
349            .map_err(Error::ECDSAError)?
350            .into(),
351    )
352}
353
354#[cfg(test)]
355mod test_known_answers;
356#[cfg(test)]
357mod test_sec1;
358
359#[cfg(test)]
360pub(crate) mod tests {
361    use hex::FromHex;
362
363    use super::*;
364
365    #[test]
366    fn test_sha1_hashstr_matches_known_hex_input_vector() {
367        let s = "65860affb4b570dba06db294aa7c676f68e04a5bf2721243ad3cbc05a79c68c0";
368        let t: HashStr = s.into();
369        assert_eq!(t.0, "3e32a6d219dc2370ae3f35142eb9a411200aef0b");
370    }
371
372    #[test]
373    fn test_sha1_hashstr_matches_empty_ascii_and_binary_vectors() {
374        assert_eq!(
375            HashStr::from_bytes(b"").0,
376            "da39a3ee5e6b4b0d3255bfef95601890afd80709"
377        );
378        assert_eq!(
379            HashStr::from_bytes("hello".as_bytes()).0,
380            "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
381        );
382        assert_eq!(
383            HashStr::from_bytes(&[0, 0xff, 0x80]).0,
384            "e4bc8a01806054986edd720593bc12f760eca5b9"
385        );
386    }
387
388    #[test]
389    fn test_metamask_sign_for_debug() {
390        let key = &SecretKey::try_from(
391            "65860affb4b570dba06db294aa7c676f68e04a5bf2721243ad3cbc05a79c68c0",
392        )
393        .unwrap();
394        let sig_hash =
395            Vec::from_hex("4a5c5d454721bbbb25540c3317521e71c373ae36458f960d2ad46ef088110e95")
396                .unwrap();
397        let msg = "test";
398        // https://docs.rs/web3/latest/src/web3/signing.rs.html#221
399        let prefix_msg_ret = "\x19Ethereum Signed Message:\n4test"
400            .to_string()
401            .into_bytes();
402        let mut prefix_msg = format!("\x19Ethereum Signed Message:\n{}", msg.len()).into_bytes();
403        prefix_msg.extend_from_slice(msg.as_bytes());
404        assert_eq!(
405            prefix_msg,
406            prefix_msg_ret,
407            "{}",
408            String::from_utf8(prefix_msg.clone()).unwrap()
409        );
410        //        let hash = hash_message(msg.as_bytes()).0;
411        assert_eq!(keccak256(prefix_msg_ret.as_slice()), sig_hash.as_slice());
412        // window.ethereum.request({method: "personal_sign", params: ["test", "0x11E807fcc88dD319270493fB2e822e388Fe36ab0"]})
413        let metamask_sig = Vec::from_hex("724fc31d9272b34d8406e2e3a12a182e72510b008de6cc44684577e31e20d9626fb760d6a0badd79a6cf4cd56b2fc0fbd60c438b809aa7d29bfb598c13e7b50e1b").unwrap();
414        assert_eq!(metamask_sig.len(), 65);
415        let h: [u8; 32] = sig_hash.as_slice().try_into().unwrap();
416        let recover_id = key.sign_hash(&h).unwrap()[64];
417        assert_eq!(recover_id, 0);
418        let mut sig = key.sign_raw(&prefix_msg).unwrap();
419        sig[64] = 27;
420        assert_eq!(sig, metamask_sig.as_slice());
421    }
422
423    #[test]
424    fn test_recover() {
425        let key = SecretKey::random();
426        let pubkey1 = key.pubkey();
427        let pubkey2 = recover("hello".as_bytes(), key.sign("hello").unwrap()).unwrap();
428        assert_eq!(pubkey1, pubkey2);
429    }
430
431    #[test]
432    fn secret_key_redacts_debug_and_needs_drop() {
433        let key =
434            SecretKey::try_from("65860affb4b570dba06db294aa7c676f68e04a5bf2721243ad3cbc05a79c68c0")
435                .unwrap();
436
437        assert_eq!(format!("{key:?}"), "SecretKey(\"<redacted>\")");
438        assert!(std::mem::needs_drop::<SecretKey>());
439    }
440
441    #[test]
442    fn zero_secret_key_bytes_are_rejected() {
443        assert!(matches!(
444            SecretKey::from_bytes([0u8; 32]),
445            Err(Error::PrivateKeyBadFormat)
446        ));
447    }
448
449    #[test]
450    fn recover_hash_rejects_high_s_signature() {
451        let key =
452            SecretKey::try_from("65860affb4b570dba06db294aa7c676f68e04a5bf2721243ad3cbc05a79c68c0")
453                .unwrap();
454        let hash = keccak256(b"canonical signature");
455        let mut signature_bytes = key.sign_hash(&hash).unwrap();
456        let signature = K256Signature::try_from(&signature_bytes[..64]).unwrap();
457        let (r, s) = signature.split_scalars();
458        let high_s = K256Signature::from_scalars(r.to_bytes(), (-s).to_bytes()).unwrap();
459
460        signature_bytes[..64].copy_from_slice(&high_s.to_bytes());
461        signature_bytes[64] ^= 1;
462
463        assert!(matches!(
464            recover_hash(&hash, &signature_bytes),
465            Err(Error::NonCanonicalSignature)
466        ));
467    }
468
469    pub(crate) fn gen_ordered_key_vec(n: usize) -> Vec<SecretKey> {
470        let mut keys = Vec::from_iter(std::iter::repeat_with(SecretKey::random).take(n));
471        keys.sort_by(|a, b| {
472            if a.address() < b.address() {
473                std::cmp::Ordering::Less
474            } else {
475                std::cmp::Ordering::Greater
476            }
477        });
478        keys
479    }
480
481    /// The secret key whose scalar is `index + 1`: a fixed, valid key per index, so a test
482    /// built on it replays the same identities, ring positions and routes on every run.
483    #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
484    pub(crate) fn deterministic_key(index: usize) -> SecretKey {
485        let mut bytes = [0_u8; 32];
486        let scalar = u64::try_from(index)
487            .expect("key index must fit u64")
488            .saturating_add(1);
489        bytes[24..].copy_from_slice(&scalar.to_be_bytes());
490        SecretKey::from_bytes(bytes).expect("positive test scalar must be a valid secret key")
491    }
492
493    #[allow(dead_code)]
494    pub(crate) fn gen_ordered_keys<const N: usize>() -> [SecretKey; N] {
495        let mut keys = std::array::from_fn(|_| SecretKey::random());
496        keys.sort_by(|a, b| {
497            if a.address() < b.address() {
498                std::cmp::Ordering::Less
499            } else {
500                std::cmp::Ordering::Greater
501            }
502        });
503        keys
504    }
505}