iOS with a self-signed certificate realize HTTPS requests

iOS with a self-signed certificate realize HTTPS requests

HTTPS:

In simple terms, HTTPS SSL protocol is the HTTP protocol plus a layer of encryption, HTTP Security. Compared to HTTP, HTTPS can ensure that the content will not be a third-party view in the transmission process, the timely detection of tampering by a third party to transfer content, prevent identity pretending to more effectively ensure the security of network data.

HTTPS client and server interaction:
1, when the client first request, the server returns a digital certificate containing the public key to the client;
2, the client generates a symmetric encryption key and public key encrypts its obtained after returning to the server;
3, the server uses its own private key to decrypt the received encrypted data to obtain the symmetric encryption key and stored;
4, and then transmitted through both symmetric encryption data.


IOS create a self-signed https step certificate

Note: The steps only for internal use or test configuration required SSL certificate . If you want to generate two-way authentication certificate, please refer to: production inside certificates //www.2cto.com/article/201411/347512.html: http

Step 1: generating a private key

Use openssl tool to generate an RSA private key


$ openssl genrsa -des3 -out server.key 2048

Description: Generate rsa private key, des3 algorithm, 2048 strength, server.key is secret key filename.


Note: generating a private key, you need to provide a password of at least four.


Step 2: generating a CSR (Certificate Signing Request)

After generating a private key, you can create csr files.


At this point you have two choices. After Ideally, the certificate can be sent to a certificate authority (CA), CA verified the identity of the requester, it will issue a signed certificate (very expensive). Further, if only the inside or the test requirements, may be implemented using a self-signed OpenSSL, as follows:




$ openssl req -new -key server.key -out server.csr

Description: Enter need to turn the country, region, city, organization, organizational unit, Common Name and Email. Where Common Name, or you can write your own domain name, if you want to support https, Common Name should be consistent with the domain name, otherwise it will cause the browser warning.



Country Name (2 letter code) [AU]:CN

State or Province Name (full name) [Some-State]:Beijing

Locality Name (eg, city) []:Beijing

Organization Name (eg, company) [Internet Widgits Pty Ltd]:joyios

Organizational Unit Name (eg, section) []:info technology

Common Name (e.g. server FQDN or YOUR name) []:demo.joyios.com

Email Address []:[email protected]



Step 3: Remove the private key password

During the first step to create a private key, because the need to specify a password. And this code will bring a side effect, that is, each time you start the Apache Web server, will be asked to enter a password, which is obviously very inconvenient. To delete the private key in the password, as follows:



cp server.key server.key.org

openssl rsa -in server.key.org -out server.key



Step 4: Generate a self-signed certificate

If you do not want to spend money to help CA signature, or just test specific implementation of SSL. Well, now you can begin to generate a self-signed certificate of.


Note that, in the use of temporary self-signed certificates, the browser will prompt the certificate authority is unknown.



$ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Description: There certificate holder information, the holder of the public key, and the signing of the information's signature on the crt. When the user installed the certificate, it means trusting this certificate, which also has a public key. It will explain the use of the certificate, such as server authentication, client authentication, or to sign other certificates. When the system receives a new certificate when the certificate will explain, who is signed. If the signer indeed signed by other certificates, and receive a public key signature and signer of the certificate can on time, the system will automatically trust the new certificate.


Step 5: Install the private key and certificate

Copy the private key and certificate files to the Apache configuration directory, and Mac 10.10 system, copied to / etc / apache2 / directory can be.




Step 6: Clients use AF3.0 use a custom certificate


Copy the code

1. Initialize // singleton

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

manager.securityPolicy.SSLPinningMode = AFSSLPinningModeCertificate;

// 2. Set the certificate mode

NSString * cerPath = [[NSBundle mainBundle] pathForResource:@”xxx” ofType:@”cer”];

NSData * cerData = [NSData dataWithContentsOfFile:cerPath];

manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSSet alloc] initWithObjects:cerData, nil]];

// illegal whether the client trust certificates

mgr.securityPolicy.allowInvalidCertificates = YES;

// Verify that the domain name in the Domain field in the certificate

[mgr.securityPolicy setValidatesDomainName:NO];

Copy the code

2. request AFNetworking


AFNetworking first need to configure AFSecurityPolicy class, AFSecurityPolicy class encapsulates the certificate verification process.


Copy the code

/**

AFSecurityPolicy verification in three modes:

AFSSLPinningModeNone: just verify whether the certificate trust list

AFSSLPinningModeCertificate: This mode verifies whether the certificate trust list, and then compare the server certificates and client certificates are the same

AFSSLPinningModePublicKey: if only validates the server certificate and public key of the same client certificate

*/


AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

securityPolicy.allowInvalidCertificates = YES; // whether to allow the use of self-signed certificates

securityPolicy.validatesDomainName = NO; // need to verify whether the domain name, the default YES


AFHTTPSessionManager *_manager = [AFHTTPSessionManager manager];

_manager.responseSerializer = [AFHTTPResponseSerializer serializer];

_manager.securityPolicy = securityPolicy;

// set timeout

[_manager.requestSerializer willChangeValueForKey:@”timeoutinterval”];

_manager.requestSerializer.timeoutInterval = 20.f;

[_manager.requestSerializer didChangeValueForKey:@”timeoutinterval”];

_manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringCacheData;

_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@”application/xml”,@”text/xml”,@”text/plain”,@”application/json”,nil];


__weak typeof(self) weakSelf = self;

[_manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *_credential) {


SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];

/**

* Import multiple CA certificates

*/

NSString * cerPath = [[NSBundle mainBundle] pathForResource: @ "ca" ofType: @ "cer"]; // self-signed certificate

NSData* caCert = [NSData dataWithContentsOfFile:cerPath];

NSArray *cerArray = @[caCert];

weakSelf.manager.securityPolicy.pinnedCertificates = cerArray;


SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCert);

NSCAssert(caRef != nil, @”caRef is nil”);


NSArray *caArray = @[(__bridge id)(caRef)];

NSCAssert(caArray != nil, @”caArray is nil”);


OSStatus status = SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray);

SecTrustSetAnchorCertificatesOnly(serverTrust,NO);

NSCAssert(errSecSuccess == status, @”SecTrustSetAnchorCertificates failed”);


NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;

__autoreleasing NSURLCredential *credential = nil;

if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

if ([weakSelf.manager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {

credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

if (credential) {

provision = NSURLSessionAuthChallengeUseCredential;

} else {

provision = NSURLSessionAuthChallengePerformDefaultHandling;

}

} else {

provision = NSURLSessionAuthChallengeCancelAuthenticationChallenge;

}

} else {

provision = NSURLSessionAuthChallengePerformDefaultHandling;

}


return disposition;

}];

Copy the code

The code provided by a certificate validation callback AFHTTPSessionManager again to verify their certificate, own certificate and then added to the list of trusted certificate, the certificate by checking to.


Guess you like

Origin blog.51cto.com/14588847/2467031