背景:
我正在编写一个客户端实用程序,它能够使用SSL / TLS连接到远程服务器.客户端使用OpenSSL执行SSL / TLS事务,我希望允许用户指定用于签署服务器证书的授权CA Certs(在自签名证书或私有CA设置的情况下).我计划使用cert的指纹,通用名称和有效日期,以允许用户快速查看客户端用于验证服务器的证书.
题:
如何使用C/C++ / Objective-C计算存储在PEM文件中的X509证书的SHA1哈希/指纹?
解决方法
我在下面发现产生与上面相同的输出:
+(NSData *)sha1:(SecCertificateRef) cert { // fingerprint is over canonical DER rep. CFDataRef data = SecCertificateCopyData(cert); NSData * out = [[NSData dataWithBytes:CFDataGetBytePtr(data) length:CFDataGetLength(data)] sha1Digest]; CFRelease(data); return out; }
它在目标C中有点短.它需要NSData / NSString的以下扩展,但要使格式接近Netscape,OSX或Windows.
- (NSData *)md5Digest { unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5([self bytes],(CC_LONG)[self length],result); return [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH]; } - (NSData *)sha1Digest { unsigned char result[CC_SHA1_DIGEST_LENGTH]; CC_SHA1([self bytes],result); return [NSData dataWithBytes:result length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)hexStringValue { NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:([self length] * 2)]; const unsigned char *dataBuffer = [self bytes]; int i; for (i = 0; i < [self length]; ++i) { [stringBuffer appendFormat:@"%02lx",(unsigned long)dataBuffer[i]]; } return [stringBuffer copy]; } - (NSString *)hexColonSeperatedStringValue { return [self hexColonSeperatedStringValueWithCapitals:YES]; } - (NSString *)hexColonSeperatedStringValueWithCapitals:(BOOL)capitalize { NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:([self length] * 3)]; const unsigned char *dataBuffer = [self bytes]; NSString * format = capitalize ? @"%02X" : @"%02x"; int i; for (i = 0; i < [self length]; ++i) { if (i) [stringBuffer appendString:@":"]; [stringBuffer appendFormat:format,(unsigned long)dataBuffer[i]]; } return [stringBuffer copy]; }