sign data using rsa private key

Viewed 4466

i know is christmas but i have a huge problem that i need to solve, and i'm looking for my christmas miracle here...

I have read apples documentation, and there were only guides how to create RSA public and private keys from certificates. In my case, i have only RSA private key in .pem file. So my question is his: how should i sign data, using that key? I dont want to use openssl. i have tried it with no luck, and i think it's possible to sign data with RSA, by using apples API's.

This is how my key looks like:

-----BEGIN RSA PRIVATE KEY-----
..............................
-----END RSA PRIVATE KEY-----

This is what i have done so far:

-(NSString *)signing:(NSString *)dataString {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"PrestaMobilekey" ofType:@"pem"];
    NSData *data = [[NSData alloc]initWithContentsOfFile:filePath];

    SecKeyRef privateKey = (__bridge SecKeyRef)(data);

    uint8_t *signedHashBytes = NULL;
    // calculate private key size
    size_t signedHashBytesSize = SecKeyGetBlockSize(privateKey);

    // create space to put signature
    signedHashBytes = (uint8_t *)malloc(signedHashBytesSize * sizeof(uint8_t));
    memset((void *)signedHashBytes, 0x0, signedHashBytesSize);

    OSStatus status = NULL;

    // sign data
    status = SecKeyRawSign(privateKey,
                           kSecPaddingPKCS1SHA1,
                           [[[dataString dataUsingEncoding:NSUTF8StringEncoding] SHA1] bytes],
                           CC_SHA1_DIGEST_LENGTH,
                           signedHashBytes,
                           &signedHashBytesSize);

    if (privateKey) {
        CFRelease(privateKey);
    }

    // get signature hash
    NSData *signedHash = [NSData dataWithBytes:(const void *)signedHashBytes length:(NSUInteger)signedHashBytesSize];

    // release created space
    if (signedHashBytes) {
        free(signedHashBytes);
    }

    if (status != errSecSuccess) {
        return @"";
    }

    // return Base64 encoded signature string
    return [Base64 encode:signedHash];
}

I really hope that someone will help me, with some good information and answer.

Thank you.

2 Answers
Related