证书工具之openSSL

X.509证书(*.cer; *.crt)
个人信息交换(*.pfx; *.p12)
证书信任列表(*.stl)
证书吊销列表(*.crl)
Microsoft系列证书存储(*.sst)
PKCS #7证书(*.spc; *.p7b)

公钥加密数据,私钥解密 称为加密和解密。
私钥加密数据,公钥解密 称为签名和验证签名。

互联网数据安全可靠的条件:
1.数据来源可信,即数据发送者身份可信。
2.数据具备完整性,即数据未被修改过。
3.数据安全性,即数据不会被泄漏,他人截获后无法解密。

1、openssl install

yum -y install openssl
当安装碰到各种依赖循环问题无法解决时可以使用下面的命令哦!!
yum -y install openssl*

1、openssl help

[root@centos6a ~]# openssl --help
openssl:Error: '--help' is an invalid command.

Standard commands
asn1parse         ca                ciphers           cms               
crl               crl2pkcs7         dgst              dh                
dhparam           dsa               dsaparam          ec                
ecparam           enc               engine            errstr            
gendh             gendsa            genpkey           genrsa            
nseq              ocsp              passwd            pkcs12            
pkcs7             pkcs8             pkey              pkeyparam         
pkeyutl           prime             rand              req               
rsa               rsautl            s_client          s_server          
s_time            sess_id           smime             speed             
spkac             ts                verify            version           
x509              

