openssl加密与模拟CA签证和颁发


libcrypto:通用功能的加密库
libssl: 用于实现TLS/SSL的功能
openssl: 多功能命令行工具, 通常会用到的功能:生成密钥、创建数字证书、手动加密解密数据;
那么,先来看下加密解密技术常用的功能及算法:
1)对称加密:
算法:DES, 3DES, AES, Blowfish, Twofish, RC6, CAST5
工具:gpg, openssl enc
使用 openssl ?可以查看命令的详细信息,尽管这种用法是错误的。
[root@bogon ~]# openssl ?
openssl:Error: '?' 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              
用来加密和解密的参数,我们用到是enc,实现对称加密(Cipher commands加密的命令)这里我们可以man enc:
NAME
       enc - symmetric cipher routines #对称加密历程,说白了就是应用程序;
SYNOPSIS
       openssl enc -ciphername [-in filename] [-out filename] [-pass arg] [-e] [-d] [-a/-base64] [-A] [-k password] [-kfile filename]
       [-K key] [-iv IV] [-S salt] [-salt] [-nosalt] [-z] [-md] [-p] [-P] [-bufsize number] [-nopad] [-debug] [-none] [-engine id]
#这里的单词ciphername译为:加密算法名称;其参数可以是在命令行中输入openssl ?后显示的那些算法;
#[-a/-base64] 表示保存为base64的文本编码格式
#举例来说,下面的例子中,源文件不会改变:
[root@bogon ~]# openssl enc -des3 -a -salt -in /etc/fstab -out /tmp/fstab.cipher
enter des-ede3-cbc encryption password:
Verifying - enter des-ede3-cbc encryption password:
[root@bogon ~]# cat /tmp/fstab.cipher 
U2FsdGVkX18Tt3X8WT6wlwan7Amp/1ypFrUqIJ7/iTpMDU7O2DI9IA7uJpWUyaoX
QM2PvESuP+cjHcsWytjk01doFfco/G7uqMwAjDkCsWtkd6pvOkai5dDeNF3oUArb
Lf4BdUPB5iwEMK/Imh/7Jo28dJdg/3bzjma0cuNy4pnjVThG6/imzsGG+U8fY8pF
wMuBRlfRTsQXW7Kae0gSiic0JCKTNZZRDnhn9rp6f2nNGy5Cs/dOFebTc63X+SkQ
dcclUnIxXNbQjt7rXbOqtINcNkU/N8GFklxuUY8d4OYLmoFvphqFTYJoMIqcocFw
ne03Se0v6hhvUX2ixSLr2tCsKZspEHxqxq9riZFTrjXet7gen0dh2NXbaOZLrR/W
6eW8GZiiRvZsHfISt8neyvVO3p464N47NwQ+3nFyn1eSvWBpp0Kt9aovfb+BJ+9+
coTR1iu7h+S1oC9OqqdXaTJySpQsgp7Zh0xV32cuU+5pr9dmoqVSd0X6QQE994su
yQa1m2aLniHhdhB0n1PLlLh05Rj42vjrRMR7wAl1R+JqHr7kcVw58/icGTL4kykn
eUuUPD8DTolZTdlUfNtvpPIf+Onf3AIt83IIHt6XSpLtVrMbl6mUbQVxsU1FYnKQ
4dbY87k7pzErlT6i89I6alPXkrbnO+5XKdYRkiLjqXD50wvVURvmoao1tp+l5H/3
OaomnyK2+bWU+hSUXLXAxqXZpG2D51hjKZQ62I4ld92YklnYAyaapiNdBWD94Uxz
Q5HrK3HuyKtDaVMtBK6HJJ867gVjM17Da1tN8mI1DJgrJNd/OHIsz5kwB4RuYQlM
/WUI0KOUCdTAhSb1ALQ9obdxjJaEUcMURwPxPQ8i/tptBqvxaKbXbkGe4Se/bept
1iJvWkAvg2AEJBRoEwGVM3UsaK7sbn7HTFFsr1moT6/CDQeHpQX0UzTbEeGy+9UV
4iNfRgczKgTwJFZGnvEbq+fJx/5M+M6Yobzv0a4/7MAaLHH2ebEfk1lxQKqab1xc
CbtPtkR6HTF/mWt+/160kKF1Pab3UtEIQ2UiZRkmMEldpdu3JEhMCdGS2swR0Vd1
wpcXqumsOdecGmV3FepFPzxA3qMP74WOygUAwvzlwIT5oDSHouIwuDosl49+iFnC
oGk62mT9Tp96jxFzfJShPbljHK1u7txRZI7L5mWFT3CLobwez/vdAUNGONW90FVi
u48msYfn4gi5RCPo0J5wGSM7WVus0GvwLYH/PTy4jxuvF1qfhFB5Hp35oRqfdQ8o
iGzjUmFtVB3fUg5KW7IV6C+811HFaK1qno8gU7NXiHg6pdxwOtCSjfi1LDL4Q8YF
B4oh2B3Vx/w=
[root@bogon ~]# openssl enc -d -des3 -a -salt -in /tmp/fstab.cipher -out /tmp/fstab.cleartex
enter des-ede3-cbc decryption password:
[root@bogon ~]# cat /tmp/fstab.cleartex 


