Friday, January 28, 2011

iPhone OpenSSL

Encryption

To Encrypt unsigned char* in_array, without using EVP_PKEY

char* filename = "public_key_pem_format";
FILE* fp_public = fopen(filename,"r");
RSA* p_rsa_public;
if((p_rsa_public=PEM_read_RSAPublicKey(fp_public,NULL,NULL,NULL))==NULL)
{
    ERR_print_errors_fp(stdout);
}
fclose(fp_public);

int in_len = RSA_size(p_rsa_public);
unsigned char* out_array = (unsigned char *) malloc(in_len);
int out_len = 
RSA_public_encrypt(in_len, in_array, out_array, p_rsa_public, RSA_NO_PADDING);
NSData* crypted = [NSData dataWithBytes:out_array length:out_len];

free(out_array);
RSA_free(p_rsa_public);

To Decrypt NSData* crypted

char* filename = "private_key_pem_format";
FILE* fp_private = fopen(filename,"r");
RSA* p_rsa_private;
if((p_rsa_private=PEM_read_RSAPrivateKey(fp_private,NULL,NULL,NULL))==NULL)
{
    ERR_print_errors_fp(stdout);
}
fclose(fp_private);

int in_len = RSA_size(p_rsa_private);
unsigned char* in_array = (unsigned char *) [crypted bytes];
unsigned char* out_array = (unsigned char *) malloc(in_len+1);
memset(out_array, 0, in_len+1);
int out_len = RSA_private_decrypt(in_len, in_array, out_array, p_rsa_private, RSA_NO_PADDING);
NSString * s = [[NSString alloc] initWithBytes:out_array length:out_len encoding:NSUTF8StringEncoding];

free(out_array);
RSA_free(p_rsa_private);


To Sign unsigned char* in_data using a p12 private key

OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();

NSString *p12FilePath = @"filename.p12";
BIO *bio = BIO_new_file ([p12FilePath UTF8String], "r");
PKCS12 *p12 = d2i_PKCS12_bio (bio, NULL);
BIO_free (bio);
bio = NULL;

EVP_PKEY *key = NULL;
X509 *cert = NULL;
STACK_OF (X509) * ca = NULL;
const char * password = "mypassword";
PKCS12_parse (p12, password, &key, &cert, &ca);
PKCS12_free (p12);
p12 = NULL;

RSA *rsaKey = EVP_PKEY_get1_RSA(key);
int rsaSize = RSA_size(rsaKey);
unsigned char *out_data = malloc(rsaSize);
unsigned int out_len;
unsigned char * in_data = (unsigned char*) "1234567890";
int in_len = strlen((char*) in_data);
int sigtype = NID_sha256WithRSAEncryption;
RSA_sign(sigtype, in_data, in_len, out_data, &out_len, rsaKey);
NSLog(@"signed result: %s length: %d", out_data, out_len);

if (key != NULL) EVP_PKEY_free(key);
if (cert != NULL) X509_free(cert);
if (ca != NULL) {
  for(;;) {
    X509 *x5 = sk_X509_pop(ca);
    if (!x5)
      break;
    X509_free(x5);
  }
  sk_X509_free (ca);
}
if (rsaKey != NULL) RSA_free(rsaKey);

free(out_data);

No comments:

Post a Comment