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!