1 /*************************************************************************
2 * Written in 2020-2022 by Elichai Turkel *
3 * To the extent possible under law, the author(s) have dedicated all *
4 * copyright and related and neighboring rights to the software in this *
5 * file to the public domain worldwide. This software is distributed *
6 * without any warranty. For the CC0 Public Domain Dedication, see *
7 * EXAMPLES_COPYING or https://creativecommons.org/publicdomain/zero/1.0 *
8 *************************************************************************/
9 10 #include <stdio.h>
11 #include <assert.h>
12 #include <string.h>
13 14 #include <secp256k1.h>
15 #include <secp256k1_extrakeys.h>
16 #include <secp256k1_schnorrsig.h>
17 18 #include "examples_util.h"
19 20 int main(void) {
21 unsigned char msg[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'};
22 unsigned char msg_hash[32];
23 unsigned char tag[] = {'m', 'y', '_', 'f', 'a', 'n', 'c', 'y', '_', 'p', 'r', 'o', 't', 'o', 'c', 'o', 'l'};
24 unsigned char seckey[32];
25 unsigned char randomize[32];
26 unsigned char auxiliary_rand[32];
27 unsigned char serialized_pubkey[32];
28 unsigned char signature[64];
29 int is_signature_valid, is_signature_valid2;
30 int return_val;
31 secp256k1_xonly_pubkey pubkey;
32 secp256k1_keypair keypair;
33 /* Before we can call actual API functions, we need to create a "context". */
34 secp256k1_context* ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
35 if (!fill_random(randomize, sizeof(randomize))) {
36 printf("Failed to generate randomness\n");
37 return 1;
38 }
39 /* Randomizing the context is recommended to protect against side-channel
40 * leakage See `secp256k1_context_randomize` in secp256k1.h for more
41 * information about it. This should never fail. */
42 return_val = secp256k1_context_randomize(ctx, randomize);
43 assert(return_val);
44 45 /*** Key Generation ***/
46 if (!fill_random(seckey, sizeof(seckey))) {
47 printf("Failed to generate randomness\n");
48 return 1;
49 }
50 /* Try to create a keypair with a valid context. This only fails if the
51 * secret key is zero or out of range (greater than secp256k1's order). Note
52 * that the probability of this occurring is negligible with a properly
53 * functioning random number generator. */
54 if (!secp256k1_keypair_create(ctx, &keypair, seckey)) {
55 printf("Generated secret key is invalid. This indicates an issue with the random number generator.\n");
56 return 1;
57 }
58 59 /* Extract the X-only public key from the keypair. We pass NULL for
60 * `pk_parity` as the parity isn't needed for signing or verification.
61 * `secp256k1_keypair_xonly_pub` supports returning the parity for
62 * other use cases such as tests or verifying Taproot tweaks.
63 * This should never fail with a valid context and public key. */
64 return_val = secp256k1_keypair_xonly_pub(ctx, &pubkey, NULL, &keypair);
65 assert(return_val);
66 67 /* Serialize the public key. Should always return 1 for a valid public key. */
68 return_val = secp256k1_xonly_pubkey_serialize(ctx, serialized_pubkey, &pubkey);
69 assert(return_val);
70 71 /*** Signing ***/
72 73 /* Instead of signing (possibly very long) messages directly, we sign a
74 * 32-byte hash of the message in this example.
75 *
76 * We use secp256k1_tagged_sha256 to create this hash. This function expects
77 * a context-specific "tag", which restricts the context in which the signed
78 * messages should be considered valid. For example, if protocol A mandates
79 * to use the tag "my_fancy_protocol" and protocol B mandates to use the tag
80 * "my_boring_protocol", then signed messages from protocol A will never be
81 * valid in protocol B (and vice versa), even if keys are reused across
82 * protocols. This implements "domain separation", which is considered good
83 * practice. It avoids attacks in which users are tricked into signing a
84 * message that has intended consequences in the intended context (e.g.,
85 * protocol A) but would have unintended consequences if it were valid in
86 * some other context (e.g., protocol B). */
87 return_val = secp256k1_tagged_sha256(ctx, msg_hash, tag, sizeof(tag), msg, sizeof(msg));
88 assert(return_val);
89 90 /* Generate 32 bytes of randomness to use with BIP-340 schnorr signing. */
91 if (!fill_random(auxiliary_rand, sizeof(auxiliary_rand))) {
92 printf("Failed to generate randomness\n");
93 return 1;
94 }
95 96 /* Generate a Schnorr signature.
97 *
98 * We use the secp256k1_schnorrsig_sign32 function that provides a simple
99 * interface for signing 32-byte messages (which in our case is a hash of
100 * the actual message). BIP-340 recommends passing 32 bytes of randomness
101 * to the signing function to improve security against side-channel attacks.
102 * Signing with a valid context, a 32-byte message, a verified keypair, and
103 * any 32 bytes of auxiliary random data should never fail. */
104 return_val = secp256k1_schnorrsig_sign32(ctx, signature, msg_hash, &keypair, auxiliary_rand);
105 assert(return_val);
106 107 /*** Verification ***/
108 109 /* Deserialize the public key. This will return 0 if the public key can't
110 * be parsed correctly */
111 if (!secp256k1_xonly_pubkey_parse(ctx, &pubkey, serialized_pubkey)) {
112 printf("Failed parsing the public key\n");
113 return 1;
114 }
115 116 /* Compute the tagged hash on the received messages using the same tag as the signer. */
117 return_val = secp256k1_tagged_sha256(ctx, msg_hash, tag, sizeof(tag), msg, sizeof(msg));
118 assert(return_val);
119 120 /* Verify a signature. This will return 1 if it's valid and 0 if it's not. */
121 is_signature_valid = secp256k1_schnorrsig_verify(ctx, signature, msg_hash, 32, &pubkey);
122 123 124 printf("Is the signature valid? %s\n", is_signature_valid ? "true" : "false");
125 printf("Secret Key: ");
126 print_hex(seckey, sizeof(seckey));
127 printf("Public Key: ");
128 print_hex(serialized_pubkey, sizeof(serialized_pubkey));
129 printf("Signature: ");
130 print_hex(signature, sizeof(signature));
131 132 /* This will clear everything from the context and free the memory */
133 secp256k1_context_destroy(ctx);
134 135 /* Bonus example: if all we need is signature verification (and no key
136 generation or signing), we don't need to use a context created via
137 secp256k1_context_create(). We can simply use the static (i.e., global)
138 context secp256k1_context_static. See its description in
139 include/secp256k1.h for details. */
140 is_signature_valid2 = secp256k1_schnorrsig_verify(secp256k1_context_static,
141 signature, msg_hash, 32, &pubkey);
142 assert(is_signature_valid2 == is_signature_valid);
143 144 /* It's best practice to try to clear secrets from memory after using them.
145 * This is done because some bugs can allow an attacker to leak memory, for
146 * example through "out of bounds" array access (see Heartbleed), or the OS
147 * swapping them to disk. Hence, we overwrite the secret key buffer with zeros.
148 *
149 * Here we are preventing these writes from being optimized out, as any good compiler
150 * will remove any writes that aren't used. */
151 secure_erase(seckey, sizeof(seckey));
152 return 0;
153 }
154