1

I am trying to get public key from private key using secp256k1 library. https://github.com/bitcoin-core/secp256k1

I set same private key(sk) in here. https://github.com/ethereumbook/ethereumbook/blob/develop/04keys-addresses.asciidoc#ethereum-addresses

unsigned char *sk = "f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315";
secp256k1_ec_pubkey_create(secp256k1_ctx, &pk, sk);
secp256k1_ec_pubkey_serialize(secp256k1_ctx, output, &outputlen, &pk, SECP256K1_EC_UNCOMPRESSED);

But serialized public key (output) which I got is

04a82b7752a73ab1de51ae4f614e7e9908fb891c1cdeeab96c0e7c237d3e3a0369daf8eab4e3864668575c5d10fc000a6897b10102c14671140c1cdf9765fd46b0

Not same public key in ethereum book. Am I writing wrong code to get correct public key ?

  • 1
    I solved it. each byte in sk must be a number. like.. sk[0] = 0xf8, sk[1] = 0xf8, sk[2] = 0xa2, ... – xiaofo Sep 16 at 13:07
  • Hi there - can you add your solution as a proper answer? :-) – Richard Horrocks Sep 16 at 15:03
1

I solved this problem. Each byte in secret key(sk) must be a number.

void skstr_to_sk(const unsigned char *sk_str, unsigned char *sk)
{
  const unsigned char *sk_pos = sk_str;
  int i;

  for (i = 0; i < PRIVATE_KEY_SIZE; i++) {
      sscanf(sk_pos, "%2hhx", &sk[i]);
      sk_pos += 2;
  }
}

int main(void)
{
  ...

  unsigned char *sk_str = "f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315";
  unsigned char sk[PRIVATE_KEY_SIZE];  // PRIVATE_KEY_SIZE == 32
  ...

  skstr_to_sk(sk_str, sk);

  /* get public key and serialize it */
  secp256k1_ctx = secp256k1_context_create(flags);

  secp256k1_ec_pubkey_create(secp256k1_ctx, &pk, sk);
  secp256k1_ec_pubkey_serialize(secp256k1_ctx, output, &outputlen, &pk, SECP256K1_EC_UNCOMPRESSED);
  ...
}

skstr_to_sk() function converts sk_str to a corresponding hexadecimal number. For example, sk_str[0] and sk_str[1] have the value 'f' and '8' respectively. We must make it hexadecimal number 0xf8. such that

sk_str[0] = f, sk_str[1] = 8 -> sk[0] = 0xf8
sk_str[2] = f, sk_str[3] = 8 -> sk[1] = 0xf8
sk_str[4] = a, sk_str[5] = 2 -> sk[2] = 0xa2
sk_str[6] = f, sk_str[7] = 4 -> sk[3] = 0xf4
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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