#
# /etc/fstab
# Created by anaconda on Fri Jul 22 14:32:09 2016
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=a1bf4f08-07e0-4b3c-9518-f438b77fe176 /                       ext4    defaults        1 1
UUID=4a88f213-d8f4-4e5d-843f-1a37240d5883 /boot                   ext4    defaults        1 2
UUID=40a7d81a-cd29-4f9b-a5a2-d72f308458c7 /usr                    ext4    defaults        1 2
UUID=2c96b245-515f-4de7-9077-26a54975e50d /var                    ext4    defaults        1 2
UUID=23bccb4f-63af-430b-a8d8-9a8d3faae3be swap                    swap    defaults        0 0
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0
[root@bogon ~]# cat /etc/fstab 


#
# /etc/fstab
# Created by anaconda on Fri Jul 22 14:32:09 2016
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=a1bf4f08-07e0-4b3c-9518-f438b77fe176 /                       ext4    defaults        1 1
UUID=4a88f213-d8f4-4e5d-843f-1a37240d5883 /boot                   ext4    defaults        1 2
UUID=40a7d81a-cd29-4f9b-a5a2-d72f308458c7 /usr                    ext4    defaults        1 2
UUID=2c96b245-515f-4de7-9077-26a54975e50d /var                    ext4    defaults        1 2
UUID=23bccb4f-63af-430b-a8d8-9a8d3faae3be swap                    swap    defaults        0 0
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0


小结命令格式:
# openssl enc -des3 -a -salt -in /path/to/input_file -out /path/to/cipher_file
# openssl enc -d -des3 -a -salt -in /path/to/cipher_file -out /path/to/clear_file


2)单向加密:
常用算法:
md5: 128bits
sha1: 160bits
sha512: 512bits
命令工具:sha1sum, md5sum, cksum, openssl dgst


单向加密,两种方法一样,举例说明如下:
[root@bogon ~]# sha1sum /tmp/fstab.cleartex 
e277d404d49e0bb744028f74f010fbbc69ca3ef1  /tmp/fstab.cleartex
[root@bogon ~]# openssl dgst -sha1 /tmp/fstab.cleartex 
SHA1(/tmp/fstab.cleartex)= e277d404d49e0bb744028f74f010fbbc69ca3ef1


小结此加密格式,可以自己man dgst查看:# openssl dgst [-md5|-md4|-md2|-sha1|-sha|-mdc2|-ripemd160|-dss1] [-out filename] /path/to/somefile


3)用户认证:
工具:passwd, openssl passwd
# openssl passwd -1 
例如:
[root@bogon ~]# man sslpasswd
[root@bogon ~]# openssl passwd -1
Password: 
Verifying - Password: 
$1$fowx7D.3$FREUT8loiNFZYXvGT1lID/
[root@bogon ~]# openssl passwd -1 -salt fowx7D.3
Password: 
$1$fowx7D.3$FREUT8loiNFZYXvGT1lID/


