Introduction (Creating a generated certificate can only be used for test use.) If you want to use a self-signed certificate, you can only issue certificates to the CA authority for two-way authentication to use.
The use of HTTP (Hypertext Transfer) protocol to access data on the Internet is not encrypted. That is, anyone can intercept or listen to a stream of data that is transmitted over the network through the appropriate tools. But sometimes we need to transmit some security or privacy data on the Internet, such as electronic orders that contain credit cards and commodity information. this time, if you still use the HTTP protocol, you are bound to face a very large risk! Believe that no one can accept their credit card number on the internet to run naked.
The HTTPS (Hypertext Transport Security) protocol is undoubtedly an effective solution to this problem. The so-called HTTPS, in fact, is a combination of HTTP and SSL/TLS to provide encrypted communication and authentication of the network server. The main idea of HTTPS is to create a secure channel on an unsecured network to prevent hackers from eavesdropping and attacking.
SSL (Secure Sockets Layer) can be used to encrypt the flow of data between the Web server and the client.
SSL encrypts data using asymmetric cryptographic techniques. The encryption process uses two keys: a public key and a corresponding private key. Data encrypted with the public key can only be decrypted with the corresponding private key, and the data encrypted with the private key can only be decrypted with the corresponding public key. Therefore, if the message or traffic that is transmitted over the network is encrypted by the private key of the server, it can only be decrypted with its corresponding public key, thereby guaranteeing the security of the data between the client and the server.
Digital certificate (Certificate)
In the process of HTTPS transmission, there is a very critical role-digital certificate, then what is a digital certificate? What's the effect?
The so-called digital certificate, is a computer for the identification mechanism. A signature (stamped) by a digital certification authority (CA) on a signature request file created with the private key, indicating the CA structure's endorsement of the certificate holder. Digital certificates have several advantages:
- Use of digital certificates can increase user confidence
- The public key in the digital certificate can be paired with the private key of the server to realize the encryption and decryption during data transmission.
- Sensitive personal data of the user is not transmitted to the certificate holder's network system during the identity of the user
The ten-X certificate contains three files: Key,csr,crt.
- Key is a private key file on the server that is used to encrypt the data sent to the client and to decrypt the data received from the client
- A CSR is a certificate signing request file that is used to submit a certificate signing to a certification authority (CA)
- A CRT is a certificate signed by a Certificate authority (CA), or a developer's self-signed certificate that contains information about the holder of the certificate, the public key of the holder, and the signature of the signer, among others
Note: In cryptography, the number is a standard, the specification of public key authentication, certificate revocation list, authorization credentials, credential path verification algorithm.
Steps to create a self-signed certificate
Note: The following steps are only used to configure SSL certificates that are required for internal use or testing. If you want to generate two-way authentication certificate, please refer to: Http://www.2cto.com/article/201411/347512.html Inside Certificate production
1th step: Generate the private key
Generate an RSA private key using the OpenSSL tool
1 |
$ OpenSSL genrsa -des3 -out server. Key 2048 |
Description: Generate RSA private key, DES3 algorithm, 2048-bit strength, Server.key is the secret key file name.
Note: To generate a private key, you need to provide a password of at least 4 bits.
2nd step: Generate CSR (certificate signing request)
Once the private key is generated, you can create a CSR file.
There are two options available at this time. Ideally, you can send a certificate to a certification authority (CA), which, after the CA has verified the requestor's identity, will issue a signing certificate (very expensive). In addition, you can use OpenSSL to self-sign if you are only in-house or test requirements:
1 |
$ openssl< Span class= "crayon-h" > req -< Span class= "CRAYON-E" >new -key server. Key -out server. CSR |
Description: You need to enter country, region, city, organization, organizational unit, Common name and email in turn. where Common name, you can write your own name or domain name, if you want to support Https,common name should be consistent with the domain name, otherwise it will cause a browser warning.
1234567 |
Country Name (2 letter code) [AU]:CN state or province Name (full name) [< Span class= "Crayon-r" >some-state]:beijing locality name (eg, city) [< Span class= "Crayon-sy" >]:beijing organization Name (eg, company) < Span class= "Crayon-sy" >[internet Widgits pty ltd]:joyios organizational Unit name ( eg, section< Span class= "Crayon-sy" >) []:info technology common name (e. G. server FQDN or YOUR name) []:demojoyios. COM Email Address []:liufan@joyios. COM |
3rd Step: Remove the password from the private key
During the 1th step of creating the private key, you must specify a password. And this password has a side effect, that is, every time Apache starts the Web server, will be asked to enter a password, which is obviously very inconvenient. To remove a password from the private key, proceed as follows:
12 |
cp server.< Span class= "crayon-i" >key server.< Span class= "crayon-i" >key. org OpenSSL RSA -in server. Key. Org -out server. Key |
4th step: Generate a self-signed certificate
If you don't want to spend money on a CA signing, or just testing the specifics of SSL implementations. Now it's time to start generating a self-signed certificate.
It is important to note that when you use a self-signed temporary certificate, the browser prompts the certificate authority to be unknown.
1 |
$Openssl X509 -req < Span class= "Crayon-o" >-days 365 -in server. Csr -signkey server. Key -out server. CRT |
Description: The CRT has information about the certificate holder, the holder's public key, and the signature of the signer. When a user installs a certificate, it means that the certificate is trusted and has the public key. The certificate will describe the purpose, such as server authentication, client authentication, or signing other certificates. When the system receives a new certificate, the certificate will indicate who signed it. The system automatically trusts the new certificate if the signer can actually sign the other certificate and receives the signature on the certificate and the signer's public key.
5th step: Install the private key and certificate
Copy the private key and certificate files to the Apache configuration directory, and in the Mac 10.10 System, copy to the/etc/apache2/directory.
6th step: The client uses AF3.0 to use the custom certificate
1.
/ / 1. Initialize the singleton class
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]];
// Does the client trust an illegal certificate?
mgr.securityPolicy.allowInvalidCertificates = YES;
// Whether to verify the domain name in the certificate domain field
[mgr.securityPolicy setValidatesDomainName:NO];
2. Using Afnetworking for requests
Afnetworking first needs to configure the Afsecuritypolicy class, and the Afsecuritypolicy class encapsulates the process of certificate validation.
/**
AFSecurityPolicy is divided into three authentication modes:
AFSSLPinningModeNone: just verify that the certificate is in the trust list
AFSSLPinningModeCertificate: This mode verifies whether the certificate is in the trust list, and then compares whether the server certificate and the client certificate are consistent.
AFSSLPinningModePublicKey: Only verify that the server certificate is the same as the public key of the client certificate.
*/
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
securityPolicy.allowInvalidCertificates = YES;//Do you allow self-signed certificates?
securityPolicy.validatesDomainName = NO; / / Whether you need to verify the domain name, the default YES
AFHTTPSessionManager *_manager = [AFHTTPSessionManager manager];
_manager.responseSerializer = [AFHTTPResponseSerializer serializer];
_manager.securityPolicy = securityPolicy;
/ / Set the 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 evaluationServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
Credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
If (credential) {
Disposition = NSURLSessionAuthChallengeUseCredential;
} else {
Disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
Disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else {
Disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
Return disposition;
}];
The code above validates the certificate itself by re-setting the certificate validation callback to Afhttpsessionmanager and then joins its own certificate to the list of trusted certificates, which can be verified by the certificate.
iOS adaptation HTTPS, creating a self-signed SSL certificate (X509) Specific steps