Created
April 24, 2019 03:31
-
-
Save yutelin/b5d8d728d784c34e15e8fa6589e3f3ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <secp256k1.h> | |
int main() { | |
secp256k1_context* ctx; | |
secp256k1_pubkey pubkey; | |
const unsigned char *seckey = (unsigned char*) "Secret Key Br0!"; | |
ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); | |
if (!secp256k1_ec_pubkey_create(ctx, &pubkey, seckey)) { | |
printf("Failed to create pubkey\n"); | |
return 1; | |
} | |
size_t size = 33 * sizeof(char); | |
unsigned char *out = (unsigned char *)malloc(size); | |
char *hex = (char *)malloc(size * 2); | |
secp256k1_ec_pubkey_serialize(ctx, out, &size, &pubkey, SECP256K1_EC_COMPRESSED); | |
for (int i = 0, j = 0; i < strlen((const char*)out); ++i, j += 2) { | |
sprintf(hex + j, "%02x", out[i] & 0xff); | |
} | |
printf("Public key: %s\n", hex); | |
secp256k1_ecdsa_signature sig; | |
const unsigned char *msg = (unsigned char*)"This is the message"; | |
if (!secp256k1_ecdsa_sign(ctx, &sig, msg, seckey, NULL, NULL)) { | |
printf("Unable to sign the message\n"); | |
return 1; | |
} | |
size_t sig_len = sizeof(secp256k1_ecdsa_signature)*2; | |
unsigned char *sig_out = (unsigned char *)malloc(sig_len); | |
if (secp256k1_ecdsa_signature_serialize_der(ctx, sig_out, &sig_len, &sig) == 0) { | |
printf("Unable to serialize the signature\n"); | |
return 1; | |
} | |
char *sig_hex = (char *)malloc(sig_len * 2); | |
for (int i = 0, j = 0; i < strlen((const char*)sig_out); ++i, j += 2) { | |
sprintf(sig_hex + j, "%02x", sig_out[i] & 0xff); | |
} | |
printf("Signature: %s\n", sig_hex); | |
if(secp256k1_ecdsa_verify(ctx, &sig, msg, &pubkey)==0){ | |
printf("Unable to verify signature\n"); | |
} else { | |
printf("Signature verified\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed bugs from original source.