Skip to content

Commit 36e5750

Browse files
committed
Add a key generation example
1 parent 39198a0 commit 36e5750

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

examples/keygen.c

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
}

examples/random.h

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#if defined(_WIN32)
2+
#include <bcrypt.h>
3+
#elif defined(__linux__)
4+
#include <fcntl.h>
5+
#include <unistd.h>
6+
#else
7+
#error "Couldn't identify the OS"
8+
#endif
9+
10+
11+
/* Returns 1 on sucess, and 0 on failure. */
12+
int fill_random(unsigned char* data, unsigned long size) {
13+
#if defined(_WIN32)
14+
NTSTATUS res = BCryptGenRandom(NULL, data, size, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
15+
if (res != STATUS_SUCCESS) {
16+
return 0;
17+
}
18+
#elif defined(__linux__)
19+
ssize_t res;
20+
int fd = open("/dev/urandom", O_RDONLY);
21+
if (fd == -1 ) {
22+
return 0;
23+
}
24+
res = read(fd, data, size);
25+
close(fd);
26+
if (res != (ssize_t)size) {
27+
return 0;
28+
}
29+
#endif
30+
return 1;
31+
}

0 commit comments

Comments
 (0)