先来介绍下三种加密方式:

  1. 对称加密
  2. 公钥加密
  3. 单向加密

对称加密

openssl pem加密文件 openssl密码加密_网络

实现工具openssl enc介绍

[root@node1 sh]# man enc
enc - symmetric cipher routines   对称密码
-in filename  
-out filename
-salt
-S   十六进制salt
-nosalt

-e  加密 encrypt the input data
-d  解密decrypt the input data.
-a  -base64  加密得到base64
-A  得到一行的base64
-p  print out the key and IV used.错误的话会报错
-P  print out the key and IV used.错误的话会不会输出 明文
-z  压缩

-pass pass:"123"      #密码是123  
-pass pass:123        #密码是123  
-pass evn:VAR         #密码从环境变量VAR中去  
-pass file:p.txt      #密码从文件p.txt第一行去,不包括换行符,注意DOS格式的^M及回车符。  
-pass fd:3            #密码从文件描述符3中读  
-pass stdin           #标准输入

字符串加密解密

#默认salt  des3
[root@node1 sh]# echo 'zander'|openssl enc -e  -des3 -salt -pass pass:"99" -a
U2FsdGVkX194kB7nt8HybghJn3KAHoIo
[root@node1 sh]# echo "U2FsdGVkX194kB7nt8HybghJn3KAHoIo"| openssl enc -d -des3 -salt -pass pass:"99" -a
zander

#指定salt  aes256
[root@node1 sh]# echo 'zanderzanderzander'|openssl enc -e  -aes256 -S 012F -pass pass:"99" -a
U2FsdGVkX18BLwAAAAAAAFPXPKSxoUEf7dQpfiY73AwBz3aaH00+pVnf+W54DT0k
[root@node1 sh]# echo "U2FsdGVkX18BLwAAAAAAAFPXPKSxoUEf7dQpfiY73AwBz3aaH00+pVnf+W54DT0k"| openssl enc -d -aes256 -S 012F -pass pass:"99" -a
zanderzanderzander

文件操作

#保存到文件
[root@node1 test]# openssl enc -e -des3 -a -salt -in fstab -out fstab.cipher -pass pass:abc
[root@node1 test]# cat fstab.cipher
U2FsdGVkX1/WiSzaJnPYsK94ra0wkxT3SjK/27b9fH10xWSrjppLpk8BgIa58oJh
/CrbiIqpg6DXje3CVMKD0Te++9TXs8SdkuE6rAy+a5yANcyYxhwjwVxsEwZgOQu0
GBZUXVvlSnDpaLP7GjOhrsQxdgUaZ+2s9znIvwpqh0JCWUSZJQb6ueA4jbljjY3K
rs2T3IXUqpkNaKvVWhXCuB0wZ/yEVhbcHaKvxglh4vZKk2ee9pryzhMVy8SvoIsp
4p/yeBpNiH+7YNIM6go5w2/bOnG+2nabH3VvCsmPAUqBgjwQbHuqG3B58etUdED0
SXSUZ2TJhDmGz2CUq0uPtYvlkaxj9Jc2SWKERsb39XkfcZPOhzvZPr2FfR8IopKp
5ptGbVGFs6dpT3AyVZUwkeauLoXHWYsgbbuMWlPHdnX6NDB1m1vCnTcw0rhIjVLh
dPqI/85B5ngh2mN7Lpef8u+2h+/3ukDEcp3cFKvswhcVVe3ls684xdwal2xdxu5u
E8jUn+8YfkK86zpQmgb5RehBvcGuH6iKgInLF2jCOgBG/fNJG0aS8A16LW7Pjx5E
Vs7nBnHWLd7O7LHx1/39m9zDFejBFclh9pvaEFvOUUbsqcAdvsJ2GTiSiHDjIMRT
bKTE6WL0BlhIq/9yz+NE+RgIv4YFfQbMyt93iiCt4ywTwRxbK5AEQw==

#解密
[root@node1 test]# openssl enc -d -des3 -a -salt -in fstab.cipher -out fstab.decrypt -pass pass:abc
[root@node1 test]# cat fstab.decrypt

#
# /etc/fstab
# Created by anaconda on Sun Apr 22 06:26:44 2018
#
# 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=7ceb028a-a8b8-467c-b6d4-36910c06c5ac /                       xfs     defaults        0 0
UUID=3d81b92c-abeb-41f5-8de0-b46d3ffbcf4c /boot                   xfs     defaults        0 0
UUID=943c7e04-b733-42fe-a1e2-eabf93693f6b swap                    swap    defaults        0 0
[root@node1 test]# diff fstab fstab.decrypt

公钥加密

公钥加密也称非对称加密,私钥生产依赖随机数

/dev/random:仅从熵池返回随机数;随机数用尽,阻塞;

/dev/urandom:从熵池返回随机数;随机数用尽,会利用软件生成伪随机数,非阻塞;

