Openssl证书管理

 

Openssl证书管理

转载自:http://wiki.ubuntu.org.cn/Openssl%E8%AF%81%E4%B9%A6%E7%AE%A1%E7%90%86

为CA创建一个RSA私钥

openssl genrsa -out ca.key 2048

利用CA的RSA私钥创建一个自签名的CA证书

openssl req -new -x509 -days 3650 -key ca.key -out ca.crt -extensions v3_ca -config openssl.cnf 

[编辑]python编程实现Demon

利用python pexpect模块来按照预定义的结果自动完成

#!/usr/bin/env python

'create CA cert '

import os
import pexpect
CA_KEY     = "/mnt/home/panhaitao/ca/ca.key"
CA_CRT     = "/mnt/home/panhaitao/ca/ca.crt"
CA_CONFIG  = "/mnt/home/panhaitao/ca/openssl.cnf"

# 命令原型 openssl req -new -x509 -days 3650 -key ca.key -out ca.crt -extensions v3_ca -config openssl.cnf 

child = pexpect.spawn('openssl req -new -x509 -days 3650 -key %s -out %s -extensions v3_ca -config %s '%(CA_KEY, CA_CRT, CA_CONFIG))

child.sendline ('\n')
child.sendline ('\n')
child.sendline ('\n')
child.sendline ('\n')
child.sendline ('\n')
child.sendline ('koji')
child.sendline ('\n')

print 'DONE'

[编辑]为客户创建一个RSA私钥,并使用CA证书来对其签署

openssl genrsa -out client.key 2048
openssl req -new -nodes -key client.key -out client.csr -config openssl.cnf
openssl ca -keyfile ca.key -cert ca.crt -in client.csr -out client.crt -outdir certs -config openssl.cnf 
cat client.crt client.key > client.pem

[编辑]撤销一个客户证书

openssl ca -gencrl -out crl/sopac-ca.crl -config openssl.cnf

[编辑]下面是收集整理的资料

openssl req -new -x509 -days 3650 -newkey rsa:2048 -keyout ca.key -out ca.crt -extensions v3_ca -config openssl.cnf 为客户颁发证书,为客户创建证书,先用genrsa命令生成的私钥,用req命令生成证书签署请求CSR

openssl genrsa -out client.key 2048
openssl req -new -nodes -key client.key -out client.csr -config openssl.cnf


openssl req -new -nodes -newkey rsa:2048 -keyout client.key -out client.csr -config openssl.cnf

[编辑]openssl.cnf 解读

 
CSR (Certificate Signing Request) 证书签发请求  

证书文件生成

也许很多人和本人一样深有体会,使用OpenSSL库写一个加密通讯过程,代码很容易就写出来了,可是整个工作却花了了好几天。除将程序编译成功外(没有可以使用的证书文件,编译成功了,它并不能跑起来,并不表示它能正常使用,所以......),还需生成必要的证书和私钥文件使双方能够成功验证对方。
找了n多的资料,很多是说的很模糊,看了n多的英文资料,还是没有办法(不知道是不是外国朋友都比较厉害,不用说明得太清?),无意间找到yawl([email protected])写的文章,难得的汉字(呵呵)。里面有生成证书部分,说到生成了Certificate Signing Request (CSR)文件后,就有点不太清楚了。后面生成自签字证书在很多地方都可以找到的,签名这部分,yawl说mod_ssl有比较好的脚本,但是笔者一时找不到,就自己用openssl的ca命令来完成了,也不是很麻烦。 

说说本人的操作环境:无盘工作站(有权限问题使用起来不太方便),操作目录是openssl/bin(没办法改不了环境变量,如果你可以改的话,就不用在这个目录下工作了),为了方便本人把apps下的openssl.cnf也复制到了这个目录下来。文件名都是以本人使用的来说了:

1.首先要生成服务器端的私钥(key文件):
openssl genrsa -des3 -out server.key 1024
运行时会提示输入密码,此密码用于加密key文件(参数des3便是指加密算法,当然也可以选用其他你认为安全的算法.),以后每当需读取此文件(通过openssl提供的命令或API)都需输入口令.如果觉得不方便,也可以去除这个口令,但一定要采取其他的保护措施!
去除key文件口令的命令:
openssl rsa -in server.key -out server.key

