I am relatively new to C and I am trying to encrypt a string data in C.
I have been provided with a PUBLIC KEY that is somewhat like
-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1WRkqlsZbmaNWbOZr/M4
.
.
.
EKseLc8iKzkwEQcuyMn4znaFpnOL0CmSrYB5K1E9zmmtDhMvDs540ZotcH/xpJiV BwIDAQAB
-----END PUBLIC KEY-----
And a sample representation of what I am trying to achieve in Typescript
rsaEncrypt(text: string, publicKey: string): Promise<string> {
const buffer = Buffer.from(JSON.stringify(text));
const encrypted = publicEncrypt(
{
key: publicKey,
padding: constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha1',
},
buffer,
);
return encrypted.toString('base64');
}
This is my implementation however, my rsa is always NULL after PEM_read_bio_RSA_PUBKEY
int rsa_encrypt(const unsigned char *msg, size_t msg_len, unsigned char **enc_msg, size_t *enc_msg_len) {
RSA *rsa = NULL;
BIO *bio = NULL;
int ret = -1;
tappa_print("%s", "In rsa_enc");
tappa_print("%s", PUBLIC_KEY);
bio = BIO_new_mem_buf(PUBLIC_KEY, -1);
tappa_printf("Bio %d", BIO_get_init(bio));
if (bio == NULL) {
fprintf(stderr, "Error creating bion");
return -1;
}
rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
tappa_printf("RSA %d", rsa==NULL);
if (rsa == NULL) {
ERR_print_errors_fp(stderr);
tappa_print("%s", strerror(errno));
fprintf(stderr, "Error reading public keyn");
//BIO_free(bio);
return -1;
}
tappa_printf("RSA %d", RSA_size(rsa));
*enc_msg = (unsigned char *)malloc(RSA_size(rsa));
tappa_printf("Enc msg %d", sizeof *enc_msg);
if (*enc_msg == NULL) {
fprintf(stderr, "Memory allocation errorn");
RSA_free(rsa);
BIO_free(bio);
return -1;
}
*enc_msg_len = RSA_public_encrypt(msg_len, msg, *enc_msg, rsa, RSA_PKCS1_PADDING);
tappa_printf("Enc msg len%d", sizeof *enc_msg_len);
if (*enc_msg_len == -1) {
fprintf(stderr, "Encryption errorn");
free(*enc_msg);
RSA_free(rsa);
BIO_free(bio);
return -1;
}
ret = 0;
tappa_printf("ret msg %d", ret);
RSA_free(rsa);
BIO_free(bio);
return ret;
}
I tried another approach I saw on the internet, reading the key from a file however, I am faced with “No such file/directory” error after adding the file to my project
FILE* fp =fopen("public.txt","r");
if(fp==NULL){
perror("file error");
return NULL;
}