I want to generate pem with openssl in C.
I'm compiling with gcc key_utils.c tests.c -o key_tests -lcrypto -lssl -Wall
My code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#include <openssl/ecdsa.h>
#include <openssl/pem.h>
int generatePem(char **pem) {
char *pemholder = calloc(224, sizeof(char));
EC_KEY *eckey = NULL;
BIO *out = BIO_new(BIO_s_mem());
BUF_MEM *buf = NULL;
EC_GROUP *group = NULL;
group = EC_GROUP_new_by_curve_name(NID_secp256k1);
buf = BUF_MEM_new();
eckey = EC_KEY_new();
createNewKey(group, eckey);
EC_GROUP_clear_free(group);
PEM_write_bio_ECPrivateKey(out, eckey, NULL, NULL, 0, NULL, NULL);
BIO_get_mem_ptr(out, &buf);
memcpy(pemholder, buf->data, 223);
if ( buf->data[219] == '\n') {
pemholder[220] = '\0';
memcpy(*pem, pemholder, 221);
} else if ( buf->data[221] == '\n') {
pemholder[222] = '\0';
memcpy(*pem, pemholder, 223);
} else {
pemholder[223] = '\0';
memcpy(*pem, pemholder, 224);
}
free(pemholder);
EC_KEY_free(eckey);
BIO_free_all(out);
return NOERROR;
};
The bad pem looks like so:
-----BEGIN EC PRIVATE KEY-----
MHMCAQEEH8kO/hjEyM2hvQk//LSsp1xRBIYNDRjAi4b8N78odyCgBwYFK4EEAAqh
RANCAAQ43017I40ci8YMLJnguD/DHUjohY4blKoJ4lXYbgYqyjWvJfVnsNPMU8H9
o3IdPwAitnJjCOG11n9DIQoS3S/o
-----END EC PRIVATE KEY-----
6T