0

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.

0

1 Answer 1

3

First off, is this the correct way to send a public key to the client?

No. It isn't even a valid way to save the keys. It isn't valid to use strcpy() on binary data. You should use memcpy().

how do I encrypt the message on the client-side only using the public key?

You would need to show some code for comment.

Is it possible?

Sure, but why? Why not use SSL/TLS?

Sign up to request clarification or add additional context in comments.

2 Comments

I've updated my code to show the client-side encryption issue
But not how you received the public key. The presumption must be that the data you loaded it from isn't correct, so how you acquired that data is critical. In any case you are supposed to post a complete reproducible problem here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.