|
| 1 | +#include <stdio.h> |
| 2 | +#include <assert.h> |
| 3 | + |
| 4 | +#include "random.h" |
| 5 | +#include "secp256k1.h" |
| 6 | + |
| 7 | + |
| 8 | +void print_hex(unsigned char* data, size_t size) { |
| 9 | + size_t i; |
| 10 | + printf("0x"); |
| 11 | + for (i = 0; i < size; i++) { |
| 12 | + printf("%02x", data[i]); |
| 13 | + } |
| 14 | + printf("\n"); |
| 15 | +} |
| 16 | + |
| 17 | +int main(void) { |
| 18 | + unsigned char seckey[32]; |
| 19 | + unsigned char compressed_pubkey[33]; |
| 20 | + unsigned char uncompressed_pubkey[65]; |
| 21 | + size_t len; |
| 22 | + secp256k1_pubkey pubkey; |
| 23 | + secp256k1_context* ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); |
| 24 | + while (1) { |
| 25 | + if (!fill_random(seckey, sizeof(seckey))) { |
| 26 | + printf("Failed to generate randomness\n"); |
| 27 | + return 1; |
| 28 | + } |
| 29 | + if (secp256k1_ec_seckey_verify(ctx, seckey)) { |
| 30 | + break; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + /* Pubkey creation on a valid Context with a verified seckey should never fail */ |
| 35 | + assert(secp256k1_ec_pubkey_create(ctx, &pubkey, seckey)); |
| 36 | + |
| 37 | + /* Serialize the pubkey in a compressed form */ |
| 38 | + len = sizeof(compressed_pubkey); |
| 39 | + secp256k1_ec_pubkey_serialize(ctx, compressed_pubkey, &len, &pubkey, SECP256K1_EC_COMPRESSED); |
| 40 | + /* Should be the same size as the size of the output */ |
| 41 | + assert(len == sizeof(compressed_pubkey)); |
| 42 | + |
| 43 | + /* Serialize the pubkey in an uncompressed form */ |
| 44 | + len = sizeof(uncompressed_pubkey); |
| 45 | + secp256k1_ec_pubkey_serialize(ctx, uncompressed_pubkey, &len, &pubkey, SECP256K1_EC_UNCOMPRESSED); |
| 46 | + assert(len == sizeof(uncompressed_pubkey)); |
| 47 | + |
| 48 | + printf("Secret Key: "); |
| 49 | + print_hex(seckey, sizeof(seckey)); |
| 50 | + printf("Compressed Pubkey: "); |
| 51 | + print_hex(compressed_pubkey, sizeof(compressed_pubkey)); |
| 52 | + printf("Uncompressed Pubkey: "); |
| 53 | + print_hex(uncompressed_pubkey, sizeof(uncompressed_pubkey)); |
| 54 | + |
| 55 | + return 0; |
| 56 | +} |
0 commit comments