Message Digest commands (see the `dgst' command for more details)
md2               md4               md5               rmd160            
sha               sha1              

Cipher commands (see the `enc' command for more details)
aes-128-cbc       aes-128-ecb       aes-192-cbc       aes-192-ecb       
aes-256-cbc       aes-256-ecb       base64            bf                
bf-cbc            bf-cfb            bf-ecb            bf-ofb            
camellia-128-cbc  camellia-128-ecb  camellia-192-cbc  camellia-192-ecb  
camellia-256-cbc  camellia-256-ecb  cast              cast-cbc          
cast5-cbc         cast5-cfb         cast5-ecb         cast5-ofb         
des               des-cbc           des-cfb           des-ecb           
des-ede           des-ede-cbc       des-ede-cfb       des-ede-ofb       
des-ede3          des-ede3-cbc      des-ede3-cfb      des-ede3-ofb      
des-ofb           des3              desx              idea              
idea-cbc          idea-cfb          idea-ecb          idea-ofb          
rc2               rc2-40-cbc        rc2-64-cbc        rc2-cbc           
rc2-cfb           rc2-ecb           rc2-ofb           rc4               
rc4-40            seed              seed-cbc          seed-cfb          
seed-ecb          seed-ofb          zlib 

openssl命令的格式是"openssl command command-options args",command部分有很多种命令,这些命令需要依赖于openssl命令才能执行,所以称为伪命令(pseudo-command),每个伪命令都有各自的功能,大部分command都可以直接man command查看命令的用法和功能。


1、查看openssl完整版本信息
[root@localhost ~]# openssl version -a
OpenSSL 1.0.1e-fips 11 Feb 2013
built on: Mon May  9 09:54:24 CDT 2016
platform: linux-x86_64
options:  bn(64,64) md2(int) rc4(16x,int) des(idx,cisc,16,int) idea(int) blowfish(idx) 
compiler: gcc -fPIC -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -DKRB5_MIT -m64 -DL_ENDIAN -DTERMIO -Wall -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -Wa,--noexecstack -DPURIFY -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/etc/pki/tls"
engines:  rdrand dynamic
1、openssl目录结构
[root@hadoop101 ~]# tree -d /etc/pki/
/etc/pki/
├── CA
│   ├── certs
│   ├── crl
│   ├── newcerts
│   └── private
├── ca-trust
│   ├── extracted
│   │   ├── java
│   │   ├── openssl
│   │   └── pem
│   └── source
│       ├── anchors
│       └── blacklist
├── java
├── nssdb
├── nss-legacy
├── rpm-gpg
├── rsyslog
└── tls
    ├── certs
    ├── misc
    └── private

2、生产rsa私钥

man genrsa

openssl genrsa [-out filename] \
[-passout arg] \
[-des] [-des3] [-idea] \
[-f4] [-3] \
[-rand file(s)] \
[-engine id] \
[numbits]

选项说明:
[-out filename] :
将生成的私钥保存至filename文件,若未指定输出文件,则为标准输出。
[-passout args] :
加密私钥文件时,传递密码的格式,如果要加密私钥文件时单未指定该项,则提示输入密码。传递密码的args的格式见openssl密码格式。
[-f4|-3]
the public exponent to use, either 65537 or 3. The default is 65537.
[-des|-des3|-idea|-aes128|-aes192|-aes256] :
指定加密私钥文件用的算法,这样每次使用私钥文件都将输入密码,太麻烦所以很少使用。
[numbits]:the size of the private key to generate in bits. This must be the last option specified. The default is 512.

[root@centos6a ~]# openssl genrsa  512
Generating RSA private key, 512 bit long modulus
..........++++++++++++
....++++++++++++
e is 65537 (0x10001)
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBAOJzt0+92N8EZwIQiDefhqz4VM/aN88TxddJVNjyWkATjvO9cyJx
XfpBdcTEtC/4CdUb4ahVwCaNa8aWCdEHIo0CAwEAAQJALToRNXLkOn5lmEr2+az5
t9gNEEoz9T6st7eko4ObtMoS9F2lLDfsypqRPkBsHCWt0rE3RZ8LFDhcg6Is2sOB
AQIhAPrT92TEqCJU7nRrxJQiItbFELd/98T9AKzZbUpbd2bBAiEA5x8Tz1AN3P4I
vrc4SjX4hcSWJb2cdN5+3VH9JITKWs0CIQD4Z8OyQDBjD8m38qKUMdpe6HtNv6YZ
qJZqmEnsQflWAQIhALpI0ze6p6Hi43uMxAMUoz52aCr9PFj6aLjMd8PygANVAiB6
63rm/VNtTb9MknpwPAwUSIp5X6QyEoUE92h5wdxSJA==
-----END RSA PRIVATE KEY-----
[root@centos6a ~]# openssl genrsa -des3 -passout pass:123456 512
Generating RSA private key, 512 bit long modulus
.......++++++++++++
...++++++++++++
e is 65537 (0x10001)
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,8C843F225B7F9D33

suv4Ssyo/pzQq4YxvVVw7asVz0J0U1AknZvJgWPDtXe/UWGaK6KdPYaYPW0maFeq
5kGzOX3jqg1AKRL4YsySDb4Chi90XCWzgpf2Y7d5g22i6X/Vi/QXcvRrQu52lSd8
yIid29RLiGy5+IV5VkmfcFJE+7ir/s/7MKE40astOyqEez2ss/wIVbXm82csWnwG
uQCajjEtwFYqspqjchqhTNQ1Qf0PboiZUtTvoB+9vgBHnkW4eBLQPfJBVNHws0w8
0SMhnLbicKd8OedmDQu5aRXdyxdLH/TU748d9QvjQ9GXiNkfdHLF+8RfDUsfR+g7
rY+2tNPQj66NpPSmPRZlFKGqdZl6y5ZkwWcfkIhiulVqWN+tWjlPmRerxg1h9LUp
GD149HDdWL/w8r+vOaO17YGwV6iUsK5qr5MIYbV3UF5IYWcnz3jqGg==
-----END RSA PRIVATE KEY-----

2、查看openssl的配置文件openssl.cnf

配置证书的名称和存放位置等相关信息

vim /etc/pki/tls/openssl.cnf
 35 ####################################################################
 36 [ ca ]
 37 default_ca      = CA_default            # The default ca section
 38 
 39 ####################################################################
 40 [ CA_default ]
 41 
 42 dir             = /etc/pki/CA           # Where everything is kept
 43 certs           = $dir/certs            # Where the issued certs are kept
 44 crl_dir         = $dir/crl              # Where the issued crl are kept
 45 database        = $dir/index.txt        # database index file.
 46 #unique_subject = no                    # Set to 'no' to allow creation of
 47                                         # several ctificates with same subject.
 48 new_certs_dir   = $dir/newcerts         # default place for new certs.
 49 
 50 certificate     = $dir/cacert.pem       # The CA certificate
 51 serial          = $dir/serial           # The current serial number
 52 crlnumber       = $dir/crlnumber        # the current crl number
 53                                         # must be commented out to leave a V1 CRL
 54 crl             = $dir/crl.pem          # The current CRL
 55 private_key     = $dir/private/cakey.pem# The private key
 56 RANDFILE        = $dir/private/.rand    # private random number file
 57 
 58 x509_extensions = usr_cert              # The extentions to add to the cert
 59 
 60 # Comment out the following two lines for the "traditional"
 61 # (and highly broken) format.
 62 name_opt        = ca_default            # Subject Name options
 63 cert_opt        = ca_default            # Certificate field options
 64 
 65 # Extension copying option: use with caution.
 66 # copy_extensions = copy
 67 
 68 # Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
 69 # so this is commented out by default to leave a V1 CRL.
 70 # crlnumber must also be commented out to leave a V1 CRL.
 71 # crl_extensions        = crl_ext
 72 
 73 default_days    = 365                   # how long to certify for
 74 default_crl_days= 30                    # how long before next CRL
 75 default_md      = sha256                # use SHA-256 by default
 76 preserve        = no                    # keep passed DN ordering
 77 
 78 # A few difference way of specifying how similar the request should look
 79 # For type CA, the listed attributes must be the same, and the optional
 80 # and supplied fields are just that :-)
 81 policy          = policy_match
 82 
3、根据配置文件信息创建根证书CA所需的目录及文件,若没有则自己创建
cd /etc/pki/CA
mkdir -pv {certs,crl,newcerts,private}
touch {serial,index.txt}
4、指明证书的开始编号
echo 01 >> serial
5、生成根证书的私钥

注意:私钥的文件名与存放位置要与配置文件中的设置相匹配:

(umask 077; openssl genrsa -out private/cakey.pem 2048)

参数说明:
genrsa :产生rsa密钥命令
-aes256 :使用AES算法(256位密钥)对产生的私钥加密,这里没有此参数,则只是用了rsa算法加密。
-out :输出路径,这里指private/ca.key.pem
这里的参数2048,指的是密钥的长度位数,默认长度为512位

(6)生成自签证书,即根证书CA,自签证书的存放位置也要与配置文件中的设置相匹配,生成证书时需要填写相应的信息。

openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out cacert.pem -days 365

参数说明:
-new :表示生成一个新证书签署请求
-x509 :专用于CA生成自签证书,如果不是自签证书则不需要此项
-key :用到的私钥文件
-out :证书的保存路径
-days :证书的有效期限,单位是day(天),默认是openssl.cnf的default_days

1、生成一个私钥pri_key.pem
openssl genrsa -out pri_key.pem
2、根据私钥pri_key.pem生成“证书请求文件”

"-new"表示新生成一个新的证书请求文件,
"-key"指定私钥文件,
"-out"指定输出文件,此处输出文件即为证书请求文件。

openssl req -new -key pri_key.pem -out req1.csr
3、查看“证书请求文件”内容。

查看请求文件时,"-text"选项表示以文本格式输出证书请求文件的内容。

openssl req -in req1.csr -text

将"-text"和"-noout"结合使用,则只输出证书请求的文件头部分。

openssl req -in req1.csr -noout -text

只输出subject部分的内容

openssl req -in req1.csr -subject -noout

使用"-pubkey"输出证书请求文件中的公钥内容

openssl req -in req1.csr -pubkey -noout

从获取“申请证书请求”时所提供的私钥中提取出公钥

openssl rsa -in pri_key.pem -pubout
指定“证书请求文件”中的签名算法

默认使用的是sha1,还支持md5、sha256、sha512等。
列出可支持的签名算法。

openssl dgst --help

如指定md5算法

openssl req -new -key pri_key.pem -out req2.csr -md5

openssl req -in req2.csr -noout -text | grep 'Signature Algorithm'
验证“证书请求文件”的数字签名

"-verify"选项表示验证证书请求文件的数字签名。可以验证出证书请求文件是否被篡改过。

openssl req -verify -in req1.csr

使用"-noout"选项,只输出"verify OK"。

openssl req -verify -in req1.csr -noout
自签署证书,可用于自建根CA时

使用openssl req自签署证书时,需要使用"-x509"选项,由于是签署证书请求文件,所以可以指定"-days"指定所颁发的证书有效期。

openssl req -x509 -key pri_key.pem -in req1.csr -out CA1.crt -days 365
# 使用rsa加密解密,签名,验证签名
1:生成RSA私钥,1024位,base64编码的二进制数据的私钥。
openssl genrsa -out private_key.pem 1024


2:从private.pem私钥中提取公钥,输出。
openssl rsa -in private_key.pem -pubout -out public_key.pem


3:查看pem文件中base64编码的二进制数据。
cat private_key.pem
cat public_key.pem


4:将私钥转化成明文。
openssl rsa -in private_key.pem -text -out private_key.txt


5:通过公钥rsa加密message.txt。
openssl rsautl -encrypt -in message.txt -inkey public_key.pem -pubin -out enc.txt


6:通过私钥解密enc.txt。
openssl rsautl -decrypt -in enc.txt -inkey private_key.pem -out message_dec.txt


7:使用私钥签名。
openssl rsautl -sign -in message.txt -inkey private_key.pem -out message_sign.bin


8:xxd查看二进制文件。


9:使用公钥验证签名。
openssl rsautl -verify -in message_sign.bin -inkey public_key.pem -pubin -out decode.txt


# 使用openssl生成证书
1:从pem私钥中提取证书签名请求。
openssl req -new -key private_key.pem -out rsacert.csr


2: 给请求文件从pem文件中提取证书,.crt这个证书还是base64编码的,这个crt文件也不是直接使用的。
openssl x509 -req -days 3650 -in rsacert.csr -signkey private_key.pem -out rsacert.crt


3:生成der文件. 这个der文件主要包含公钥。最后通过这个来生成一个p12是这个der对应的私钥文件。
openssl x509 -outform der -in rsacert.crt -out rsacert.der


4:通过crt文件通提取私钥P12文件,公钥也是从crt中提取出来的
openssl pkcs12 -inkey private_key.pem -in rsacert.crt -export -out p.p12


5:证书的关系
.der 文件是公钥,二进制文件。
.p12 是私钥文件,二进制文件。


2:他们是从crt文件中提取出来的,crt文件是从pem文件中提取出来的。
crt和pem中有公钥和私钥他们是base64编码的文件。


base64编解码,所有的base64都是对二进制数据操作的。

附录:openssl.cnf 默认配置

[root@hadoop101 tls]$ cat /etc/pki/tls/openssl.cnf 
# OpenSSL example configuration file.
# This is mostly being used for generation of certificate requests.

# This definition stops the following lines choking if HOME isn't defined.
HOME			= .
RANDFILE		= $ENV::HOME/.rnd

# Extra OBJECT IDENTIFIER info:
#oid_file		= $ENV::HOME/.oid
oid_section		= new_oids

# To use this configuration file with the "-extfile" option of the
# "openssl x509" utility, name here the section containing the
# X.509v3 extensions to use:
# extensions		= 
# (Alternatively, use a configuration file that has only
# X.509v3 extensions in its main [= default] section.)

[ new_oids ]

# We can add new OIDs in here for use by 'ca', 'req' and 'ts'.
# Add a simple OID like this:
# testoid1=1.2.3.4
# Or use config file substitution like this:
# testoid2=${testoid1}.5.6

# Policies used by the TSA examples.
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7

####################################################################
[ ca ]
default_ca	= CA_default		# The default ca section

####################################################################
[ CA_default ]

dir		= /etc/pki/CA			# Where everything is kept
certs		= $dir/certs		# Where the issued certs are kept
crl_dir		= $dir/crl			# Where the issued crl are kept
database	= $dir/index.txt	# database index file.
#unique_subject	= no			# Set to 'no' to allow creation of
					# several ctificates with same subject.
new_certs_dir	= $dir/newcerts		# default place for new certs.

certificate	= $dir/cacert.pem 	# The CA certificate
serial		= $dir/serial 		# The current serial number
crlnumber	= $dir/crlnumber	# the current crl number
					# must be commented out to leave a V1 CRL
crl		= $dir/crl.pem 		# The current CRL
private_key	= $dir/private/cakey.pem# The private key
RANDFILE	= $dir/private/.rand	# private random number file

x509_extensions	= usr_cert		# The extentions to add to the cert

# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt 	= ca_default		# Subject Name options
cert_opt 	= ca_default		# Certificate field options

# Extension copying option: use with caution.
# copy_extensions = copy

# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crlnumber must also be commented out to leave a V1 CRL.
# crl_extensions	= crl_ext

default_days	= 365			# how long to certify for
default_crl_days= 30			# how long before next CRL
default_md	= sha256		# use SHA-256 by default
preserve	= no			# keep passed DN ordering

# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy		= policy_match

# For the CA policy
[ policy_match ]
countryName		= match
stateOrProvinceName	= match
organizationName	= match
organizationalUnitName	= optional
commonName		= supplied
emailAddress		= optional

# For the 'anything' policy
# At this point in time, you must list all acceptable 'object' types.
[ policy_anything ]
countryName		= optional
stateOrProvinceName	= optional
localityName		= optional
organizationName	= optional
organizationalUnitName	= optional
commonName		= supplied
emailAddress		= optional

####################################################################
[ req ]
default_bits		= 2048
default_md		= sha256
default_keyfile 	= privkey.pem
distinguished_name	= req_distinguished_name
attributes		= req_attributes
x509_extensions	= v3_ca	# The extentions to add to the self signed cert

# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret

# This sets a mask for permitted string types. There are several options. 
# default: PrintableString, T61String, BMPString.
# pkix	 : PrintableString, BMPString (PKIX recommendation before 2004)
# utf8only: only UTF8Strings (PKIX recommendation after 2004).
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
string_mask = utf8only

# req_extensions = v3_req # The extensions to add to a certificate request

[ req_distinguished_name ]
countryName			= Country Name (2 letter code)
countryName_default		= XX
countryName_min			= 2
countryName_max			= 2

stateOrProvinceName		= State or Province Name (full name)
#stateOrProvinceName_default	= Default Province

localityName			= Locality Name (eg, city)
localityName_default		= Default City

0.organizationName		= Organization Name (eg, company)
0.organizationName_default	= Default Company Ltd

# we can do this but it is not needed normally :-)
#1.organizationName		= Second Organization Name (eg, company)
#1.organizationName_default	= World Wide Web Pty Ltd

organizationalUnitName		= Organizational Unit Name (eg, section)
#organizationalUnitName_default	=

commonName			= Common Name (eg, your name or your server\'s hostname)
commonName_max			= 64

emailAddress			= Email Address
emailAddress_max		= 64

# SET-ex3			= SET extension number 3

[ req_attributes ]
challengePassword		= A challenge password
challengePassword_min		= 4
challengePassword_max		= 20

unstructuredName		= An optional company name

[ usr_cert ]

# These extensions are added when 'ca' signs a request.

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType			= server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# This will be displayed in Netscape's comment listbox.
nsComment			= "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

# This is required for TSA certificates.
# extendedKeyUsage = critical,timeStamping

[ v3_req ]

# Extensions to add to a certificate request

basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

[ v3_ca ]


# Extensions for a typical CA


# PKIX recommendation.

subjectKeyIdentifier=hash

authorityKeyIdentifier=keyid:always,issuer

# This is what PKIX recommends but some broken software chokes on critical
# extensions.
#basicConstraints = critical,CA:true
# So we do this instead.
basicConstraints = CA:true

# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign

# Some might want this also
# nsCertType = sslCA, emailCA

# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy

# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF

[ crl_ext ]

# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.

# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always

[ proxy_cert_ext ]
# These extensions should be added when creating a proxy certificate

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType			= server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# This will be displayed in Netscape's comment listbox.
nsComment			= "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

# This really needs to be in place for it to be a proxy certificate.
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo

####################################################################
[ tsa ]

default_tsa = tsa_config1	# the default TSA section

[ tsa_config1 ]

# These are used by the TSA reply generation only.
dir		= ./demoCA		# TSA root directory
serial		= $dir/tsaserial	# The current serial number (mandatory)
crypto_device	= builtin		# OpenSSL engine to use for signing
signer_cert	= $dir/tsacert.pem 	# The TSA signing certificate
					# (optional)
certs		= $dir/cacert.pem	# Certificate chain to include in reply
					# (optional)
signer_key	= $dir/private/tsakey.pem # The TSA private key (optional)

default_policy	= tsa_policy1		# Policy if request did not specify it
					# (optional)
other_policies	= tsa_policy2, tsa_policy3	# acceptable policies (optional)
digests		= sha1, sha256, sha384, sha512	# Acceptable message digests (mandatory)
accuracy	= secs:1, millisecs:500, microsecs:100	# (optional)
clock_precision_digits  = 0	# number of digits after dot. (optional)
ordering		= yes	# Is ordering defined for timestamps?
				# (optional, default: no)
tsa_name		= yes	# Must the TSA name be included in the reply?
				# (optional, default: no)
ess_cert_id_chain	= no	# Must the ESS cert id chain be included?
				# (optional, default: no)

.crt:per格式的证书
.der: der格式的证书
.key:pem格式的私钥
.pub:pem格式的公钥
.req:申请证书时发送给CA认证机构的请求文件
.csr:也表示请求文件
证书文件的格式
所有证书内容格式有两种:pem格式和der格式,这两种格式的证书文件可以相互转换,利用OpenSSL中的程序就可以完成。

PEM格式(Privacy Enhanced Mail)
pem格式的证书内容是经过加密的文本文件,一般是base64格式,可以用记事本来打开一个base64格式的证书

DER格式(Distinguished Encoding Rules)
der格式的证书文件内容是经过加密的二进制数据,也就是说文件内容打开后是乱码。

X.509标准
X.509是一个体系、标准,用来规定一个证书的格式标准,CA认证结构在生成证书的时候,就根据这个标准把每部分信息写入到证书文件中。

X.509包括3个版本:V1, V2和V3。每一个版本中颁发证书时,必须包含下列信息:

版本号:用来区分版本;
系列号:由CA认证机构给每一个证书分配一个唯一的数字编号;
算法签名标识符:用来指定CA认证机构在颁发证书时使用的签名算法;
认证机构:颁发证书的机构唯一名称;
有效期限:证书有效期(开始时间和结束时间);
主题信息:证书持有人的基本信息;
公钥信息:证书持有者的公钥;
认证结构签名:以确保这个证书在颁发之后没有被篡改过;

证书标准

X.509 这是一种证书标准,主要定义了证书中应该包含哪些内容.其详情可以参考RFC5280,SSL使用的就是这种证书标准.

编码格式

同样的X.509证书,可能有不同的编码格式,目前有以下两种编码格式.

PEM - Privacy Enhanced Mail, 文本格式,以"-----BEGIN"开头,"END-----"结尾,内容是BASE64编码
查看PEM格式证书的信息:openssl x509 -in certificate.pem -text -noout
Apache和*NIX服务器偏向于使用这种编码格式.

DER - Distinguished Encoding Rules, 二进制格式,不可读
查看DER格式证书的信息:openssl x509 -in certificate.der -inform der -text -noout
Java和Windows服务器偏向于使用这种编码格式.

相关的文件扩展名

CRT - certificate是证书的意思,常见于*NIX系统,有可能是PEM编码,也有可能是DER编码,大多数应该是PEM编码.

CER - certificate还是证书的意思,常见于Windows系统,同样的可能是PEM编码,也可能是DER编码,大多数应该是DER编码.

KEY - 通常用来存放一个公钥或者私钥,并非X.509证书,编码同样的,可能是PEM,也可能是DER.
查看KEY的办法: openssl rsa -in mykey.key -text -noout
如果是DER格式: openssl rsa -in mykey.key -text -inform der -noout

CSR - Certificate Signing Request,即证书签名请求,这个并不是证书,而是向权威证书颁发机构获得签名证书的申请,
其核心内容是一个公钥(当然还附带了一些别的信息),在生成这个申请的时候,同时也会生成一个私钥,私钥要自己保管好。
查看信息的办法: openssl req -noout -text -in my.csr
如果是DER格式 : openssl req -noout -text -in my.csr -inform der

PFX/P12 - predecessor of PKCS#12,对*nix服务器来说,一般CRT和KEY是分开存放在不同文件中的,但Windows的IIS则将它们存在一个PFX文件中,
(因此这个文件包含了证书及私钥)这样会不会不安全?应该不会,PFX通常会有一个"提取密码",你想把里面的东西读取出来的话,
它就要求你提供提取密码,PFX使用的是DER编码,如何把PFX转换为PEM编码?
openssl pkcs12 -in for_iis.pfx -out for_iis.pem -nodes
这个时候会提示你输入"提取密码",for_iis.pem就是可读的文本.
生成pfx的命令类似这样:
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
其中CACert.crt是CA(权威证书颁发机构)的根证书,有的话也通过 -certfile 参数一起带进去,这么看来,PFX其实是个证书密钥库.

JKS - 即Java Key Storage,这是Java的专利,跟OpenSSL关系不大,利用Java的一个叫"keytool"的工具,可以将PFX转为JKS,当然了,
keytool也能直接生成JKS,不过在此就不多表了.

证书编码的转换
PEM转为DER: openssl x509 -in cert.crt -outform der -out cert.der
DER转为PEM: openssl x509 -in cert.crt -inform der -outform pem -out cert.pem
(提示:要转换KEY文件也类似,只不过把x509换成rsa,要转CSR的话,把x509换成req…)

获得证书
向权威证书颁发机构申请证书
用这命令生成一个csr:
openssl req -newkey rsa:2048 -new -nodes -keyout my.key -out my.csr
把csr交给权威证书颁发机构,权威证书颁发机构对此进行签名,完成.保留好csr,当权威证书颁发机构颁发的证书过期的时候,
你还可以用同样的csr来申请新的证书,key保持不变.

或者生成自签名的证书
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem

man openssl

[root@hadoop101 ~]# man openssl
NAME
       openssl - OpenSSL command line tool

SYNOPSIS
       openssl command [ command_opts ] [ command_args ]

       openssl [ list-standard-commands | list-message-digest-commands | list-cipher-commands |
       list-cipher-algorithms | list-message-digest-algorithms | list-public-key-algorithms]

       openssl no-XXX [ arbitrary options ]
DESCRIPTION
       OpenSSL is a cryptography toolkit implementing the Secure Sockets Layer (SSL v2/v3) and
       Transport Layer Security (TLS v1) network protocols and related cryptography standards
       required by them.

       The openssl program is a command line tool for using the various cryptography functions
       of OpenSSL's crypto library from the shell.  It can be used for

        o  Creation and management of private keys, public keys and parameters
        o  Public key cryptographic operations
        o  Creation of X.509 certificates, CSRs and CRLs
        o  Calculation of Message Digests
        o  Encryption and Decryption with Ciphers
        o  SSL/TLS Client and Server Tests
        o  Handling of S/MIME signed or encrypted mail
        o  Time Stamp requests, generation and verification

COMMAND SUMMARY
       The openssl program provides a rich variety of commands (command in the SYNOPSIS above),
       each of which often has a wealth of options and arguments (command_opts and command_args
       in the SYNOPSIS).

   STANDARD COMMANDS
       asn1parse Parse an ASN.1 sequence.

       ca        Certificate Authority (CA) Management.

       ciphers   Cipher Suite Description Determination.

       cms       CMS (Cryptographic Message Syntax) utility

       crl       Certificate Revocation List (CRL) Management.

       crl2pkcs7 CRL to PKCS#7 Conversion.

       dgst      Message Digest Calculation.

       dh        Diffie-Hellman Parameter Management.  Obsoleted by dhparam.

       dhparam   Generation and Management of Diffie-Hellman Parameters. Superseded by genpkey
                 and pkeyparam

       dsa       DSA Data Management.

       dsaparam  DSA Parameter Generation and Management. Superseded by genpkey and pkeyparam

       ec        EC (Elliptic curve) key processing

       ecparam   EC parameter manipulation and generation

       enc       Encoding with Ciphers.

       engine    Engine (loadble module) information and manipulation.

       errstr    Error Number to Error String Conversion.

       gendh     Generation of Diffie-Hellman Parameters.  Obsoleted by dhparam.

       gendsa    Generation of DSA Private Key from Parameters. Superseded by genpkey and pkey

       genpkey   Generation of Private Key or Parameters.

       genrsa    Generation of RSA Private Key. Superceded by genpkey.

       nseq      Create or examine a netscape certificate sequence

       ocsp      Online Certificate Status Protocol utility.

       passwd    Generation of hashed passwords.

       pkcs12    PKCS#12 Data Management.

       pkcs7     PKCS#7 Data Management.

       pkey      Public and private key management.

       pkeyparam Public key algorithm parameter management.

       pkeyutl   Public key algorithm cryptographic operation utility.

       rand      Generate pseudo-random bytes.

       req       PKCS#10 X.509 Certificate Signing Request (CSR) Management.

       rsa       RSA key management.

       rsautl    RSA utility for signing, verification, encryption, and decryption. Superseded
                 by  pkeyutl

       s_client  This implements a generic SSL/TLS client which can establish a transparent
                 connection to a remote server speaking SSL/TLS. It's intended for testing
                 purposes only and provides only rudimentary interface functionality but
                 internally uses mostly all functionality of the OpenSSL ssl library.

       s_server  This implements a generic SSL/TLS server which accepts connections from remote
                 clients speaking SSL/TLS. It's intended for testing purposes only and provides
                 only rudimentary interface functionality but internally uses mostly all
                 functionality of the OpenSSL ssl library.  It provides both an own command
                 line oriented protocol for testing SSL functions and a simple HTTP response
                 facility to emulate an SSL/TLS-aware webserver.

       s_time    SSL Connection Timer.

       sess_id   SSL Session Data Management.

       smime     S/MIME mail processing.

       speed     Algorithm Speed Measurement.

       spkac     SPKAC printing and generating utility

       ts        Time Stamping Authority tool (client/server)

       verify    X.509 Certificate Verification.

       version   OpenSSL Version Information.

       x509      X.509 Certificate Data Management.

   MESSAGE DIGEST COMMANDS
       md2       MD2 Digest

       md5       MD5 Digest

       mdc2      MDC2 Digest

       rmd160    RMD-160 Digest

       sha       SHA Digest

       sha1      SHA-1 Digest

       sha224    SHA-224 Digest

       sha256    SHA-256 Digest

       sha384    SHA-384 Digest

       sha512    SHA-512 Digest

   ENCODING AND CIPHER COMMANDS
       base64    Base64 Encoding

       bf bf-cbc bf-cfb bf-ecb bf-ofb
                 Blowfish Cipher

       cast cast-cbc
                 CAST Cipher

       cast5-cbc cast5-cfb cast5-ecb cast5-ofb
                 CAST5 Cipher

       des des-cbc des-cfb des-ecb des-ede des-ede-cbc des-ede-cfb des-ede-ofb des-ofb
                 DES Cipher

       des3 desx des-ede3 des-ede3-cbc des-ede3-cfb des-ede3-ofb
                 Triple-DES Cipher

       idea idea-cbc idea-cfb idea-ecb idea-ofb
                 IDEA Cipher

       rc2 rc2-cbc rc2-cfb rc2-ecb rc2-ofb
                 RC2 Cipher

       rc4       RC4 Cipher

       rc5 rc5-cbc rc5-cfb rc5-ecb rc5-ofb
                 RC5 Cipher

PASS PHRASE ARGUMENTS
       Several commands accept password arguments, typically using -passin and -passout for
       input and output passwords respectively. These allow the password to be obtained from a
       variety of sources. Both of these options take a single argument whose format is
       described below. If no password argument is given and a password is required then the
       user is prompted to enter one: this will typically be read from the current terminal
       with echoing turned off.

       pass:password
       input and output passwords respectively. These allow the password to be obtained from a
       variety of sources. Both of these options take a single argument whose format is
       described below. If no password argument is given and a password is required then the
       user is prompted to enter one: this will typically be read from the current terminal
       with echoing turned off.

       pass:password
                 the actual password is password. Since the password is visible to utilities
                 (like 'ps' under Unix) this form should only be used where security is not
                 important.

       env:var   obtain the password from the environment variable var. Since the environment
                 of other processes is visible on certain platforms (e.g. ps under certain Unix
                 OSes) this option should be used with caution.

       file:pathname
                 the first line of pathname is the password. If the same pathname argument is
                 supplied to -passin and -passout arguments then the first line will be used
                 for the input password and the next line for the output password. pathname
                 need not refer to a regular file: it could for example refer to a device or
                 named pipe.

       fd:number read the password from the file descriptor number. This can be used to send
                 the data via a pipe for example.

       stdin     read the password from standard input.
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值