2

I created key pair with openssl:

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

Then sign a file with private_key.pem:

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

I want to use the public_key.der in my iOS app to verify foo.sig and foo.dat, but SecKeyRawVerify always return -9809. My codes like this:

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");

Could anynoe tell me what is wrong? Thanks!

Aaron Sun
  • 21
  • 2
  • See [Security Framework - SecKeyRawVerify - OSError Unknown (-9809)](http://stackoverflow.com/questions/10757033/security-framework-seckeyrawverify-oserror-unknown-9809) – jww Jan 12 '14 at 01:38
  • I found this article: http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/ I will try it. – Aaron Sun Jan 12 '14 at 03:01
  • 3
    Did you ever solve this problem? I'm running into the same issue (-9809) when trying to verify on OS X. – Maurizio Jun 24 '15 at 21:07
  • Same here - any advice? – mitschmidt Apr 07 '19 at 22:59

0 Answers0