7

I am trying to recover a ecdsa pub key from the given signature and data. But returned pubkey does not match with the signer. Is there something that is missing or wrong?

let pair = ecdsa::Pair::from_string(&format!("//{}",1), None).unwrap();
let t_hash = keccak_256(b"Hello");
let new_signature = pair.sign(&t_hash);
if let Ok(recover_pub_key) = sp_io::crypto::secp256k1_ecdsa_recover(&new_signature.0, &t_hash) {
    print!("This is recovered key : {:?}",recover_pub_key);
    } else {
        print!("recovery failed ...!");
    }

Output:

signer publicKey : [3, 51, 2, 40, 152, 20, 6, 98, 223, 234, 132, 126, 60, 191, 229, 233, 137, 132, 90, 198, 118, 110, 131, 71, 47, 139, 12, 101, 13, 133, 231, 123, 174]

Recovered PublicKey : [81, 75, 231, 120, 203, 190, 133, 220, 74, 33, 169, 246, 87, 80, 28, 196, 89, 171, 118, 173, 174, 27, 147, 176, 42, 53, 71, 229, 36, 36, 0, 90, 52, 165, 231, 253, 187, 118, 225, 90, 140, 119, 23, 194, 231, 252, 99, 207, 211, 84, 179, 184, 245, 248, 243, 215, 56, 53, 26, 252, 92, 230, 14, 218]

1 Answer 1

9

Making your code work required:

  • Using sign_prehashed instead of sign
  • secp256k1_ecdsa_recover_compressed instead of secp256k1_ecdsa_recover
  • Using ecdsa::Public::from_raw to construct the recovered PK
use sp_core::{ecdsa, keccak_256, Pair};
use sp_io::crypto::secp256k1_ecdsa_recover_compressed;

let pair = ecdsa::Pair::from_string(&format!("//{}",1), None).unwrap();
let hash = keccak_256(b"Hello");
let signature = pair.sign_prehashed(&hash);

if let Ok(recovered_raw) = secp256k1_ecdsa_recover_compressed(&signature.0, &hash) {
    let recovered = ecdsa::Public::from_raw(recovered_raw);
    // Assert that we recovered the correct PK.
    assert_eq!(pair.public(), recovered);
} else {
    panic!("recovery failed ...!");
}

There are much better ways to do this than directly using the low-level primitives.
Maybe this question better fits your use-case.

2
  • sure, will go through it. Thanks.
    – salman01z
    Mar 30, 2022 at 11:20
  • 1
    This is really helpful! Thanks for your detailed information.
    – extraymond
    Oct 1, 2022 at 4:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.