iOS SecKeyRawVerify返回-9809

时间:2014-01-11 02:38:54

标签: ios openssl

我用openssl创建了密钥对:

openssl req -x509 -out public_key.der -outform der -new -newkey rsa:1024 -nodes -keyout private_key.pem -days 36500

然后使用private_key.pem签名文件:

openssl dgst -sha1 foo.dat > hash
openssl rsautl -sign -inkey private_key.pem -keyform PEM -in hash > foo.sig

我想在我的iOS应用程序中使用public_key.der来验证foo.sig和foo.dat,但是SecKeyRawVerify总是返回-9809。我的代码是这样的:

NSData* fileData = [NSData dataWithContentsOfFile:(datFileName)];
NSData* signatureData = [NSData dataWithContentsOfFile:(sigFileName)];

NSString *certificatePath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
NSData* certificateData = [NSData dataWithContentsOfFile:(certificatePath)];

SecCertificateRef certificateFromFile = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData); // load the certificate

CFStringRef certificateDescription = SecCertificateCopySubjectSummary(certificateFromFile);

NSLog(@"certificateDescription: %@",certificateDescription);

SecPolicyRef secPolicy = SecPolicyCreateBasicX509();

SecTrustRef trust;
OSStatus statusTrust = SecTrustCreateWithCertificates( certificateFromFile, secPolicy, &trust);
SecTrustResultType resultType;
OSStatus statusTrustEval =  SecTrustEvaluate(trust, &resultType);
SecKeyRef publicKey = SecTrustCopyPublicKey(trust);

uint8_t sha1HashDigest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1([fileData bytes], [fileData length], sha1HashDigest);
char hash_hex[(CC_SHA1_DIGEST_LENGTH * 2) + 1];
ToHex(sha1HashDigest, CC_SHA1_DIGEST_LENGTH, hash_hex);
NSLog(@"hash: %@",[NSString stringWithCString: hash_hex encoding: NSASCIIStringEncoding]);

OSStatus verficationResult = SecKeyRawVerify(publicKey,  kSecPaddingPKCS1SHA1, sha1HashDigest, CC_SHA1_DIGEST_LENGTH, (const uint8_t *)[signatureData bytes], [signatureData length]);
NSLog(@"signatureData length: %d",[signatureData length]);

CFRelease(publicKey);
CFRelease(trust);
CFRelease(secPolicy);
CFRelease(certificateFromFile);
CFRelease(certificateDescription);
if (verficationResult == errSecSuccess) NSLog(@"Verified");

anynoe可以告诉我出了什么问题吗?谢谢!

0 个答案:

没有答案