我有很多谷歌搜索,但任何答案都可以帮助我解决这个问题:
代码:
XRSA.m中的主要解密
- (NSData *) decryptWithString:(NSString *)content {
return [self RSADecryptData:[content dataUsingEncoding:NSUTF8StringEncoding]];
}
在XRSA.m中加载私钥.p12
#pragma mark - Private Key (.p12)
-(BOOL)setPrivateKey:(NSString *)privateKeyPath withPassphrase:(NSString *)password{
NSData *pkcs12key = [NSData dataWithContentsOfFile:privateKeyPath];
NSDictionary* options = NULL;
CFArrayRef importedItems = NULL;
if (password) {
options = [NSDictionary dictionaryWithObjectsAndKeys: password, kSecImportExportPassphrase, nil];
}
OSStatus returnCode = SecPKCS12Import((__bridge CFDataRef) pkcs12key,
(__bridge CFDictionaryRef) options,
&importedItems);
if (returnCode != 0) {
NSLog(@"SecPKCS12Import fail");
return FALSE;
}
NSDictionary* item = (NSDictionary*) CFArrayGetValueAtIndex(importedItems, 0);
SecIdentityRef identity = (__bridge SecIdentityRef) [item objectForKey:(__bridge NSString *) kSecImportItemIdentity];
SecIdentityCopyPrivateKey(identity, &privateKey);
if (privateKey == nil) {
NSLog(@"SecIdentityCopyPrivateKey fail");
return FALSE;
}
return TRUE;
}
解密XRSA.m中的消息
#pragma mark - RSA Decryption
-(NSData *)RSADecryptData:(NSData *)content{
NSAssert(privateKey != nil,@"Private key can not be nil");
size_t cipherLen = content.length;
void *cipher = malloc(cipherLen);
[content getBytes:cipher length:cipherLen];
size_t plainLen = SecKeyGetBlockSize(privateKey) - 12;
void *plain = malloc(plainLen);
//SecKeyDecrypt(<#SecKeyRef key#>, <#SecPadding padding#>, <#const uint8_t *cipherText#>, <#size_t cipherTextLen#>, <#uint8_t *plainText#>, <#size_t *plainTextLen#>)
OSStatus returnCode = SecKeyDecrypt(privateKey, kSecPaddingPKCS1, cipher,cipherLen, plain, &plainLen);
NSData *result = nil;
if (returnCode != 0) {
NSLog(@"SecKeyDecrypt fail. Error Code: %d", (int)returnCode);
}
else {
result = [NSData dataWithBytes:plain
length:plainLen];
}
free(plain);
free(cipher);
return result;
}
ViewControler.m中的:
NSString *privatekeyPath = [[NSBundle mainBundle] pathForResource:@"private_key" ofType:@"p12"];
XRSA *rsa2 = [XRSA alloc];
if([rsa2 setPrivateKey:privatekeyPath withPassphrase:@"Xs23tg"]){
NSString *data = @"UKFpmRmyu1TUZLqcgHmCEGnHaT7+0j5fAaf57xzVR2/j/Qe0j+b5Lez7wya3jlARfzRuHSSZctsGs4gK2JX2LEqHmQLX2zRhLSSzyMlLnYPF8X4pjbDY5agjPlWf4FpFJnmwGr2XjdqRJzPZ9NvEJAns5dNKAh0lQ3nc3kDppfg=";
[rsa2 decryptWithString:data];
}
else{
}
在RSADecryptData功能中,OSStaus始终返回错误代码-9809。
有什么想法吗? 谢谢你的时间。
答案 0 :(得分:0)
有几种可能性:
在[content getBytes:cipher length:cipherLen];
行中,您没有将结果分配给任何内容。也许将其分配给const uint8_t *
并传入SecKeyDecrypt
函数而不是content
。
您应该检查以确保cipherLen
小于plainLen
值。你没有提到你的密钥长度,但这可能是失败的原因。如果您需要支持更大的消息,则需要在较小的块中解密并迭代cipher
。