Search code examples
rustpublic-keyecdsa

Rust p256: How to get a PublicKey from a String


I have a public key stored as a String. My goal is to verify a message using ecdsa.

I tried to use the from_str function but get an Err each time

let public_key: String = "...my_public_key..."
PublicKey::from_str(&public_key)

The documentation provided by p256 is very bad. How could I implement this?

EDIT:

Using the from_str function from PublicKey, I always end up getting an Err (crypto error). Would you have any idea of how I could create a PublicKey from a String?

use p256::elliptic_curve::PublicKey;

match PublicKey::from_str(public_key)) {
        Ok(pub_k) => {},
        Err(e) => println!("{}", e)
}

I tried using this public_key (but does not seem to work for any): 0458962a508fc3648f30cc81f56d4d5ad79d09b7f8d1f88e254c8e915e4f669c5c738f05ad657f25a2f1afb7396fc4239de9b869e71dc3dbfd4f2e137c68871fe3

I also tried adding '0x' at the beggining of my String but it didn't work.


Solution

  • The posted key is a hex encoded uncompressed public EC key (for secp256r1 aka NIST P-256). This must first be hex decoded and can then be imported using p256::PublicKey::from_sec1_bytes().

    Example:

    use p256;
    use hex;
    
    fn main() {
    
        // Hex decode key
        let public_key_uncompressed_hex = "0458962a508fc3648f30cc81f56d4d5ad79d09b7f8d1f88e254c8e915e4f669c5c738f05ad657f25a2f1afb7396fc4239de9b869e71dc3dbfd4f2e137c68871fe3";
        let public_key_uncompressed = hex::decode(public_key_uncompressed_hex).expect("decoding error");   
    
        // Import uncompressed public key
        let public_key = p256::PublicKey::from_sec1_bytes(&public_key_uncompressed).expect("import error");
        println!("{:?}", public_key); // PublicKey { point: AffinePoint {...
    }