I am writing a simple server and client program using C and local sockets. I have successfully generated a public and private key with openSSL with the following code:
int generateKeys(char* publicDest, char* privateDest) {
RSA *keypair = RSA_generate_key(2048, 3, NULL, NULL);
BIO *pri = BIO_new(BIO_s_mem());
BIO *pub = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);
PEM_write_bio_RSAPublicKey(pub, keypair);
size_t pri_len = BIO_pending(pri);
size_t pub_len = BIO_pending(pub);
char *pri_key = malloc(pri_len + 1);
char *pub_key = malloc(pub_len + 1);
BIO_read(pri, pri_key, pri_len);
BIO_read(pub, pub_key, pub_len);
pri_key[pri_len] = '\0';
pub_key[pub_len] = '\0';
strcpy(publicDest, pub_key);
strcpy(privateDest, pri_key);
}
I now need to send the public key to the client so that they are able to encrypt their message for the server. I am doing this as follows:
char publicKey[2048];
char privateKey[2048];
generateKeys(publicKey, privateKey);
write(clientSocket, publicKey, 2048);
First off, is this the correct way to send a public key to the client?
This is where I am stuck now, how do I encrypt the message on the client-side only using the public key? Is it possible?
Edit - here is my code on the client-side where I am trying to encrypt the message:
char dest[2048];
BIO *pubBio = BIO_new_mem_buf(publicKey, -1);
RSA *pubRSA = PEM_read_bio_RSA_PUBKEY(pubBio, NULL, NULL, NULL);
if(!pubRSA) {
printf("Issue loading public key...");
}
RSA_public_encrypt(sizeof(sigMessage), sigMessage, dest, pubRSA, RSA_PKCS1_PADDING);
My issue is that I am unable to load the public key in this way.