我有一些非常简单的要求,我很惊讶这是多么困难:我想签署一个文件,将签名作为base64进行传输,然后在Objective C中验证iOS和OS X上的签名。这是什么我已经有了。
生成签名相当容易 - 出于我的目的,这可以在命令行上完成。首先生成密钥:
openssl genrsa -out rsa_priv.pem 1024
openssl rsa -in rsa_priv.pem -pubout -outform DER -out rsa_pub.der
openssl req -new -x509 -key rsa_priv.pem -out rsa_cert.cer
我想将验证作为框架的一部分进行,因此不希望将证书捆绑为文件,因此我获得了base64编码版本,然后在验证之前解码:
openssl enc -base64 -in rsa_cert.cer
为文件创建签名:
openssl dgst -sha1 -sign rsa_priv.pem FILE | openssl enc -base64
所以现在我有了base64编码的签名和base64编码的X509证书。我查看了各种堆栈溢出帖子和CryptoCompatibility示例,并使用以下代码加载证书:
NSData *certD = [self decodeBase64:base64Certificate];
NSAssert(certD != nil, @"Could not load certificate");
CFDataRef certData = CFBridgingRetain(certD);
SecCertificateRef publicCertificate = SecCertificateCreateWithData(CFAllocatorGetDefault(), certData);
NSAssert(publicCertificate != NULL, @"Invalid public certificate");
CFRelease(certData);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef trustRef;
OSStatus trustResult = SecTrustCreateWithCertificates(publicCertificate, policy, &trustRef);
NSAssert1(trustResult == 0, @"Bad trust result: %d", trustResult);
SecTrustResultType trustEvalResult;
trustResult = SecTrustEvaluate(trustRef, &trustEvalResult);
NSAssert1(trustResult == 0, @"Bad trust eval result: %d", trustResult);
NSAssert1(trustEvalResult == kSecTrustResultProceed, @"Trust eval result not proceed: %d", trustEvalResult);
keyRef = SecTrustCopyPublicKey(trustRef);
NSAssert(keyRef != NULL, @"Could not copy public key");
CFRelease(policy);
CFRelease(trustRef);
从CryptoCompatibility示例中复制decodeBase64方法:
const char * stringC = [base64String UTF8String];
size_t stringCLength = strlen(stringC);
NSMutableData * result = [NSMutableData dataWithLength:((stringCLength + 3) / 4) * 3];
int bytesDecoded = b64_pton(stringC, [result mutableBytes], [result length]);
if (bytesDecoded < 0) {
result = nil;
} else {
[result setLength: (NSUInteger) bytesDecoded];
}
return result;
评估信任时失败:
"Trust eval result not proceed: 6":
kSecTrustResultFatalTrustFailure
Trust denied; no simple fix is available. For example, if a certificate cannot be
verified because it is corrupted, trust cannot be established without replacing the
certificate. This value may be returned by the SecTrustEvaluate function but not stored
as part of the user trust settings.
答案 0 :(得分:0)
问题是我的证书不是DER编码的:
openssl x509 -outform der -in rsa_cert.cer -out rsa_cert.der