I have a key pair created like this:
openssl req -x509 -out public_key.der -outform der -new -newkey rsa:1024 -keyout private_key.pem -days 3650
Next I sign a text file using the foll. commands:
openssl dgst -sha256 some_text.txt > hash256
openssl rsautl -sign -inkey private_key.pem -keyform PEM -in hash256 > signature256.txt
Now, I want to verify it on iOS:
+ (BOOL)verifySignature {
NSData* publicKeyData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"public_key" withExtension:@"der"]];
SecCertificateRef pubCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, ( __bridge CFDataRef) publicKeyData);
if (pubCertificate == nil) {
NSLog(@"Can not read certificate from data");
return NO;
}
SecTrustRef trust;
SecPolicyRef policy = SecPolicyCreateBasicX509();
OSStatus returnCode = SecTrustCreateWithCertificates(pubCertificate, policy, &trust);
if (returnCode != errSecSuccess) {
NSLog(@"SecTrustCreateWithCertificates fail. Error Code: %d", (int)returnCode);
return NO;
}
SecTrustResultType trustResultType;
returnCode = SecTrustEvaluate(trust, &trustResultType);
if (returnCode != errSecSuccess) {
return NO;
}
SecKeyRef publicKey = SecTrustCopyPublicKey(trust);
NSURL* textFileUrl = [[NSBundle mainBundle] URLForResource:@"some_text" withExtension:@"txt"];
NSData* signedData = [NSData dataWithContentsOfURL:textFileUrl];
size_t signedDataLen = [signedData length];
void *signedDataBuffer = malloc(signedDataLen);
[signedData getBytes:signedDataBuffer length:signedDataLen];
void* hashBuffer = malloc(CC_SHA256_DIGEST_LENGTH);
CC_SHA256(signedDataBuffer, (CC_LONG)signedDataLen, hashBuffer);
NSURL* signatureFileUrl = [[NSBundle mainBundle] URLForResource:@"signature256" withExtension:@"txt"];
NSData* signatureData = [NSData dataWithContentsOfURL:signatureFileUrl];
size_t signatureLen = [signatureData length];
void* signatureBuffer = malloc(signatureLen);
[signatureData getBytes:signatureBuffer length:signatureLen];
returnCode = SecKeyRawVerify(publicKey, kSecPaddingPKCS1SHA256, hashBuffer, CC_SHA256_DIGEST_LENGTH, signatureBuffer, signatureLen);
if (returnCode != errSecSuccess) {
NSLog(@"SecKeyRawVerify fail. Error Code: %d", (int)returnCode);
}
free(signedDataBuffer);
free(signatureBuffer);
free(hashBuffer);
CFRelease(pubCertificate);
CFRelease(policy);
CFRelease(trust);
CFRelease(publicKey);
Everything looks OK until the point where I call SecKeyRawVerify
, which returns error code -9809.
What am I doing wrong?