HTTPS网络加密双向验证->使用AFNetworking封装
2017-02-27 14:05
561 查看
1.首先使用OC封装请求头
#import <Foundation/Foundation.h>
#import "AFNetworking.h"
@interface HttpsHandler :
NSObject
+ (AFHTTPSessionManager *)setHttpsMange;
@end
2.实现方法
+ (AFHTTPSessionManager *)setHttpsMange;
{
NSString *certFilePath = [[NSBundle
mainBundle] pathForResource:@"mykey"
ofType:@"cer"];
NSData *certData = [NSData
dataWithContentsOfFile:certFilePath];
NSSet *certSet = [NSSet
setWithObject:certData];
AFSecurityPolicy *policy = [AFSecurityPolicy
policyWithPinningMode:AFSSLPinningModeNone
withPinnedCertificates:certSet];
policy.allowInvalidCertificates =
YES;//是否允许不信任的证书通过验证,默认为NO
policy.validatesDomainName =
NO;//是否验证主机名,默认为YES
__weak
AFHTTPSessionManager *_manager = [AFHTTPSessionManager
manager];
_manager.securityPolicy = policy;
_manager.requestSerializer = [AFHTTPRequestSerializer
serializer];
_manager.responseS
1374e
erializer = [AFHTTPResponseSerializer
serializer];
_manager.requestSerializer = [AFHTTPRequestSerializer
serializer];
_manager.responseSerializer = [AFJSONResponseSerializer
serializer];
[_manager.requestSerializer
setValue:@"application/json"
forHTTPHeaderField:@"Content-Type"];
_manager.responseSerializer.acceptableContentTypes = [NSSet
setWithObject:@"application/json"];
[_manager.requestSerializer
setValue:@"application/json"
forHTTPHeaderField:@"Accept"];
_manager.responseSerializer.acceptableContentTypes = [NSSet
setWithObjects:@"application/json",
@"text/json", @"text/javascript",
@"text/plain", @"text/html",@"application/text",
nil];
//关闭缓存避免干扰测试r
_manager.requestSerializer.cachePolicy =
NSURLRequestReloadIgnoringLocalCacheData;
[_manager setSessionDidBecomeInvalidBlock:^(NSURLSession *
_Nonnull session,
NSError * _Nonnull error) {
NSLog(@"setSessionDidBecomeInvalidBlock");
}];
//客户端请求验证
重写 setSessionDidReceiveAuthenticationChallengeBlock
方法
__weak
typeof(self)weakSelf =
self;
[_manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session,
NSURLAuthenticationChallenge *challenge,
NSURLCredential *__autoreleasing*_credential) {
NSURLSessionAuthChallengeDisposition disposition =
NSURLSessionAuthChallengePerformDefaultHandling;
__autoreleasing
NSURLCredential *credential =nil;
if([challenge.protectionSpace.authenticationMethod
isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if([_manager.securityPolicy
evaluateServerTrust:challenge.protectionSpace.serverTrust
forDomain:challenge.protectionSpace.host]) {
credential = [NSURLCredential
credentialForTrust:challenge.protectionSpace.serverTrust];
if(credential) {
disposition =NSURLSessionAuthChallengeUseCredential;
} else {
disposition =NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else {
// client authentication
SecIdentityRef identity =
NULL;
SecTrustRef trust =
NULL;
NSString *p12 = [[NSBundle
mainBundle] pathForResource:@"mykey"ofType:@"p12"];
NSFileManager *fileManager =[NSFileManager
defaultManager];
if(![fileManager
fileExistsAtPath:p12])
{
NSLog(@"client.p12:not exist");
}
else
{
NSData *PKCS12Data = [NSData
dataWithContentsOfFile:p12];
if ([[weakSelf
class]extractIdentity:&identity
andTrust:&trust fromPKCS12Data:PKCS12Data])
{
SecCertificateRef certificate =
NULL;
SecIdentityCopyCertificate(identity, &certificate);
const
void*certs[] = {certificate};
CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault,
certs,1,NULL);
credential =[NSURLCredential
credentialWithIdentity:identity
certificates:(__bridge
NSArray*)certArray
persistence:NSURLCredentialPersistencePermanent];
disposition =NSURLSessionAuthChallengeUseCredential;
}
}
}
*_credential = credential;
return disposition;
}];
return _manager;
}
最后 加上这些
+(BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef
*)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
OSStatus securityError =
errSecSuccess;
//client certificate password
NSDictionary*optionsDictionary = [NSDictionary
dictionaryWithObject:@"password"
forKey:(__bridge
id)kSecImportExportPassphrase];
CFArrayRef items =
CFArrayCreate(NULL,
0, 0,
NULL);
securityError = SecPKCS12Import((__bridge
CFDataRef)inPKCS12Data,(__bridge
CFDictionaryRef)optionsDictionary,&items);
if(securityError ==
0) {
CFDictionaryRef myIdentityAndTrust =CFArrayGetValueAtIndex(items,0);
const
void*tempIdentity =NULL;
tempIdentity= CFDictionaryGetValue (myIdentityAndTrust,kSecImportItemIdentity);
*outIdentity = (SecIdentityRef)tempIdentity;
const
void*tempTrust =NULL;
tempTrust = CFDictionaryGetValue(myIdentityAndTrust,kSecImportItemTrust);
*outTrust = (SecTrustRef)tempTrust;
} else {
NSLog(@"Failedwith error code %d",(int)securityError);
return
NO;
}
return
YES;
}
#import <Foundation/Foundation.h>
#import "AFNetworking.h"
@interface HttpsHandler :
NSObject
+ (AFHTTPSessionManager *)setHttpsMange;
@end
2.实现方法
+ (AFHTTPSessionManager *)setHttpsMange;
{
NSString *certFilePath = [[NSBundle
mainBundle] pathForResource:@"mykey"
ofType:@"cer"];
NSData *certData = [NSData
dataWithContentsOfFile:certFilePath];
NSSet *certSet = [NSSet
setWithObject:certData];
AFSecurityPolicy *policy = [AFSecurityPolicy
policyWithPinningMode:AFSSLPinningModeNone
withPinnedCertificates:certSet];
policy.allowInvalidCertificates =
YES;//是否允许不信任的证书通过验证,默认为NO
policy.validatesDomainName =
NO;//是否验证主机名,默认为YES
__weak
AFHTTPSessionManager *_manager = [AFHTTPSessionManager
manager];
_manager.securityPolicy = policy;
_manager.requestSerializer = [AFHTTPRequestSerializer
serializer];
_manager.responseS
1374e
erializer = [AFHTTPResponseSerializer
serializer];
_manager.requestSerializer = [AFHTTPRequestSerializer
serializer];
_manager.responseSerializer = [AFJSONResponseSerializer
serializer];
[_manager.requestSerializer
setValue:@"application/json"
forHTTPHeaderField:@"Content-Type"];
_manager.responseSerializer.acceptableContentTypes = [NSSet
setWithObject:@"application/json"];
[_manager.requestSerializer
setValue:@"application/json"
forHTTPHeaderField:@"Accept"];
_manager.responseSerializer.acceptableContentTypes = [NSSet
setWithObjects:@"application/json",
@"text/json", @"text/javascript",
@"text/plain", @"text/html",@"application/text",
nil];
//关闭缓存避免干扰测试r
_manager.requestSerializer.cachePolicy =
NSURLRequestReloadIgnoringLocalCacheData;
[_manager setSessionDidBecomeInvalidBlock:^(NSURLSession *
_Nonnull session,
NSError * _Nonnull error) {
NSLog(@"setSessionDidBecomeInvalidBlock");
}];
//客户端请求验证
重写 setSessionDidReceiveAuthenticationChallengeBlock
方法
__weak
typeof(self)weakSelf =
self;
[_manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session,
NSURLAuthenticationChallenge *challenge,
NSURLCredential *__autoreleasing*_credential) {
NSURLSessionAuthChallengeDisposition disposition =
NSURLSessionAuthChallengePerformDefaultHandling;
__autoreleasing
NSURLCredential *credential =nil;
if([challenge.protectionSpace.authenticationMethod
isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if([_manager.securityPolicy
evaluateServerTrust:challenge.protectionSpace.serverTrust
forDomain:challenge.protectionSpace.host]) {
credential = [NSURLCredential
credentialForTrust:challenge.protectionSpace.serverTrust];
if(credential) {
disposition =NSURLSessionAuthChallengeUseCredential;
} else {
disposition =NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else {
// client authentication
SecIdentityRef identity =
NULL;
SecTrustRef trust =
NULL;
NSString *p12 = [[NSBundle
mainBundle] pathForResource:@"mykey"ofType:@"p12"];
NSFileManager *fileManager =[NSFileManager
defaultManager];
if(![fileManager
fileExistsAtPath:p12])
{
NSLog(@"client.p12:not exist");
}
else
{
NSData *PKCS12Data = [NSData
dataWithContentsOfFile:p12];
if ([[weakSelf
class]extractIdentity:&identity
andTrust:&trust fromPKCS12Data:PKCS12Data])
{
SecCertificateRef certificate =
NULL;
SecIdentityCopyCertificate(identity, &certificate);
const
void*certs[] = {certificate};
CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault,
certs,1,NULL);
credential =[NSURLCredential
credentialWithIdentity:identity
certificates:(__bridge
NSArray*)certArray
persistence:NSURLCredentialPersistencePermanent];
disposition =NSURLSessionAuthChallengeUseCredential;
}
}
}
*_credential = credential;
return disposition;
}];
return _manager;
}
最后 加上这些
+(BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef
*)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
OSStatus securityError =
errSecSuccess;
//client certificate password
NSDictionary*optionsDictionary = [NSDictionary
dictionaryWithObject:@"password"
forKey:(__bridge
id)kSecImportExportPassphrase];
CFArrayRef items =
CFArrayCreate(NULL,
0, 0,
NULL);
securityError = SecPKCS12Import((__bridge
CFDataRef)inPKCS12Data,(__bridge
CFDictionaryRef)optionsDictionary,&items);
if(securityError ==
0) {
CFDictionaryRef myIdentityAndTrust =CFArrayGetValueAtIndex(items,0);
const
void*tempIdentity =NULL;
tempIdentity= CFDictionaryGetValue (myIdentityAndTrust,kSecImportItemIdentity);
*outIdentity = (SecIdentityRef)tempIdentity;
const
void*tempTrust =NULL;
tempTrust = CFDictionaryGetValue(myIdentityAndTrust,kSecImportItemTrust);
*outTrust = (SecTrustRef)tempTrust;
} else {
NSLog(@"Failedwith error code %d",(int)securityError);
return
NO;
}
return
YES;
}
相关文章推荐
- 验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate
- 验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate
- Android HTTPS SSL双向验证 使用HTTPs
- 使用Tomcat 9验证Https单向认证和双向认证
- 验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate。
- 验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保<machineKey>配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate。
- 使用Nginx实现HTTPS双向验证的方法
- 网络编程六:https请求(双向验证)
- 验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate。
- 使用HttpClient连接池进行https单双向验证
- 验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate。
- 验证视图MAC失败。如果此引用程序由网络场或群集承载,请确保<machineKey>配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerateP>
- 待解决问题:验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate
- 验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate
- eclipse中使用Jetty插件实现https请求与SSL双向验证
- 转载HTTPS双向验证加密过程
- SSL双向认证以及证书的制作和使用-https+客户端身份验证
- System.Web.HttpException (0x80004005): 验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate。
- 使用Nginx实现HTTPS双向验证的方法
- 验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate