Skip to content

Commit b8411d1

Browse files
authored
feat(identity): allow importing and exporting secp256k1 keys
Related: #3681 Pull-Request: #3887.
1 parent eecfe2f commit b8411d1

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

identity/src/keypair.rs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,10 @@ impl Keypair {
236236
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
237237
Self::Rsa(_) => return Err(DecodingError::encoding_unsupported("RSA")),
238238
#[cfg(feature = "secp256k1")]
239-
Self::Secp256k1(_) => return Err(DecodingError::encoding_unsupported("secp256k1")),
239+
Self::Secp256k1(data) => proto::PrivateKey {
240+
Type: proto::KeyType::Secp256k1,
241+
Data: data.secret().to_bytes().to_vec(),
242+
},
240243
#[cfg(feature = "ecdsa")]
241244
Self::Ecdsa(data) => proto::PrivateKey {
242245
Type: proto::KeyType::ECDSA,
@@ -269,7 +272,12 @@ impl Keypair {
269272
Err(DecodingError::missing_feature("ed25519"))
270273
}
271274
proto::KeyType::RSA => Err(DecodingError::decoding_unsupported("RSA")),
272-
proto::KeyType::Secp256k1 => Err(DecodingError::decoding_unsupported("secp256k1")),
275+
proto::KeyType::Secp256k1 => {
276+
#[cfg(feature = "secp256k1")]
277+
return secp256k1::SecretKey::try_from_bytes(&mut private_key.Data)
278+
.map(|key| Keypair::Secp256k1(key.into()));
279+
Err(DecodingError::missing_feature("secp256k1"))
280+
}
273281
proto::KeyType::ECDSA => {
274282
#[cfg(feature = "ecdsa")]
275283
return ecdsa::SecretKey::try_decode_der(&mut private_key.Data)
@@ -726,6 +734,21 @@ mod tests {
726734
roundtrip_protobuf_encoding(&priv_key, &pub_key);
727735
}
728736

737+
#[test]
738+
#[cfg(all(feature = "secp256k1", feature = "peerid"))]
739+
fn keypair_protobuf_roundtrip_secp256k1() {
740+
let priv_key = Keypair::from_protobuf_encoding(&hex_literal::hex!(
741+
"0802122053DADF1D5A164D6B4ACDB15E24AA4C5B1D3461BDBD42ABEDB0A4404D56CED8FB"
742+
))
743+
.unwrap();
744+
let pub_key = PublicKey::try_decode_protobuf(&hex_literal::hex!(
745+
"08021221037777e994e452c21604f91de093ce415f5432f701dd8cd1a7a6fea0e630bfca99"
746+
))
747+
.unwrap();
748+
749+
roundtrip_protobuf_encoding(&priv_key, &pub_key);
750+
}
751+
729752
#[cfg(feature = "peerid")]
730753
fn roundtrip_protobuf_encoding(private_key: &Keypair, public_key: &PublicKey) {
731754
assert_eq!(&private_key.public(), public_key);

0 commit comments

Comments
 (0)