4)MAC: 消息摘要码,单向加密的延伸应用
应用:用于实现在网络通信中保证所传输的数据完整性;
机制:
CBC-MAC:循环冗余校验码;
HMAC:使用md5和sha1算法;能够实现消息认证;
5)公钥加密:公钥加密、私钥解密
密钥对儿:
公钥:pkey
私钥:skey
算法:RSA, EIGamal
工具:gpg, openssl rsautl
数字签名:私钥加密、公钥解密
算法:RSA, EIGamal, DSA(只能用来做签名无法加密的算法,全称英文如下。)
DSA: Digital Signature Algorithm
或者也可称为DSS: Digital Signature Standard
密钥交换:IKE(Intenet Key Exchange)
算法:DH(Diffie-Hellman), 用在公钥加密。
 
数字证书格式:x509、pkcs  (分为个人证书,组织证书,公司证书等好多种;)
x509格式:
公钥和有效期限;
持有者的个人合法身份信息;(公司名、主机名、等等)
证书的使用方式;(实现加密传输或者主机间的认证)
CA的信息;(谁给你发的证)
CA的数字签名;(验证是否合法,用CA自己的私钥就行加密认证。)
谁给CA发证:自签署证书


与现实生活原理非常相似;
申请方:需要生成一对密钥对;把所需信息和公钥按固定格式制作成证书申请;
颁证方(必须合法得有自己的密钥对,所以得先自签证书):需要进行对申请方核实检查后,达到资质,方可颁发;
1、用openssl实现私有CA:
               配置文件:/etc/pki/tls/openssl.cnf 这个文件我们几乎不用修改;
