2
votes

I'm trying to do RSA2048 in iOS and am following the example codes from Apple and also this question RSA implementations in Objective C. I have tested on iPhone 5c with iOS 8.4.1, but the sample codes fail at decryption with private key, with error code -9809 (An underlying cryptographic error was encountered), even though encryption with public key. I understand the basic approach is to generate an RSA key pair, secure them in keychain and use public key ref to encrypt and private key to decrypt. I'm completely lost why decryption shall fail, and not always, there are times when decryption succeeded.

Full codes can be found at https://gist.github.com/aceisScope/372e6d6f92650ce03624. The decryption part that throws an error is below, where from time to time status = -9809, and other times it works and returns 0:

status = SecKeyDecrypt(privateKey,
                       PADDING,
                       cipherBuffer,
                       cipherBufferSize,
                       plainBuffer,
                       &plainBufferSize
                       );

I have also set a check that if such key pair has already generated, next time encryption/decryption is called, it will directly using the already-generated-and-stored key pair from key chain without generating a new pair.


Update: I came across this post iPhone Public-Key Encryption SecKeyEncrypt returns error 9809 (errSSLCrypto) which found out wrong cipher buffer size may cause -9809 error to encryption. Yet even if I make sure both the cipher buffer size in encryption and plain buffer size in decryption is the same as key block size and private key block size, encryption always works but with decryption failing from time to time.

1
Could you edit your question to at least show the lines of code where you get the error code -9809, if not the whole encryption / decryption routines you're doing?Michael Dautermann
The key size is 2048bits, and the message size is 15BabyPanda

1 Answers

0
votes

I found the problem. By the end of encryption, when converting cipher buffer to NSData, in the following code

NSMutableData *data=[[NSMutableData alloc] init];
[data appendBytes:cipherBuffer length:strlen( (char*)cipherBuffer ) + 1];

the length is not correct. It should be the size of the cipher buffer, which is the same as key block size. So after changing it to

NSData *data = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];

decryption works now.