Hi,
Yeah it helped. Thanks.
Then I wrote this code(attched) to encrypt and decrypt a text.
I generated the private key using
   openssl genrsa -out rsakey2.pem 1024
And then the public key using
    openssl rsa -in rsakey2.pem -pubout > rsapub2.pem
When I compile and run the test the encryption works but decryption fails.
My openssl version is OpenSSL 0.9.7g 11 Apr 2005.
What I've done wrong here.
Thanks,
Kaushalye

Bernhard Froehlich wrote:

Kaushalye Kapuruge wrote:

Hi,
I'm trying to encrypt a Text using a session key and then encrypt that session key using the public key of the reciever side. Can anybody point me to an example in C?
For this
1. I need to read the key using PEM format.

http://www.openssl.org/docs/crypto/pem.html

2. Generate the session key.

http://www.openssl.org/docs/crypto/RAND_bytes.html

3. Encrypt using RSA

http://www.openssl.org/docs/crypto/RSA_public_encrypt.html

Also I'd like to know how get the key from a key store providing an alias.

I guess that depends strongly on the kind of key store you want to use...

Thanks in advance,
Kaushalye

Hope it helps.
Ted
;)


#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include <string.h>


int main(){
    EVP_PKEY *pubKey = NULL, *prvKey = NULL;
    BIO *bio;
    char *pubfilename, *prvfilename;
    int prvKey_size, pubKey_size, ret;
    
    unsigned char *in = NULL, *encrypted = NULL , *decrypted = NULL; 

    pubfilename = "rsapub2.pem";
    prvfilename = "rsakey2.pem";

    in = (unsigned char*)"SESSION_KEY";
    /*Read  pub key*/
    bio = BIO_new_file(pubfilename, "rb");
    pubKey = PEM_read_bio_PUBKEY(bio, NULL, 0 , "");
    
    if(pubKey){
        encrypted = malloc(RSA_size(pubKey->pkey.rsa));
        ret = RSA_public_encrypt(strlen((char*)in), in, encrypted, pubKey->pkey.rsa, RSA_PKCS1_PADDING);
        if(ret <0) {
            printf("FAILED : Encrypting\n");
            return -1;
        }else{
            printf("SUCCESS : Encrypting\nsize=%d\n",ret);
            
        }
    }else{
        printf("pub key failed\n");        
    }
    
    /*Decryption*/
    /*Read the private key*/
    BIO_reset(bio);
    bio = BIO_new_file(prvfilename, "rb");
    
    prvKey = PEM_read_bio_PrivateKey(bio, NULL, 0, "");
    if(prvKey){
        decrypted = malloc(2048);
       /* decrypted = malloc(RSA_size( prvKey->pkey.rsa));*/
        ret = RSA_private_decrypt(strlen((char*)encrypted), encrypted, decrypted, prvKey->pkey.rsa, RSA_PKCS1_PADDING);
        if(ret <0) {
            printf("FAILED : Decrypting\n");
            return -1;
        }else{
            printf("SUCCESS : Decrypted\nsize=%d\n%s", ret, decrypted);
            return 0;
        }
    }else{
        printf("prv key failed\n");        
    }



   
    
}

Reply via email to