2.openssl req -new -key server.key -out server.csr -config openssl.cnf
生成Certificate Signing Request(CSR),生成的csr文件交给CA签名后形成服务端自己的证书.屏幕上将有提示,依照其指示一步一步输入要求的个人信息即可.

3.对客户端也作同样的命令生成key及csr文件:
openssl genrsa -des3 -out client.key 1024
openssl req -new -key client.key -out client.csr -config openssl.cnf

4.CSR文件必须有CA的签名才可形成证书.可将此文件发送到verisign等地方由它验证,要交一大笔钱,何不自己做CA呢.
openssl req -new -x509 -keyout ca.key -out ca.crt -config openssl.cnf

5.用生成的CA的证书为刚才生成的server.csr,client.csr文件签名:
Openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key -config openssl.cnf
Openssl ca -in client.csr -out client.crt -cert ca.crt -keyfile ca.key -config openssl.cnf

现在我们所需的全部文件便生成了.

另:
client使用的文件有:ca.crt,client.crt,client.key
server使用的文件有:ca.crt,server.crt,server.key
.crt文件和.key可以合到一个文件里面,本人把2个文件合成了一个.pem文件(直接拷贝过去就行了)

 

#
# OpenSSL example configuration file. 
# This is mostly being used for generation of certificate requests.
# 翻译:
# Openssl 配置文件示例。该文件主要用于生成证书   
  

# 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节从这里开始定义

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

dir		= ./demoCA		# 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	= default		# use public key default MD
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    定义CA证书的策略
[ 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		= 1024
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		= AU
countryName_min			= 2
countryName_max			= 2

stateOrProvinceName		= State or Province Name (full name)
stateOrProvinceName_default	= Some-State

localityName			= Locality Name (eg, city)

0.organizationName		= Organization Name (eg, company)
0.organizationName_default	= Internet Widgits Pty 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 (e.g. server FQDN or YOUR name)
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		= md5, sha1		# 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)

[编辑]一份原创参考资料

一、RSA方式

1. 建立CA根证书 1) 建立目录RSA 2) 创建以下子目录certs, crl, newcerts 3) 在RSA目录下执行以下操作:

  1. echo 01 > serial
  2. touch index.txt
  3. openssl req -new -x509 -newkey rsa:1024 -keyout CA.key -out CA.pem (生成自签名CA证书)

2. 客户端证书请求

  1. openssl req -new -newkey rsa:1024 -keyout ddmdd_a.key -out ddmdd_a.req (生成ddmdd_a的密钥和证书请求,注意: 此处所填写的用户信息必须与CA证书信息完全一致)
  2. openssl rsa -in ddmdd_a.key -pubout -out ddmdd_a.pub (导出公钥)

3. 为客户签发证书

  1. openssl ca -keyfile CA.key -cert CA.pem -in ddmdd_a.req -out ddmdd_a.pem -notext (使用CA密钥和证书为ddmdd_a签发证书ddmdd_a.pem)
  2. openssl ca -keyfile CA.key -cert CA.pem -in subca_rsareq.pem -out subca.pem -notext (签发二级CA证书)

4. 转换证书格式

  1. openssl x509 -inform pem -outform der -in ddmdd_a.pem -out ddmdd_a.der
  2. openssl pkcs12 -export -in ddmdd_a.pem -inkey ddmdd_a_rsakey.pem -out ddmdd_a.pfx
  3. openssl pkcs12 -in ddmdd_a.pfx -out ddmdd_a.pem
  4. openssl rsa -in ddmdd_a.key -out ddmdd_a_open.key (删除私钥密码)

5. 生成证书撤消列表

  1. echo 01 > crlnumber
  2. openssl ca -keyfile  CA.key -cert CA.pem -revoke ddmdd_a.pem (从CA中撤消证书ddmdd_a.pem)
  3. openssl ca -gencrl -keyfile CA.key -cert CA.pem -out CA.crl (生成或更新证书撤消列表)

6. 查看证书信息

  1. openssl x509 -in CA.pem -noout –text


二、DSA方式

1. 建立CA根证书 1) 建立目录DSA 2) 创建以下子目录certs, crl, newcerts 3) 在DSA目录下执行以下操作:

  1. echo 01 > serial
  2. touch index.txt
  3. openssl dsaparam -out CA.para 1024 (生成dsa参数文件)
  4. openssl req -new -x509 -newkey dsa:CA.para -keyout CA.key -out CA.pem (使用dsa参数生成自签名CA证书)

