I'm wrtiting a program, that when given a bitcoin private key address, will generate a public key address.
I have been following a few online examples, but seem to be stuck...
Code:
#include <stdio.h>
#include <libgen.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/ec.h>
#include <openssl/obj_mac.h>
// Declare global variables.
char *program_name = "public_key";
int main (int argc, char *argv[])
{
// Declare variables.
EC_KEY *pkey = NULL;
EC_POINT *pub_key = NULL;
const EC_GROUP *group = NULL;
BN_CTX *ctx = NULL;
BIGNUM *res = NULL;
// Allocates and initialize BIGNUM structure.
if((res = BN_new()) == NULL)
{
fprintf(stderr, "%s: generate_pubic_key error: BN_new failed (%s)\n", program_name, ERR_error_string(ERR_get_error(), NULL));
exit(EXIT_FAILURE);
}
// Allocates and initialize BN_CTX structure.
if((ctx = BN_CTX_new()) == NULL)
{
fprintf(stderr, "%s: generate_pubic_key error: BN_CTX_new failed (%s)\n", program_name, ERR_error_string(ERR_get_error(), NULL));
exit(EXIT_FAILURE);
}
// Convert hexadecimal to BIGNUM.
if(BN_hex2bn(&res, argv[1]) == 0)
{
fprintf(stderr, "%s: generate_pubic_key error: BN_hex2bn failed (%s)\n", program_name, ERR_error_string(ERR_get_error(), NULL));
exit(EXIT_FAILURE);
}
// Generate public key.
if((pkey = EC_KEY_new_by_curve_name(NID_secp256k1)) == NULL)
{
fprintf(stderr, "%s: generate_pubic_key error: EC_KEY_new_by_curve_name failed\n", program_name);
exit(EXIT_FAILURE);
}
// Set EC_KEY group object.
group = EC_KEY_get0_group(pkey);
// Create a new point on the curve.
if((pub_key = EC_POINT_new(group)) == NULL)
{
fprintf(stderr, "%s: generate_pubic_key error: EC_POINT_new failed\n", program_name);
exit(EXIT_FAILURE);
}
// Set the private key.
if(EC_KEY_set_private_key(pkey, res) == 0)
{
fprintf(stderr, "%s: generate_pubic_key error: EC_KEY_set_private_key failed\n", program_name);
exit(EXIT_FAILURE);
}
// Convert BIGNUM to EC_POINT.
if(EC_POINT_bn2point(group, res, pub_key, ctx) == NULL)
{
fprintf(stderr, "%s: generate_pubic_key error: EC_POINT_bn2point failed\n", program_name);
exit(EXIT_FAILURE);
}
// Exit gracefully.
exit(EXIT_SUCCESS);
}
I'm getting the following when I run it:
Code:
public_key: generate_public_key error: EC_POINT_bn2point failed
When I check the man page for 'EC_POINT_bn2point' the RETURN VALUES section says:
Code:
EC_POINT_bn2point() returns the pointer to the EC_POINT supplied, or NULL on error.
Can someone help to explain what I've done wrong? The return value leaves a lot to be desired.