如何在C/C++ / Objective-C中计算X.509证书的SHA-1指纹?

前端之家收集整理的这篇文章主要介绍了如何在C/C++ / Objective-C中计算X.509证书的SHA-1指纹?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
背景:

我正在编写一个客户端实用程序,它能够使用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];
}

猜你在找的C&C++相关文章