2. 客户端证书请求

  1. openssl dsaparam -out ddmdd_b.para 1024 (生成dsa参数文件)
  2. openssl req -new -newkey dsa:ddmdd_b.para -keyout ddmdd_b.key -out ddmdd_b.req (使用dsa参数生成ddmdd_b的密钥和证书请求,注意: 此处所填写的用户信息必须与CA证书信息完全一致)
  3. openssl dsa -in ddmdd_b.key -pubout -out ddmdd_b.pub (导出公钥)

3. 为客户签发证书

  1. openssl ca -keyfile CA.key -cert CA.pem -in ddmdd_b.req -out ddmdd_b.pem -notext (使用CA密钥和证书为ddmdd_b签发证书ddmdd_b.pem)

[编辑]参考资料

  1. [ 使用 OpenSSL API 进行安全编程 http://www.ibm.com/developerworks/cn/linux/l-openssl.html ]
  2. [ 通用线程: OpenSSH 密钥管理,第 1 部分 http://www.ibm.com/developerworks/cn/linux/security/openssh/part1/index.html ]
  3. [ 通用线程: OpenSSH 密钥管理,第 2 部分 http://www.ibm.com/developerworks/cn/linux/security/openssh/part2/index.html ]
  1. [ 数据结构物语卷一http://www.nowamagic.net/librarys/veda/special/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%89%A9%E8%AF%AD%E5%8D%B7%E4%B8%80/]
  2. http://www.cnblogs.com/shipfi/archive/2008/10/12/1309168.html

[编辑]使用OpenSSL实现证书的管理

1 为CA创建一个RSA私钥

#openssl genrsa -des3 -out -ca.key 1024

系统提示输入PEM pass pharse,也就是密码。生成ca.key文件,可以将文件的属性改为400,并放在安全的地方。

2 利用CA的RSA私钥创建一个自签名的CA证书
创建一个自签名的证书(Selfsigned certificate)运行req命令,该命令生成一个ca.crt。
#openssl req -new -x509 -days 3650 -key ca.key -out ca.crt

然后系统提示输入国家代号、省份名称、城市名称、公司名称、部门名称、你的姓名及Email地址,这样一张自签名的CA证书就制作完成。

3 为客户颁发证书
为客户创建证书,先用genrsa命令生成的私钥,用req命令生成证书签署请求CSR。
#openssl genrsa -des3 -out client.key 1024

#openssl req -new -key client.key -out client.csr这里也要输入个人的信息。

然后用sign.sh签署证书。
#./sigh.sh client.crt

这样由CA签发的证书就制作完成。

4 撤消证书
要吊消证书可以使用openssl的ca命令,它可以对证书进行吊消、加进CRL及CRL有关的其它一些处理。
要吊消证书可以简单地使用以下命令:
#openssl ca -revoke 证书文件名
这时数据库被更新证书被标记上吊消的标志,需要生成新的证书吊消列表:
  1. openssl ca -gencrl -config /etc/openssl.cnf -out crl/sopac-ca.crl

证书吊消列表文件要在WEB站点上可以使用,必须将crldays或crlhours和crlexts加到证书中: openssl ca -gencrl -config /etc/openssl.cnf -crldays 7 -crlexts crl_ext -out crl/sopac-ca.crl

5 证书的更新
当用户发送他旧的证书证书或要在原有私钥的基础上建新的证书,所以必须吊消旧的证书然后再签发新的证书。要找到证书,可以用户的DN(区别名)在 index.txt文件中查到序列号xx,用cert/.pem做为证书吊消的依据。你必须手动签发证书,因为开始时间和结束时间以 便确定新证书的有效性。
#openssl ca -config /etc/openssl.cnf -policy policy_anything -out newcert.pem -infiles newreq.pem -startdate [now] -enddate [previous enddate+365days]

用正确的时间替换 [now]和[previous enddate+365days]。

6 查看证书
#openssl x509 -in cert.pem -noout -text

 

你可能感兴趣的:(CA,Openssl,Ubuntu,SSH,Ubuntu,数据库,python,操作系统)