UIWebView中的SSL证书详细信息

时间:2015-05-19 06:07:56

标签: ios ssl uiwebview ssl-certificate

我需要在UIWebView中显示所显示网址的SSL证书详情,例如Google的Chrome浏览器显示:

enter image description here

如何从UIWebView获取此数据。

1 个答案:

答案 0 :(得分:0)

我们正在拦截网络级别的呼叫(而不是UIWebView),并使用[NSURLConnectionDelegate connection:willSendRequestForAuthenticationChallenge:]。这会为您提供NSURLAuthenticationChallenge个实例,如果challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrustNSURLAuthenticationChallenge.protectionSpace.serverTrustSecTrustRef

鉴于SecTrustRef,您可以关注SecCertificateRef: How to get the certificate information?并执行以下操作:

#import <Security/Security.h>
#import <openssl/x509.h>

X509* X509CertificateFromSecTrust(SecTrustRef trust) {
    SecCertificateRef cert = SecTrustGetCertificateAtIndex(trust, 0);
    CFDataRef certDataRef = SecCertificateCopyData(cert);
    NSData *certData = (__bridge NSData *)certDataRef;

    const void* certDataBytes = certData.bytes;
    X509* result = d2i_X509(NULL, (const unsigned char**)&certDataBytes, certData.length);

    CFRelease(certDataRef);

    return result;
}

static NSString* X509NameField(X509_NAME* name, char* key) {
    if (name == NULL)
        return nil;

    int nid = OBJ_txt2nid(key);
    int index = X509_NAME_get_index_by_NID(name, nid, -1);

    X509_NAME_ENTRY *nameEntry = X509_NAME_get_entry(name, index);
    if (nameEntry == NULL)
        return nil;

    ASN1_STRING *nameASN1 = X509_NAME_ENTRY_get_data(nameEntry);
    if (nameASN1 == NULL)
        return nil;

    unsigned char *issuerName = ASN1_STRING_data(nameASN1);
    return [NSString stringWithUTF8String:(char *)issuerName];
}

NSString* X509CertificateGetSubjectCommonName(X509* cert) {
    if (cert == NULL)
        return nil;

    X509_NAME *subjectName = X509_get_subject_name(cert);
    return X509NameField(subjectName, "CN"); // Common name.
}


NSString* X509CertificateGetIssuerName(X509* certX509) {
    if (certX509 == NULL)
        return nil;

    X509_NAME *issuerX509Name = X509_get_issuer_name(certX509);
    if (issuerX509Name == NULL)
        return nil;

    return X509NameField(issuerX509Name, "O"); // organization
}

这不是一件简单的工作。您需要了解OpenSSL的X​​509代码,安全框架以及您在网络层进行SSL信任检查所做的任何事情。您可以通过其他方式获取SecTrustRef或SecCertificateRef,但如果有,我不会使用它们。