[ 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
服务端:
man genrsa 我么可以知道私钥也可以加密,但接下来的操作没有对私钥加密;而且,公钥是从私钥中来,成对出现;这里不再列出man genrsa 的结果;
[root@My-Linux ~]# cd /etc/pki/CA/
[root@My-Linux CA]# ll
total 16
drwxr-xr-x. 2 root root 4096 Aug 15  2014 certs
drwxr-xr-x. 2 root root 4096 Aug 15  2014 crl
drwxr-xr-x. 2 root root 4096 Aug 15  2014 newcerts
drwx------. 2 root root 4096 Aug 15  2014 private
[root@My-Linux CA]# ll private/
total 0
[root@My-Linux CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus
.......................................................................+++
........................................................................................................+++
e is 65537 (0x10001)
[root@My-Linux CA]# ll private/
total 4
-rw------- 1 root root 1675 Jul 26 00:15 cakey.pem


提取公钥,在输入命令后的结果的最下面,这一步并不是必要的;
[root@My-Linux CA]# openssl rsa -in private/cakey.pem -pubout -text


2、接下来服务端生成自签证书:
[root@My-Linux CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 36550
You are about to be asked to enter information that will be incorporated
into 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 blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:BeiJing
Locality Name (eg, city) [Default City]:BeiJing                 
Organization Name (eg, company) [Default Company Ltd]:GUN 
Organizational Unit Name (eg, section) []:Linux Operation
Common Name (eg, your name or your server's hostname) []:ca.My-Linux
Email Address []:root@My-Linux.com
[root@My-Linux CA]# ls -l
total 20
-rw-r--r--  1 root root 1440 Jul 26 00:30 cacert.pem
drwxr-xr-x. 2 root root 4096 Aug 15  2014 certs
drwxr-xr-x. 2 root root 4096 Aug 15  2014 crl
drwxr-xr-x. 2 root root 4096 Aug 15  2014 newcerts
drwx------. 2 root root 4096 Jul 26 00:15 private
#还差这三个文件,创建完成;然后,我们还会找一个客户端,这里先给一个编号到serial文件中;
[root@My-Linux CA]# touch index.txt serial crlnumber
[root@My-Linux CA]# echo 0001 > serial 


3、客户端生成密钥对
[root@bogon ~]# cd /etc/httpd/
[root@bogon httpd]# mkdir ssl
[root@bogon httpd]# (umask 077;openssl genrsa -out httpd.key 1024)
Generating RSA private key, 1024 bit long modulus
..++++++
..........++++++
e is 65537 (0x10001)
[root@bogon httpd]# mv httpd.key ssl/
[root@bogon httpd]# cd ssl/
[root@bogon ssl]# ll
total 4
-rw------- 1 root root 887 Jul 29 15:09 httpd.key
[root@bogon ssl]# openssl req -new -key httpd.key -out httpd.csr
You are about to be asked to enter information that will be incorporated
into 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 blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:BeiJing
Locality Name (eg, city) [Default City]:BeiJing
Organization Name (eg, company) [Default Company Ltd]:GUN
Organizational Unit Name (eg, section) []:Linux Operation
Common Name (eg, your name or your server's hostname) []:www.GUN.com
Email Address []:root@My-Linux.com


Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: #此处,笔者为了方便,直接回车没有输入密码;
An optional company name []: #此处,笔者为了方便,直接回车没有输入密码;
[root@bogon ssl]# ll
total 8
-rw-r--r-- 1 root root 708 Jul 29 15:14 httpd.csr
-rw------- 1 root root 887 Jul 29 15:09 httpd.key
[root@bogon ssl]# ll
total 8
-rw-r--r-- 1 root root 708 Jul 29 15:14 httpd.csr
-rw------- 1 root root 887 Jul 29 15:09 httpd.key
[root@bogon ssl]# scp httpd.csr root@192.168.136.129:/tmp  #将申请发送给服务端的CA认证机构
The authenticity of host '192.168.136.129 (192.168.136.129)' can't be established.
RSA key fingerprint is 1a:50:cd:ec:bd:51:01:29:72:da:c6:dc:70:42:9b:8e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.136.129' (RSA) to the list of known hosts.
reverse mapping checking getaddrinfo for bogon [192.168.136.129] failed - POSSIBLE BREAK-IN ATTEMPT!
root@192.168.136.129's password: 
httpd.csr                                                                                                         100%  708     0.7KB/s   00:00  

服务端签署证书并发送给客户端:
[root@My-Linux CA]# ls /tmp/
httpd.csr       keyring-Q9cHcV  orbit-gdm   pulse-d4QMt9LoeHN5  virtual-root.7mtIpw  virtual-root.JjkOwj  virtual-root.pZlRoD
keyring-LxDSv2  keyring-xFTrMl  orbit-root  pulse-x9Gj6GmkMxsK  virtual-root.f6IPnk  virtual-root.pVcl59  virtual-root.SDSDl4
[root@My-Linux CA]# openssl ca -in /tmp/httpd.csr -out /tmp/httpd.crt -days 36550
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Jul 25 17:03:40 2016 GMT
            Not After : Aug 20 17:03:40 2116 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = BeiJing
            organizationName          = GUN
            organizationalUnitName    = Linux Operation
            commonName                = www.GUN.com
            emailAddress              = root@My-Linux.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                29:17:49:B0:71:98:CD:C7:31:3B:75:F3:24:32:67:BE:16:21:6E:38
            X509v3 Authority Key Identifier: 
                keyid:57:35:44:34:1F:47:C5:98:A3:1D:A2:24:55:6F:E2:5C:29:77:D2:CE


Certificate is to be certified until Aug 20 17:03:40 2116 GMT (36550 days)
Sign the certificate? [y/n]:y




1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@My-Linux CA]# cat serial
02
[root@My-Linux CA]# scp /tmp/httpd.crt root@192.168.136.128:/etc/httpd/ssl/
The authenticity of host '192.168.136.128 (192.168.136.128)' can't be established.
RSA key fingerprint is cc:bf:c7:c4:fb:78:18:12:48:4e:94:31:07:3a:5f:7a.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.136.128' (RSA) to the list of known hosts.
root@192.168.136.128's password: 
httpd.crt                                                                                                         100% 3891     3.8KB/s   00:00  

客户端收到了:
[root@bogon ssl]# ll
total 12
-rw-r--r-- 1 root root 3891 Jul 29 15:27 httpd.crt
-rw-r--r-- 1 root root  708 Jul 29 15:14 httpd.csr
-rw------- 1 root root  887 Jul 29 15:09 httpd.key


然后,我们就可以使用此证书搭建我们的web服务器了。

补充吊销证书:
# openssl ca -revoke /path/to/somefile.crt  吊销后会保存在吊销目录中;这个命令在公司中不是很常用;




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值