openssl pem加密文件 openssl密码加密_网络_02

公钥私钥生产

#(umask 077;openssl genrsa 1024 >mykey.private)  # (umask 077;openssl genrsa -out mykey.private 1024)
#生产私钥
[root@node1 test]# (umask 077;openssl genrsa -out mykey.private 1024)   #() 中的命令要在子shell中运行,  umask 077 不影响默认
Generating RSA private key, 1024 bit long modulus
....++++++
....................................................++++++
e is 65537 (0x10001)
[root@node1 test]# ll mykey.private
-rw-------. 1 root root 887 May  8 09:50 mykey.private

#提取公钥  openssl  rsa  -in mykey.private -pubout  -out  mykey.public
[root@node1 test]# openssl rsa  -in mykey.private -pubout > mykey.public  
writing RSA key
[root@node1 test]# openssl rsautl -encrypt -inkey mykey.public -pubin -in w.txt -out w.en
[root@node1 test]# openssl rsautl -decrypt -inkey mykey.private -in w.en -out w.de
[root@node1 test]# diff w.txt w.de
[root@node1 test]#

单向加密

openssl pem加密文件 openssl密码加密_运维_03

工具openssl dgst

[root@node1 test]# man dgst
-c:打印出两个哈希结果的时候用冒号来分隔开。仅仅设置了[-hex]的时候有效。
-hex:显示ASCII编码的十六进制摘要结果,默认选项。
-d:打印出BIO调试信息值。
-binary:以二进制的形式来显示摘要结果值。
-r:用coreutils格式来输出摘要值。
-out filename:输出对象,默认为标准输出。
-sign filename:用filename中的私钥文件对数据进行签名。
-keyform arg:filename中的证书格式,该命令中仅仅支持PEM以及ENGINE格式。
-verify filename:用filename中的公钥文件对数据进行验证签名。输出结果仅仅是"Verification OK" 和 "Verification Failure"中的一种。
-hmac key:用密钥“key”创建一个哈希值MAC。    很好用
file:你要哈希的文件,如果没有指定,就使用标准输入。

字符串操作

#字符串
#-----------------shell--------------------------------
[root@node1 test]# echo -n zander|openssl dgst -md5
(stdin)= 4d484333d33a97eaf9c50d617301778b
#-----------------python--------------------------------
import hashlib
hl = hashlib.md5()
hl.update("zander".encode(encoding='utf-8'))
print(hl.hexdigest())
#4d484333d33a97eaf9c50d617301778b

#强烈推荐用hmac
#-----------------shell--------------------------------  
[root@node1 test]# echo -n zander|openssl dgst -sha512 -hmac 'abc'
(stdin)= f358e2e97da822e152a2f946ac1e629d9adcf14d2f1b2aafabc357659a1ac8c8a9cc728f5f6cc6413ba836a888779e4789921ffdc932c4bd39ba362416a22703
#-----------------python--------------------------------
import hashlib,hmac
hl = hmac.new('abc'.encode(encoding='utf-8'), "zander".encode(encoding='utf-8'), digestmod='sha512')
print(hl.hexdigest())
##f358e2e97da822e152a2f946ac1e629d9adcf14d2f1b2aafabc357659a1ac8c8a9cc728f5f6cc6413ba836a888779e4789921ffdc932c4bd39ba362416a22703

文件md5

#文件md5值
[root@node1 test]# openssl dgst -md5 fstab
MD5(fstab)= df49cbcbbc00c2e8cf302a458eed1388

[root@node1 test]# md5sum fstab
df49cbcbbc00c2e8cf302a458eed1388  fstab

md5加密

#密码
[root@node1 test]# man sslpasswd  
#只支持 md5

[root@node1 test]# echo zander|openssl passwd -1 -salt 88 -stdin
$1$88$qMX4lD4kTYz5R5q/ZfKK1/

ssl 握手图解

openssl pem加密文件 openssl密码加密_运维_04


网络加密过程分析

openssl pem加密文件 openssl密码加密_运维_05


构建一个企业级后台https双向认证后台

1、构建私有CA:在确定配置为CA的服务上生成一个自签证书,并为CA提供所需要的目录及文件即可;

#(1) 生成私钥;
[root@node1 sh]# (umask 077; openssl genrsa -out /etc/pki/CA/private/cakey.pem  4096)
[root@node1 sh]# ll /etc/pki/CA/private/cakey.pem
-rw-------. 1 root root 3243 May  8 09:49 /etc/pki/CA/private/cakey.pem

