怎么创建和使用SSL证书
来源:互联网 发布:网络架构方案 ppt 编辑:程序博客网 时间:2024/06/11 15:40
This document describes how to establish yourself as a root certificate authority (root CA) using the OpenSSL toolset. As a root CA, you are able to sign and install certificates for use in your Internet server applications, such as Apache andStunnel.
Scope
This document covers a very specific, limited purpose, but one that meets a common need: preventing browser, mail, and other clients from complaining about the certificates installed on your server.Not covered is dealing with a commercial root certificate authority (CA). Instead, we will become our own root CA, and sign our own certificates.
These procedures were developed using OpenSSL 0.9.6, 24 Sep 2000, on Linux.
Back to top
Quick Start
Those who want to start creating certificates right away without reading this whole document should skip to the summary at the end.Back to top
Background
Why be our own root CA? So that we can take advantage of SSL encryption without spending unnecessary money on having our certificates signed.A drawback is that browsers will still complain about our site not being trusted until our root certificate is imported. However, once this is done, we are no different from the commercial root CAs.
Clients will only import our root certificate if they trust us. This is where the commercial CAs come in: they purport to do extensive research into the people and organizations for whom they sign certificates. By importing (actually, by the browser vendors incorporating) their trusted root certificates, we are saying that we trust them when they guarantee that someone else is who they say they are. We can trust additional root CAs (like ourselves) by importing their CA certificates.
Note: If you are in the business of running a commercial secure site, obtaining a commercially signed certificate is the only realistic choice.
Back to top
Prerequisites
You will need an installed copy of OpenSSL for this, which is available fromhttp://www.openssl.org. Chances are it is already installed on your machine. This document will not cover the installation procedure.Back to top
Initial Setup
First, we will create a directory where we can work. It does not matter where this is; I am arbitrarily going to create it in my home directory.# mkdir CA# cd CA# mkdir newcerts private
- Our Certificate Authority (CA) certificate
- The database of the certificates that we have signed
- The keys, requests, and certificates we generate
The CA/newcerts directory will contain:
- A copy of each certificate we sign
- Our CA private key
- Do not lose this key. Without it, you will not be able to sign or renew any certificates.
- Do not disclose this key to anyone. If it is compromised, others will be able to impersonate you.
# echo '01' >serial# touch index.txt
---Begin---## OpenSSL configuration file.## Establish working directory.dir= .----End----
Creating a Root Certificate
With OpenSSL, a large part of what goes into a certificate depends on the contents of the configuration file, rather than the command line. This is a good thing, because there is a lot to specify.The configuration file is divided into sections, which are selectively read and processed according to openssl command line arguments. Sections can include one or more other sections by referring to them, which helps to make the configuration file more modular. A name in square brackets (e.g. "[ req ]") starts each section.
We now need to add the section that controls how certificates are created, and a section to define the type of certificate to create.
The first thing we need to specify is the Distinguished Name. This is the text that identifies the owner of the certificate when it is viewed. It is not directly referenced in the configuration file, but is included into the section processed when certificate requests are created. The command is "openssl req <args>", so the section is titled [ req ].
Add the following to openssl.cnf:
---Begin---[ req ]default_bits= 1024# Size of keysdefault_keyfile= key.pem# name of generated keysdefault_md= md5# message digest algorithmstring_mask= nombstr# permitted charactersdistinguished_name= req_distinguished_name[ req_distinguished_name ]# Variable name Prompt string#---------------------- ----------------------------------0.organizationName= Organization Name (company)organizationalUnitName= Organizational Unit Name (department, division)emailAddress= Email AddressemailAddress_max= 40localityName= Locality Name (city, district)stateOrProvinceName= State or Province Name (full name)countryName= Country Name (2 letter code)countryName_min= 2countryName_max= 2commonName= Common Name (hostname, IP, or your name)commonName_max= 64# Default values for the above, for consistency and less typing.# Variable name Value#------------------------------ ------------------------------0.organizationName_default= The Sample CompanylocalityName_default= MetropolisstateOrProvinceName_default= New YorkcountryName_default= US[ v3_ca ]basicConstraints= CA:TRUEsubjectKeyIdentifier= hashauthorityKeyIdentifier= keyid:always,issuer:always----End----
All the preparation is now in place for creating our self-signed root certificate. For this, we want to override some of the defaults we just put into the configuration, so we will specify our overrides on the command line.
Our overrides to the "openssl req" command are:
- Create a new self-signed certificate: -new -x509
- Create a CA certificate: -extensions v3_ca
- Make it valid for more than 30 days: -days 3650
- Write output to specific locations: -keyout, -out
- Use our configuration file: -config ./openssl.cnf
Run the command as shown. In this case, the PEM pass phrase it asks for is a new one, which you must enter twice:
# openssl req -new -x509 -extensions v3_ca -keyout private/cakey.pem \-out cacert.pem -days 3650 -config ./openssl.cnfUsing configuration from ./openssl.cnfGenerating a 1024 bit RSA private key.......++++++..........................++++++writing new private key to 'private/cakey.pem'Enter PEM pass phrase:demoVerifying password - Enter PEM pass phrase:demo-----You are about to be asked to enter information that will be incorporatedinto your certificate request.What you are about to enter is what is called a Distinguished Name or a DN.There are quite a few fields but you can leave some blankFor some fields there will be a default value,If you enter '.', the field will be left blank.-----Organization Name (company) [The Sample Company]:<enter>Organizational Unit Name (department, division) []:CA DivisionEmail Address []:ca@sample.comLocality Name (city, district) [Metropolis]:<enter>State or Province Name (full name) [New York]:<enter>Country Name (2 letter code) [US]:<enter>Common Name (hostname, IP, or your name) []:TSC Root CA
- A private key in private/cakey.pem
- A root CA certificate in cacert.pem
The private key (cakey.pem) looks like this:
-----BEGIN RSA PRIVATE KEY-----Proc-Type: 4,ENCRYPTEDDEK-Info: DES-EDE3-CBC,0947F49BB28FE5F4jlQvt9WdR9Vpg3WQT5+C3HU17bUOwvhp/r0+viMcBUCRW85UqI2BJJKTi1IwQQ4ctyTrhYJYOP+A6JXt5BzDzZy/B7tjEMDBosPiwH2m4MaP+6wTbi1qR1pFDL3fXYDrZsuN08dkbw9ML6LOX5Rl6bIBL3i5hnGiqm338Fl52gNstThv0C/OZhXT3B4qsJn8qZb3mC6U2nRaP/NpZPcEx4lv2vH7OzHTu1TZ7t0asSpgpuH58dfHPw775kZDep2FLXA3Oeavg0TLFHkaFBUx2xaeEG6Txpt9I74aAsw1T6UbTSjqgtsK0PHdjPNfPGlY5U3Do1pnU9hfoem/4RAOe0cCovP/xf6YPBraSFPs4XFfnWwgEtL09ReFqO9T0aSp5ajLyBOYOBKQ3PCSu1HQDw/OzphInhKxdYg81WBBEfELzSdMFQZgmfGrt5DyyWmqTADwWtGVvO3pEhO1STmCaNqZQSpSwEGPGo5RFkyFvyvyozWX2SZg4g1o1X40qSg90FMHTEB5HQebEkKBoRQMCJN/uyKXTLjNB7ibtVbZmfjsi9oNd3NJNVQQH+o9I/rPwtFsjs+t7SKrsFB2cxZQdDlFzD6EBA+5ytebGEI1lJHcOUEa6P+LTphlwh/o1QuNIKX2YKHA4ePrBzdgZ+xZuSLn/Qtjg/eZv6i73VXoHk8EdxfOk5xkJ+DnsNmyx0vqW53+O05j5xsxzDJfWr1lqBlFF/OkIYCPcyK1iLs4GOwe/V0udDNwr2Uw90tefr3qX1OZ9Dix+U0u6xXTZTETJ5dF3hV6GF7hP3Tmj9/UQdBwBzr+D8YWzQ==-----END RSA PRIVATE KEY-----
The certificate (cacert.pem) looks like this:
-----BEGIN CERTIFICATE-----MIIDrTCCAxagAwIBAgIBADANBgkqhkiG9w0BAQQFADCBnDEbMBkGA1UEChMSVGhlIFNhbXBsZSBDb21wYW55MRQwEgYDVQQLEwtDQSBEaXZpc2lvbjEcMBoGCSqGSIb3DQEJARYNY2FAc2FtcGxlLmNvbTETMBEGA1UEBxMKTWV0cm9wb2xpczERMA8GA1UECBMITmV3IFlvcmsxCzAJBgNVBAYTAlVTMRQwEgYDVQQDEwtUU0MgUm9vdCBDQTAeFw0wMTEyMDgwNDI3MDVaFw0wMjEyMDgwNDI3MDVaMIGcMRswGQYDVQQKExJUaGUgU2FtcGxlIENvbXBhbnkxFDASBgNVBAsTC0NBIERpdmlzaW9uMRwwGgYJKoZIhvcNAQkBFg1jYUBzYW1wbGUuY29tMRMwEQYDVQQHEwpNZXRyb3BvbGlzMREwDwYDVQQIEwhOZXcgWW9yazELMAkGA1UEBhMCVVMxFDASBgNVBAMTC1RTQyBSb290IENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDaiAwfKB6ZBtnTRTIo6ddomt0S9ec0NcuvtJogt0s9dXpHowh98FCDjnLtCi8du6LDTZluhlOtTFARPlV/LVnpsbyMCXMsG2qpdjJop+XIBdvoCz2HpGXjUmym8WLqt+coWwJqUSwiEba74JG93v7TU+Xcvc005MWnxmKZzD/R3QIDAQABo4H8MIH5MAwGA1UdEwQFMAMBAf8wHQYDVR0OBBYEFG/vyytrBtEquMX2dreysix/MlPMMIHJBgNVHSMEgcEwgb6AFG/vyytrBtEquMX2dreysix/MlPMoYGipIGfMIGcMRswGQYDVQQKExJUaGUgU2FtcGxlIENvbXBhbnkxFDASBgNVBAsTC0NBIERpdmlzaW9uMRwwGgYJKoZIhvcNAQkBFg1jYUBzYW1wbGUuY29tMRMwEQYDVQQHEwpNZXRyb3BvbGlzMREwDwYDVQQIEwhOZXcgWW9yazELMAkGA1UEBhMCVVMxFDASBgNVBAMTC1RTQyBSb290IENBggEAMA0GCSqGSIb3DQEBBAUAA4GBABclymJfsPOUazNQO8aIaxwVbXWS+8AFEkMMRx6O68ICAMubQBvs8Buz3ALXhqYeFS5G13pW2ZnAlSdTkSTKkE5wGZ1RYSfyiEKXb+uOKhDN9LnajDzaMPkNDU2NDXDzSqHk9ZiE1boQaMzjNLu+KabTLpmL9uXvFA/i+gdenFHv-----END CERTIFICATE-----
# openssl x509 -in cacert.pem -noout -text# openssl x509 -in cacert.pem -noout -dates# openssl x509 -in cacert.pem -noout -purpose
Creating a Certificate Signing Request (CSR)
Now that we have a root certificate, we can create any number of certificates for installation into our SSL applications such as https, spop, or simap. The procedure involves creating a private key and certificate request, and then signing the request to generate the certificate.Our configuration file needs some more definitions for creating non-CA certificates. Add the following at the end of the file:
---Begin---[ v3_req ]basicConstraints= CA:FALSEsubjectKeyIdentifier= hash----End----
---Begin---distinguished_name= req_distinguished_namereq_extensions= v3_req----End----
- Organizational Unit: a reminder of what the certificate is for
- Email Address: the postmaster
- Common Name: the server hostname
# openssl req -new -nodes -out req.pem -config ./openssl.cnf...Organizational Unit Name (department, division) []:Mail ServerEmail Address []:postmaster@sample.comCommon Name (hostname, IP, or your name) []:mail.sample.com...
- A private key in key.pem
- A certificate signing request in req.pem
The certificate signing request looks like this:
-----BEGIN CERTIFICATE REQUEST-----MIICJDCCAY0CAQAwgagxGzAZBgNVBAoTElRoZSBTYW1wbGUgQ29tcGFueTEUMBIGA1UECxMLTWFpbCBTZXJ2ZXIxJDAiBgkqhkiG9w0BCQEWFXBvc3RtYXN0ZXJAc2FtcGxlLmNvbTETMBEGA1UEBxMKTWV0cm9wb2xpczERMA8GA1UECBMITmV3IFlvcmsxCzAJBgNVBAYTAlVTMRgwFgYDVQQDEw9tYWlsLnNhbXBsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPJhc++WxcBaoDbJpzFbDg42NcOz/ELVFMU4FlPayUzUO+xXkdFRMPKo54d4Pf1w575Jhlu9lE+kJ8QN2st6JFySbc9QjPwVwl9D2+I3SSf2kVTu+2Ur5izCPbVAfU0rPZxxK8ELoOkA1uwwjFz6EFuVvnHwlguonWKDtmYWu7KTAgMBAAGgOzA5BgkqhkiG9w0BCQ4xLDAqMAkGA1UdEwQCMAAwHQYDVR0OBBYEFLWaQsUVIQzWr58HtDinH1JfeCheMA0GCSqGSIb3DQEBBAUAA4GBAAbe0jrGEQ3ityVfy5Lg4/f69rKvDGs+uhZJ9ZRx7Dl92Qq2osE7XrLB1bANmcoEv/ORLZOjWZEYNjMvuz60O7R8GKBrvb/YhAwWhIIt2LJqPkpAEWS0kY0AkoQcfZ7h6oC35+eJ7okgUu3WuE57RgcNt7/ftr0sG1jUyRwMLvhv-----END CERTIFICATE REQUEST-----
# openssl req -in req.pem -text -verify -noout
Signing a Certificate
Now we need to add the configuration file section that deals with being a Certificate Authority. This section will identify the paths to the various pieces, such as the database, the CA certificate, and the private key. It also provides some basic default values. Insert the following into openssl.cnf just before the [ req ] section:---Begin---[ ca ]default_ca= CA_default[ CA_default ]serial= $dir/serialdatabase= $dir/index.txtnew_certs_dir= $dir/newcertscertificate= $dir/cacert.pemprivate_key= $dir/private/cakey.pemdefault_days= 365default_md= md5preserve= noemail_in_dn= nonameopt= default_cacertopt= default_capolicy= policy_match[ policy_match ]countryName= matchstateOrProvinceName= matchorganizationName= matchorganizationalUnitName= optionalcommonName= suppliedemailAddress= optional----End----
# openssl ca -out cert.pem -config ./openssl.cnf -infiles req.pemUsing configuration from ./openssl.cnfEnter PEM pass phrase:demoCheck that the request matches the signatureSignature okThe Subjects Distinguished Name is as followsorganizationName :PRINTABLE:'The Sample Company'organizationalUnitName:PRINTABLE:'Mail Server'emailAddress :IA5STRING:'postmaster@sample.com'localityName :PRINTABLE:'Metropolis'stateOrProvinceName :PRINTABLE:'New York'countryName :PRINTABLE:'US'commonName :PRINTABLE:'mail.sample.com'Certificate is to be certified until Dec 8 04:37:38 2002 GMT (365 days)Sign the certificate? [y/n]:y1 out of 1 certificate requests certified, commit? [y/n]yWrite out database with 1 new entriesData Base Updated
- A certificate in cert.pem
- A copy of the certificate in newcerts/<serial>.pem
# openssl x509 -in cert.pem -noout -text -purpose | more
# mv cert.pem tmp.pem# openssl x509 -in tmp.pem -out cert.pem
Installing the Certificate and Key
This depends on the application. Some want the key and the certificate in the same file, and others want them separately. Combining them is easily done with:# cat key.pem cert.pem >key-cert.pem
- A private key in key.pem
- A certificate in cert.pem
- A combined private key and certificate in key-cert.pem
Apache
Apache has separate configuration directives for the key and the certificate, so we keep each in its own file. These files should be kept outside of the DocumentRoot subtree, so a reasonable directory structure might be:FileComment/home/httpd/htmlApache DocumentRoot/home/httpd/sslSSL-related files/home/httpd/ssl/cert.pemSite certificate/home/httpd/ssl/key.pemSite private keyWithin the <VirtualHost> directive for the site (which of course should be on port 443), include the directives that point to these files:
<VirtualHost 192.168.1.1:443> ServerName mail.sample.com DocumentRoot /home/httpd/html ... other directives for this site ... SSLEngine on SSLLog /var/log/ssl_engine_log SSLCertificateFile /home/httpd/ssl/cert.pem SSLCertificateKeyFile /home/httpd/ssl/key.pem</VirtualHost>
Stunnel
stunnel is used as an SSL wrapper for normal non-secure services such as IMAP and POP. It accepts as arguments (among other things) the service to execute, and the location of the certificate and private key.The key and the certificate are provided in the same file. These can go anywhere, but a good location might be /etc/ssl/certs. Specify it on the stunnel command line as follows:
stunnel -p /etc/ssl/certs/key-cert.pem <other stunnel args...>
Back to top
Distributing the CA Certificate
This, finally, is the step that stops the clients from complaining about untrusted certificates. Send cacert.pem to anyone who is going to use your secure servers, so they can install it in their browsers, mail clients, et cetera as a root certificate.Back to top
Renewing Certificates
Your certificate chain can break due to certificate expiry in two ways:- The certificates you signed with your root certificate have expired.
- Your root certificate itself has expired.
In the first case, you have two options. You can either generate new certificate signing requests and sign them as described above, or (if you kept them) you can re-sign the original requests. In either case, the old certificates must be revoked, and then the new certificates signed and installed into your secure applications as described earlier.
You cannot issue two certificates with the same Common Name, which is why the expired certificates must be revoked. The certificate is in the newcerts directory; you can determine its filename by browsing index.txt and searching for the Common Name (CN) on it. The filename is the index plus the extension ".pem", for example "02.pem". To revoke a certificate:
# openssl ca -revoke newcerts/02.pem -config ./openssl.cnfUsing configuration from ./openssl.cnfEnter PEM pass phrase: demoRevoking Certificate 02.Data Base Updated
Back to top
Getting a Commercially Signed Certificate
The process is basically the same as the one just demonstrated, but the CA does most of it. You need to generate a Certificate Signing Request as shown above, and then submit it for signing. You will receive a signed certificate for installation.This certificate will automatically be trusted by your client's browser, as the browser has the commercial CA's certificate built in. There is no need to distribute anything.
The configuration described here may be inadequate for this purpose, as there is much more that can go into a request. Different certificate authorities require different features in the certificate signing request, none of which we have gone into here. This additional material is beyond the current scope of this document.
Back to top
Publishing Your CA Certificate
You can post the certificate on your web site for download. If you do this, you should also post a Certificate Revocation List (CRL), and a means of displaying a certificate given its serial number. This is outside the current scope of this document.Apache will serve your certificate in a form recognizable to browsers if you specify its MIME type. For example, you can use the filename extension ".crt" for downloadable certificates, and put the following into the general section of your Apache configuration:
AddType application/x-x509-ca-cert .crt
The CRL can be created as follows:
# openssl ca -gencrl -crldays 31 -config ./openssl.cnf -out rootca.crl
Back to top
Summary
You now have enough information to create and sign certificates on your own behalf. While this is a fairly long document, the procedure can be summarized easily.One-Time Setup
Set up, and create a root CA certificate.Commands
# mkdir CA# cd CA# mkdir newcerts private# echo '01' >serial# touch index.txt# (IMPORTANT: Install and edit the configuration file shown below.)# openssl req -new -x509 -extensions v3_ca -keyout private/cakey.pem \-out cacert.pem -days 365 -config ./openssl.cnf
Output
FilePurposecacert.pemCA certificateprivate/cakey.pemCA private keyDistribute cacert.pem to your clients.
Per Certificate
Create certificate signing requests and sign them, supplying appropriate values for the Common Name and the Organizational Unit.Commands
# openssl req -new -nodes -out req.pem -config ./openssl.cnf# openssl ca -out cert.pem -config ./openssl.cnf -infiles req.pem# cat key.pem cert.pem >key-cert.pem
Output
FilePurposekey.pemPrivate keyreq.pemCertificate signing requestcert.pemCertificatekey-cert.pemCombined private key and certificateInstall key.pem and cert.pem, or just key-cert.pem as appropriate for your server application.
Per Certificate - Renewal
Revoke the expired certificate, and re-sign the original request.Commands
# openssl ca -revoke newcerts/<serial>.pem -config ./openssl.cnf# openssl ca -out cert.pem -config ./openssl.cnf -infiles req.pem
Back to top
Configuration File
(This file is available for download.)---Begin---## OpenSSL configuration file.## Establish working directory.dir= .[ ca ]default_ca= CA_default[ CA_default ]serial= $dir/serialdatabase= $dir/index.txtnew_certs_dir= $dir/newcertscertificate= $dir/cacert.pemprivate_key= $dir/private/cakey.pemdefault_days= 365default_md= md5preserve= noemail_in_dn= nonameopt= default_cacertopt= default_capolicy= policy_match[ policy_match ]countryName= matchstateOrProvinceName= matchorganizationName= matchorganizationalUnitName= optionalcommonName= suppliedemailAddress= optional[ req ]default_bits= 1024# Size of keysdefault_keyfile= key.pem# name of generated keysdefault_md= md5# message digest algorithmstring_mask= nombstr# permitted charactersdistinguished_name= req_distinguished_namereq_extensions= v3_req[ req_distinguished_name ]# Variable name Prompt string#---------------------- ----------------------------------0.organizationName= Organization Name (company)organizationalUnitName= Organizational Unit Name (department, division)emailAddress= Email AddressemailAddress_max= 40localityName= Locality Name (city, district)stateOrProvinceName= State or Province Name (full name)countryName= Country Name (2 letter code)countryName_min= 2countryName_max= 2commonName= Common Name (hostname, IP, or your name)commonName_max= 64# Default values for the above, for consistency and less typing.# Variable name Value#------------------------------ ------------------------------0.organizationName_default= The Sample CompanylocalityName_default= MetropolisstateOrProvinceName_default= New YorkcountryName_default= US[ v3_ca ]basicConstraints= CA:TRUEsubjectKeyIdentifier= hashauthorityKeyIdentifier= keyid:always,issuer:always[ v3_req ]basicConstraints= CA:FALSEsubjectKeyIdentifier= hash----End----
References
More information is available at the following sites (opens in new window):- OpenSSL Home Page
- OpenSSL Documentation
- OpenSSL FAQ
- Nick Burch's Certificate Management and Installation with OpenSSL
- Franck Martin's SSL Certificates HOWTO
- 怎么创建和使用SSL证书
- 怎么购买SSL服务器证书?
- 证书和 SSL 简介
- StartSSL免费SSL证书申请使用:Apache和Ngnix安装配置SSL证书
- HTTP和HTTPS有什么区别? 什么是SSL证书?使用ssl证书优势?
- iis 配置ssl通讯 和证书的使用
- TOMCAT使用CA签发证书配置单向和双向SSL
- SSL双向认证以及证书的制作和使用
- SSL双向认证以及证书的制作和使用
- TOMCAT使用CA签发证书配置单向和双向SSL
- SSL双向认证以及证书的制作和使用
- 使用ssl构建证书中心
- 使用自制证书配置SSL
- 使用xcode创建开发证书和打包证书
- 怎么使用SSL
- 证书和SSL或TLS
- 创建和使用自签名证书
- SSL第三讲 SSL证书生成的超级工具的使用讲解和演示
- redhat实现目录下特定文本类型内关键字查找及vim模式下关键字查找
- TempTest
- Xamarin XAML语言教程基础语法篇大学霸
- java string 首字母大写方法
- Sum of Left Leaves问题及解法
- 怎么创建和使用SSL证书
- JS简易秒表计时器
- Android Volley完全解析
- Xms Xmx PermSize MaxPermSize 区别
- JavaScript 中 Map 和 Object 的区别
- C++不常用关键字(__leave)
- ios layer.mask
- GUI测试自动化 -- python
- L1,L2正则化