Hi,
I have been trying to figure out why this is crashing with a
'Segmentation fault', as far as I can see all the buffers etc. are
getting setup and passed around correctly.
If I comment out line 51 with the call to RSA_private_decrypt() I
don't get the 'Segmentation fault'.
Help Please.
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <stdio.h>
#include <stdlib.h>
BIO *bio_err=0;
void print_data(unsigned char *data, int size)
{
int x;
printf ("%p\n", data);
printf ("0000 : ");
for (x = 0; x < size; x++) {
if ((x > 0) && (x % 16 == 0))
printf ("\n%04x : ", x);
printf ("%02x ", data[x]);
}
printf ("\n------------------------------------------------------\n");
}
unsigned char * public_encrypt(RSA *rsa, unsigned char *from)
{
int size = RSA_size(rsa);
unsigned char *to;
if (to = malloc(size)) {
int x;
for (x = 0; x < size; x++) to[x] = 0x00;
x = RSA_public_encrypt(size, from, to, rsa, RSA_NO_PADDING);
printf ("encrypt = %d\n", x);
if (x == -1) exit(0);
return (to);
}
else {
printf("memory allocation error\n");
return (NULL);
}
}
unsigned char * private_decrypt(RSA *rsa, unsigned char *from)
{
int size = RSA_size(rsa);
unsigned char *to;
if (to = malloc(size)) {
int x;
for (x = 0; x < size; x++) to[x] = 0x00;
x = RSA_private_decrypt(size, from, to, rsa, RSA_NO_PADDING);
printf ("decrypt = %d\n",x);
if (x == -1) exit(0);
return (to);
}
else {
printf("memory allocation error\n");
return (NULL);
}
}
int main (int argc, char**argv)
{
RSA *rsa;
int size;
if ((rsa = RSA_new()) != NULL) {
BIO *in;
if (in = BIO_new_file("rsakey.pem", "r")) {
int ok;
printf ("Created private BIO\n");
ok = (PEM_read_bio_RSAPrivateKey(in, &rsa, NULL, NULL) != NULL);
printf ("ok = %s\n", (ok != 0) ? "true":"false");
BIO_free(in);
if (!ok) exit(0);
}
if (in = BIO_new_file("pubkey.pem", "r")) {
int ok;
printf ("Created public BIO\n");
ok = (PEM_read_bio_RSA_PUBKEY(in, &rsa, NULL, NULL) != NULL);
printf ("ok = %s\n", (ok != 0) ? "true":"false");
BIO_free(in);
if (!ok) exit(0);
}
//PEM_write_RSA_PUBKEY(stdout, rsa);
size = RSA_size(rsa);
if (size > 0) {
unsigned char *encrypted;
unsigned char *plain;
int x;
// generate and print the plain text
plain = malloc(size);
for (x = 0; x < size; x++) plain[x] = x & 0xFF;
print_data(plain,size);
// encrypt and print
encrypted = public_encrypt(rsa,plain);
print_data(encrypted,size);
free (plain);
// decrypt and print
plain = private_decrypt(rsa,encrypted);
print_data(plain,size);
// cleanup
free(encrypted);
free(plain);
}
RSA_free(rsa);
}
}