#(2) 生成自签证书;
[root@node1 sh]# openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out /etc/pki/CA/cacert.pem -days 3655
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) []:zhejiang
Locality Name (eg, city) [Default City]:nb
Organization Name (eg, company) [Default Company Ltd]:zander
Organizational Unit Name (eg, section) []:ops
Common Name (eg, your name or your server's hostname) []:ca.zander.com
Email Address []:

[root@node1 sh]# ll /etc/pki/CA/cacert.pem
-rw-r--r--. 1 root root 2004 May  8 10:00 /etc/pki/CA/cacert.pem

#(3) 为CA提供所需的目录及文件;
[root@node1 sh]# mkdir  -pv  /etc/pki/CA/{certs,crl,newcerts}
[root@node1 sh]# touch  /etc/pki/CA/{serial,index.txt}
[root@node1 sh]# echo  01 > /etc/pki/CA/serial

2、客户端 请求签证

#客户端
[root@marvin yii_test]# pwd
/usr/local/www/nginx/conf/ssl/yii_test

[root@marvin yii_test]# openssl req -new -key httpd.key -out httpd.csr -days 3650
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) []:zhejiang
Locality Name (eg, city) [Default City]:nb
Organization Name (eg, company) [Default Company Ltd]:zander      #申请ca组织必须跟ca保持一致!
Organizational Unit Name (eg, section) []:Ops
Common Name (eg, your name or your server's hostname) []:yii-test.local
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:abcd
An optional company name []:

#发送给ca服务进行签证
[root@marvin yii_test]# scp httpd.csr  root@192.168.1.102:~/

3、ca签证,并返回

[root@node1 ~]# openssl ca  -in httpd.csr -out /etc/pki/CA/certs/yii-test.crt -days 3650
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 2 (0x2)
        Validity
            Not Before: May  8 23:46:53 2018 GMT
            Not After : May  5 23:46:53 2028 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = zhejiang
            organizationName          = zander
            organizationalUnitName    = Ops
            commonName                = yii-test.local
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                AE:25:74:75:C3:EE:E4:FF:B4:17:F6:28:B4:23:1F:61:67:55:35:DF
            X509v3 Authority Key Identifier:
                keyid:F8:3B:8D:6B:EF:B8:AE:13:9E:97:81:06:B3:E4:7C:A6:18:68:16:10

Certificate is to be certified until May  5 23:46:53 2028 GMT (3650 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@node1 ~]# cat /etc/pki/CA/index.txt
R   280505142027Z   180508143504Z   01  unknown /C=CN/ST=zhejiang/O=zander/OU=Ops/CN=www.zander.com
V   280505234653Z       02  unknown /C=CN/ST=zhejiang/O=zander/OU=Ops/CN=yii-test.local

#返回客户端签证证书  和  ca服务器的证书
[root@node1 ~]# scp /etc/pki/CA/certs/yii-test.crt  root@172.16.86.128:/usr/local/www/nginx/conf/ssl/yii_test
#服务器发送ca公钥给客户端   客户端本地认证服务器公钥是否合法
[root@node1 ~]# scp /etc/pki/CA/cacert.pem   root@172.16.86.128:/usr/local/www/nginx/conf/ssl/yii_test

4、以nginx为例配置客户端服务

server {
    charset utf-8;
    client_max_body_size 128M;

    listen 443;
    server_name yii-test.local;
    root    /mydata/code/php/yii-test.dev/web;
    index       index.php;

    ssl on;
    ssl_certificate     /usr/local/www/nginx/conf/ssl/yii_test/yii-test.crt;
    ssl_certificate_key  /usr/local/www/nginx/conf/ssl/yii_test/httpd.key;
    ssl_client_certificate /usr/local/www/nginx/conf/ssl/yii_test/cacert.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
#    ssl_verify_client on;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include fastcgi.conf;
        fastcgi_pass   127.0.0.1:9000;
        try_files $uri =404;
    }

    error_page 404 /404.html;
        location ~ /\.(ht|svn|git) {
        deny all;
    }
}

openssl pem加密文件 openssl密码加密_php_06


以上https配置完毕。

5、配置https双向认证 客户端配置(实际生产最好在在生产一组新的密钥跟签证来生产p12,毕竟服务器这组是为了加密解密用)

[root@marvin yii_test]# openssl pkcs12 -export -clcerts -inkey httpd.key  -in yii-test.crt  -out yii-test.p12   #用服务器私钥加密签证证书生产p12证书给客户端,ca公钥能完成数字签名认证
Enter Export Password:
Verifying - Enter Export Password:
[root@marvin yii_test]# ls
httpd.key  yii-test.crt  yii-test.p12

6、修改nginx配置文件 开启双向认证

ssl on;
    ssl_certificate     /usr/local/www/nginx/conf/ssl/yii_test/yii-test.crt;
    ssl_certificate_key  /usr/local/www/nginx/conf/ssl/yii_test/httpd.key;
    ssl_client_certificate /usr/local/www/nginx/conf/ssl/yii_test/cacert.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_verify_client on;

客户需要安装yii-test.p12访问

openssl pem加密文件 openssl密码加密_openssl pem加密文件_07


openssl pem加密文件 openssl密码加密_运维_08