K256 DerSignature

I have started to learn Rust just recently, there's a lot I still don't understand and one of these is probably the type system... I am practicing by rewriting some of the scripts I use at work into a Rust CLI. One of the things that blocks me is the fact, that this CLI needs to send ECDSA signed payloads.

I am using k256 crate to generate a recoverable::Signature but I then want to convert it to a der signature. I noticed that there is a DerSignature trait in k256 but I have no idea how to convert one to the other.

Since k256::ecdsa::signature::Signature has a Serialize trait implemented for serde, I am converting this recoverable::Signature into a signature::Signature and then serializing it using serde. But the response I get from the server is "Signature without r or s"...

I know I'm doing something wrong, I just have no clue what. I don't know how to convert to DerSignature and I think that's the blocker for me... the backend uses elliptic.js if that helps...

This is the code I use

let signing_key: SigningKey = SigningKey::from(SecretKey::from_be_bytes(&raw_pk).unwrap());
let signature: recoverable::Signature = signing_key.sign_digest(hasher);
let ss: k256::ecdsa::Signature = signature.into();
let signedDto = UpdatePublicKey {
    public_key: public_key.to_owned(),
    algorithm: "secp256k1".to_string(),
    signature: base64::encode(to_string(&ss).unwrap()),
};
println!("{}", to_string_pretty(&signedDto).unwrap());

You haven't said what crate you're using for the destination format, but generally serde and ASN.1 (which underlies DER) are not a great match, and one is better served with specialized crates. In this case, however, it's not difficult to implement by hand. The BTC signature format is well enough explained on this page, and you can retrieve the R and S values from the signature with r() and s() methods, and convert them to byte slices with something like to_repr().as_slice(). DER integer encoding is slightly tricky if you have input values with leading zeroes, so a production encoder must take that into account.

Ah, sorry, I am using https://crates.io/crates/k256. I actually managed to manualy DER the key and it all works. Thank you for the link which helped me understand how DER works :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.