1

EDIT: Question heavily edited to narrow focus of question

I'm trying to extract an uncompressed public key from the secp256k1::key::PublicKey struct.

Depending on which print formatting I use I either get the compressed or uncompressed key.

As observed by this question, the uncompressed key is hex- (or byte-)reversed (you can see that the reverse of the compressed version is the start of the uncompressed version).

I don't know how to extract the 64 byte (reversed) key from the struct in order to manipulate it. If I try to use the .serialize() method on the public key it returns the 33-byte slice of the compressed key, not the public key.

Does anyone know how to extract and manipulate the 64-byte key from the struct?

Snippet of code below:

//Calculate BIP32 Extended Public Key and Public Key
let ex_pub_key = ExtendedPubKey::from_private(&secp, &ex_priv_key);
    println!("Compressed Public Key: {}", ex_pub_key.public_key.key);
    //returns the 33-byte: 
    //03a593ae00ed6b402c801d2a2edca9f5c057f2be7327e3d81c5747df058e169cd5
    
    println!("Uncompressed Public Key: {:?}", ex_pub_key.public_key.key);  
    //returns the 64-byte struct:
 //PublicKey(d59c168e05df47571cd8e32773bef257c0f5a9dc2e2a1d802c406bed00ae93a57d95dc0fa554e33bda9c7cd87e4b8e8b788b759c0bb1160bb803240468d0e559)
    
//Serializing the key returns the compressed version of the key
let serialized_key = public_key.serialize();
    println!("Serialized Key: {:?}", serialized_key);
    //returns the 33-byte slice:
    //[3, 165, 147, 174, 0, 237, 107, 64, 44, 128, 29, 42, 46, 220, 169, 245, 192, 87, 242, 190, 115, 39, 227, 216, 28, 87, 71, 223, 5, 142, 22, 156, 213]

Isambard_FA
  • 97
  • 13
  • 1
    Is `uncompressed_public_key` also good or is that bad already or do you not know? – Hadus Feb 26 '21 at 22:25
  • I don't know, as it is not given on the website I'm benchmarking against. However, I do suspect that the conversion from compressed public key to uncompressed public key is wrong. With the display trait, `println!("Compressed Public Key: {}", ex_pub_key.public_key.key);` gives the 33 byte output, and using `{:?}` gives a 64 byte output. However the latter 32 bytes of the compressed key should be part of the 64 byte key and this does not appear to be the case... – Isambard_FA Feb 27 '21 at 08:18
  • EDIT: After some more investigation I am pretty sure now that my problem is generating the uncompressed public key. Does anybody know when given the compressed key how to generate the uncompressed key? – Isambard_FA Mar 01 '21 at 10:14

1 Answers1

0

After much research I have discovered that there is a simple way to extract the uncompressed public key by using the method serialize_uncompressed() on the public key, which is part of the same secp256k1 crate.

This provides a 65-byte output, where the first byte should be dropped to create the correct 64-byte public key.

Isambard_FA
  • 97
  • 13