Reputation: 1453
I am using RSACrpytoServiceProvider in .NET to encrypt data with my public key that is generated by iOS.
At iOS side, with the same private key, it sometimes decrypt successfully sometimes not. I create different cipherTexts with the same public key in .NET and pass it with Base64 encoding.In iOS i decode Base64 and send this method as content.
I use SecKeyGeneratePair to generate key pair. I delete the key pairs with the same tag before generation.
The error returned by SecKeyDecrypt is: OSStatus return error code -9809 operation could not be completed.
What may be the problem?
size_t cipherBufferSize = [content length];
void *cipherBuffer = malloc(cipherBufferSize);
[content getBytes:cipherBuffer length:cipherBufferSize];
size_t plainBufferSize = [content length];
uint8_t *plainBuffer = malloc(plainBufferSize);
OSStatus sanityCheck = SecKeyDecrypt(key,
kSecPaddingPKCS1,
cipherBuffer,
cipherBufferSize,
plainBuffer,
&plainBufferSize);
Upvotes: 2
Views: 1636
Reputation: 1453
After some digging,
I realized that the modulus that is extracted from publickey is 129 bytes. It had to be 128. I was using the getPublicKeyModFromKeyData
method to extract modulus.
I found out that this adds one extra byte at the beginning. I removed that byte now it works. Thanks for your help.
- (NSData *)getPublicKeyModFromKeyData:(NSData*)pk
{
if (pk == NULL) return NULL;
int iterator = 0;
iterator++; // TYPE - bit stream - mod + exp
[self derEncodingGetSizeFrom:pk at:&iterator]; // Total size
iterator++; // TYPE - bit stream mod
int mod_size = [self derEncodingGetSizeFrom:pk at:&iterator];
// return [pk subdataWithRange:NSMakeRange(iterator, mod_size)];
NSData* subData=[pk subdataWithRange:NSMakeRange(iterator, mod_size)];
return [subData subdataWithRange:NSMakeRange(1, subData.length-1)];
}
Upvotes: 3