NSURLConnectionでSSL認証(p12)をする事がありましたのでサンプルコードを乗せておきます。
自由に使用してください。
サンプルコードの説明
p12ファイル”newcert.p12″を読み込み、newcert.p12のpasswordは”pkcs23password”となります。
当たり前ですが、パスワードとp12ファイルはダンプしても見えないように暗号化しましょう。
使用メソッド
<NSURLConnectionDelegate>
– (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
Sample Code
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ( [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic] ||
[challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPDigest] )
{
NSLog(@"Basic認証");
}
else if ( [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] ||
[challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate])
{
NSLog(@"SSL認証(p12)");
OSStatus status;
CFArrayRef importedItems = NULL;
// パスワード設定
NSString *password = @"pkcs23password";
// 認証データP12のファイルを読み込み
NSData *PKCS12Data = [NSData dataWithContentsOfFile:@"newcert.p12"];
status = SecPKCS12Import((__bridge CFDataRef)PKCS12Data,
(__bridge CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:password,
kSecImportExportPassphrase,
nil],
&importedItems);
if (status == errSecSuccess) {
NSArray* items = (__bridge NSArray*)importedItems;
SecIdentityRef identityRef = (__bridge SecIdentityRef)[[items objectAtIndex:0] objectForKey:(__bridge id)kSecImportItemIdentity];
NSURLCredential* credential = [NSURLCredential credentialWithIdentity:identityRef
certificates:nil
persistence:NSURLCredentialPersistenceNone];
// 認証送信(?)
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
if (importedItems != NULL)
CFRelease(importedItems);
}
}
}
以上、


コメント