菜鸟教程小白 发表于 2022-12-11 22:43:10

ios - 如何在 Objective-C 或 Swift 上发送带有 .p12 证书的 https 请求


                                            <p><p>我有一个 react-native 项目,我必须为带有 .p12 认证的 https 请求创建 Native 模块,但我从不使用 Objective-C(它有点复杂)或 Swift
我找到了一个带有证书的 https 请求类 <a href="https://raw.githubusercontent.com/xdumaine/ios-secure-request/master/secure-request.m" rel="noreferrer noopener nofollow">it is</a>但我没有使用这个,因为我没有 .h 文件和我的项目文件夹;</p>

<p><strong>MyBridge.h</strong></p>

<pre><code>#import &#34;React/RCTBridgeModule.h&#34;

@interface MyFirstBridge : NSObject &lt;RCTBridgeModule&gt;

@end
</code></pre>

<p><strong>MyBridge.m</strong></p>

<pre><code>#import &#34;MyFirstBridge.h&#34;
#import &lt;React/RCTLog.h&gt;

@implementation MyFirstBridge

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(sendGetRequest:(NSString *)urllocation:(NSString *)location)
{
NSMutableURLRequest *request = [ init];
;
];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

NSData *oResponseData = ;

if( != 200){
    NSLog(@&#34;Error getting %@, HTTP status code %i&#34;, url, );
    return nil;
}

callback(@[, [ initWithData:oResponseData encoding:NSUTF8StringEncoding]]);
}

@end
</code></pre>

<p>它作为基本的 <code>HTTP</code> 获取请求,但是当我尝试 https 服务时,我需要为每个请求固定一个证书。对于这种情况,如何发送 <code>HTTPS</code> 请求?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我猜通过使用 .p12 证书,您指的是在客户端和服务器之间建立相互身份验证。基本上,你必须经过以下步骤(objective-c):</p>

<ul>
<li>创建验证服务器(根据根 CA 签名验证其签名)和验证客户端(向服务器提供客户端证书以验证其签名)所需的安全对象。加载 CA 的 .cer 文件和客户端的 .p12 文件。</li>
<li>定义你要检索和创建 NSURLConnection 的 URL 资源</li>
<li>指定您要处理的身份验证方法(使用 NSURLConnectionDelegate 回调)</li>
<li>处理身份验证质询(使用 NSURLConnectionDelegate 回调)</li>
</ul>

<p><strong>加载证书文件(服务器的根 CA 证书 + 客户端 key 和证书)</strong></p>

<p>rootCertRef 包含 CA 证书(签署服务器证书的 CA 的根证书)</p>

<p>身份 (SecIdentityRef) 包含向服务器验证客户端所需的客户端 key 和证书。</p>

<pre><code>NSData *rootCertData = pathForResource:@”rootCert” ofType:@”cer”]];
SecCertificateRef rootCertRef = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef) rootCertData);

NSData *p12Data = pathForResource:@“clientCert&#34; ofType:@&#34;p12&#34;]];
NSArray *item = nil;
NSDictionary *dict = ;
SecPKCS12Import((CFDataRef) p12Data , (CFDictionaryRef)dict, (CFArrayRef *)item);
SecIdentityRef identity = (SecIdentityRef)[ objectForKey:(id)kSecImportItemIdentity];
</code></pre>

<p><strong>配置网址</strong>(您已经完成了)</p>

<pre><code>// Create the request.
NSURLRequest *request = ];
</code></pre>

<p><strong>创建 NSURLConnection</strong>>> 将委托(delegate)设置为 self 必须实现 NSURLConnectionDelegate 才能进行客户身份验证</p>

<pre><code>// Create url connection and fire request asynchronously
NSURLConnection *conn = [ initWithRequest:request delegate:self];
</code></pre>

<p><strong>在回调 canAuthenticateAgainstProtectionSpace 中启用服务器和客户端身份验证</strong></p>

<pre><code>- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
if([ isEqualToString:NSURLAuthenticationMethodServerTrust])
    return YES;
if([ isEqualToString:NSURLAuthenticationMethodClientCertificate])
    return YES;
return NO;
}
</code></pre>

<p><strong>执行服务器请求的相互认证</strong></p>

<pre><code>-(void) connection:didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

//Authenticate the server
if([ isEqualToString:NSURLAuthenticationMethodServerTrust]) { // Verify method

    SecTrustRef trust = [ serverTrust];         // Create trust object
    NSArray *trustArray = ;   // Add as many certificates as needed
    SecTrustSetAnchorCertificates(trust, (CFArrayRef) trustArray );      // Set trust anchors

    SecTrustResultType trustResult;                                        // Store trust result in this
    SecTrustEvaluate(trust, trustResult);                                  // Evaluate server trust
    if(trust_result == kSecTrustResultUnspecified) {
      NSURLCredential *credential = ;
      [ useCredential:credential forAuthenticationChallenge:challenge];
} else {
    // handle error;
}

//Send client identity to server for client authentication
if([ authenticationMethod] isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
    NSURLCredential *credential = ;
    [ useCredential:credential forAuthenticationChallenge:challenge];
}
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在 Objective-C 或 Swift 上发送带有 .p12 证书的 https 请求,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/55758377/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/55758377/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在 Objective-C 或 Swift 上发送带有 .p12 证书的 https 请求