openssl的介绍和使用

C/C++Linux服务器开发/后台架构师知识体系

openssl简介

OpenSSL是一个安全套接字层密码库,其包括常用的密码算法、常用的密钥生成和证书封装管理功能及SSL协议,并提供了丰富的应用程序以供测试。

OpenSSL 是一个开源项目,其组成主要包括一下三个组件:

  • openssl:多用途的命令行工具
  • libcrypto:加密算法库
  • libssl:加密模块应用库,实现了ssl及tls

openssl 可以实现:秘钥证书管理、对称加密和非对称加密更多简介和官网。

openssl命令工具有两种运行模式:交换模式和批处理模式。直接输入openssl回车即可进入交互模式,而输入带命令选项的openssl命令则进行批处理模式。

1、对称加密算法的应用

利用OpenSSL作对称加密需要使用其子命令enc,其用法为:

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]

其中常用的选项为:

-e:加密;
-d:解密;
-ciphername:ciphername为相应的对称加密算命名字,如-des3、-ase128、-cast、-blowfish等等。
-a/-base64:使用base-64位编码格式;
-salt:自动插入一个随机数作为文件内容加密,默认选项;
-in FILENAME:指定要加密的文件的存放路径;
-out FILENAME:指定加密后的文件的存放路径;

使用案例:

  • 加密字符串
[root@localhost ~]# echo "hello,world" | openssl enc -aes128 -e -a -salt
enter aes-128-cbc encryption password:
Verifying - enter aes-128-cbc encryption password:
U2FsdGVkX1/LT+Ri9pzjjS0FIGXJLNRc8ljvZJ3hf0M=
  • 加解密文件
[root@localhost ~]# openssl enc -des3 -e -a -in /etc/fstab -out /tmp/fstab
enter des-ede3-cbc encryption password:
Verifying - enter des-ede3-cbc encryption password:

[root@localhost ~]# cat /tmp/fstab 
U2FsdGVkX1/pdsq5HUjsP5Kpqr378qnZSmH1j9a4KdasuG+6Jy+Mh0cRYA5IUuJ4
732mG1td6x2jvLq0JNpT+WcTFXoH30x1o6KDN6Kwyc26+uTjYb+cwf9ZhZWoEi4c
5Zh1h8S4PwKA9m/ebJAh97RSLuVWqPOsZDJ9w/zE3X0iKnb8nVNEkApB6OYjkV4s
....

[root@localhost ~]# openssl enc -d -des3 -a -salt -in /tmp/fstab 
enter des-ede3-cbc decryption password:
#
# /etc/fstab
# Created by anaconda on Sun Nov 19 02:26:36 2017
....
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0

2、单向加密

OpenSSL单向加密的子命令为dgst,其语法如下:

openssl dgst [-md5|-md4|-md2|-sha1|-sha|-mdc2|-ripemd160|-dss1] [-c] [-d] [-hex] [-binary] [-out filename] [-sign filename] [-keyform arg] [-passin arg] [-verify filename] [-prverify filename] [-signature filename] [-hmac key] [file…]

其常用的选项为:

[-md5|-md4|-md2|-sha1|-sha|-mdc2|-ripemd160|-dss1]:指定一种单向加密算法;
-out FILENAME:将加密的内容保存到指定的文件中;

单向加密除了 openssl dgst 工具还有: md5sum,sha1sum,sha224sum,sha256sum ,sha384sum,sha512sum

使用案例:

  • 生成指定文件的特征码
[root@localhost ~]# openssl dgst -md5 /tmp/fstab 
MD5(/tmp/fstab)= ef7b65e9d3200487dc06427934ce5c2d

[root@localhost ~]# md5sum /tmp/fstab 
ef7b65e9d3200487dc06427934ce5c2d  /tmp/fstab

[root@localhost ~]# echo hello,world | md5sum
757228086dc1e621e37bed30e0b73e17  -

[root@localhost ~]# echo hello,world | openssl dgst -md5
(stdin)= 757228086dc1e621e37bed30e0b73e1

3、加密密码

OpenSSL还支持生成密码的hash离散值,其子命令为passwd,语法如下:

openssl passwd [-crypt] [-1] [-apr1] [-salt string] [-in file] [-stdin] [-noverify] [-quiet] [-table] {password}

常用选项为:

-salt STRING:添加随机数;
-in FILE:对输入的文件内容进行加密;
-stdin:对标准输入的内容进行加密;

使用案例:

  • 生成密码的hash值
[root@localhost ~]# openssl passwd -1 -salt 123456 PASSWORD
$1$123456$KP0rRo6agiZOiJz8GMOd00

4、生成随机数

openssl命令也支持生成随机数,其子命令为rand,对应的语法为:

openssl rand [-out file] [-rand file(s)] [-base64] [-hex] num

常用选项有:

-base64:以base64编码格式输出;
-hex:使用十六进制编码格式;
-out FILE:将生成的内容保存在指定的文件中;

使用案例:

[root@localhost ~]# openssl rand  -base64  10
d0etSF7CA13hhg==

5、生成密钥对

利用openssl命令的子命令genrsa生成私钥,然后再使用子命令rsa私钥中提取公钥。
genrsa的语法如下:

openssl genrsa [-out filename] [-passout arg] [-des] [-des3] [-idea] [-f4] [-3] [-rand file(s)] [-engine id] [numbits]
常用选项:
-out FILENAME:将生成的私钥保存至指定的文件中;
[-des] [-des3] [-idea]:指定加密算法;
numbits:指明生成的私钥大小,默认是512;

通常来说秘钥文件的权限一般只能由管理员访问,因此可以结合umask命令来设置生成的密钥文件的权限,如:

[root@localhost ~]# (umask 077;openssl genrsa -out CA.key 4096)
Generating RSA private key, 4096 bit long modulus
.........................................................................................................................................++
.................................................................++
e is 65537 (0x10001)
[root@localhost ~]# ll CA.key 
-rw-------. 1 root root 3243 Feb  2 06:33 CA.key

而随后可利用rsa子命令生成的私钥文件中提取公钥,rsa子命令的语法为:

openssl rsa [-inform PEM|NET|DER] [-outform PEM|NET|DER] [-in filename] [-passin arg] [-out filename] [-passout arg] [-sgckey] [-des] [-des3] [-idea] [-text] [-noout] [-modulus] [-check] [-pubin] [-pubout] [-engine id]

常用选项为:
-in FILENAME:指明私钥文件的存放路径;
-out FILENAME:指明将公钥的保存路径;
-pubout:根据提供的私钥,从中提取出公钥;

如:

[root@localhost ~]# openssl rsa -pubout -in CA.key 
writing RSA key
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0r92sttB5yUOI3nE2nvj
PeTZaKkFw2f4cVy8x615afGDhw/XvfWqd2X3BqUy9pPyVoYLOrO0fvGWtx0zVy76
HZ/N3vkUdmzQlJahwKl+K2rVYl2U7fw+qO1UHzrvnNqe6p10KURwAsD1nhuRf/ra
SlxUuOPLNjyu5QeSjtoMuYbhk72M+ht+vNuZI8i2e9B6t6HzoHvnmxldjj+4tQje
BCxeWwaerb8iWZ8KiNDGtqu1X20EevvJY7sp7RzzUPT4EKrXQ6BUyl+VeodHiHxp
l/8gVdlDEYIyurjBwNJDl3I+ug+MZwB0BaPSqNdbgcQbwdM/E6SiBIKU366XkZ39
uDneIZEaZIe12k3MlxqvXyLrsHc2V4jNdK+BNF0bU8pd8Z0wJ7B+Fl/k1+4fD5hS
WLOziix36WrqWzgSgOAV4oEwZjLfBTWIPEcDLUO2LhrhHv4S9APi4FAIslu8QlHv
dkzHaG0e6zolsIAHa1wClTVwFFfmABmo2axpc3IAu9EQA4lLJwK5MiDlANHJBTY7
HXlAOGADgJXY3euiUB4oQ/WPcP2XPTmRQcYoey3hRETPbJd6heM6Rfx9TyCxjxeo
xStmZmhHKZZek+h14Q/hmaK946SkPcbbszL1WzK/STwpceDgnijMgStq6fIippLb
zaQiGXIq0SE8FGuYnCTYJPMCAwEAAQ==
-----END PUBLIC KEY-----

6、创建CA和申请证书

在使用OpenSSL命令创建证书前,可查看配置文件/etc/pki/tls/openss.conf文件,查看该文件定义了的证书存放位置及名称。
1)创建自签证书
首先为CA提供所需的目录及文件,并指明证书的开始编号:

# mkdir -pv /etc/pki/CA/{certs,crl,newcerts}
# touch /etc/pki/CA/{serial,index.txt}
# echo 01 > /etc/pki/CA/serial

随后生成私钥,注意私钥的文件名及其存放的位置,需与配置文件中相匹配:

[root@localhost ~]# (umask 077;openssl genrsa -out /etc/pki/CA/private/CAkey.pem 4096)
Generating RSA private key, 4096 bit long modulus
..............................++
.........................................................++
e is 65537 (0x10001)
[root@localhost ~]# ll /etc/pki/CA/private/CAkey.pem 
-rw-------. 1 root root 3243 Feb  2 07:10 /etc/pki/CA/private/CAkey.pem

最后创建自签证书:

[root@localhost CA]# openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem  -out /etc/pki/CA/cacert.pem -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) []:guangdong
Locality Name (eg, city) [Default City]:shenzhen  
Organization Name (eg, company) [Default Company Ltd]:magedu
Organizational Unit Name (eg, section) []:ops
Common Name (eg, your name or your server's hostname) []:ca.magedu.com
Email Address []:
[root@localhost CA]# 
[root@localhost CA]# 
[root@localhost CA]# ll 
total 20
-rw-r--r--. 1 root root 2025 Apr 17 02:14 cacert.pem
drwxr-xr-x. 2 root root 4096 May  9  2016 certs
drwxr-xr-x. 2 root root 4096 May  9  2016 crl
drwxr-xr-x. 2 root root 4096 May  9  2016 newcerts
drwx------. 2 root root 4096 Apr 17 02:12 private

其中命令openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out /etc/pki/CA/cacert.pem -days 3650用到子命令为req,其为证书请求及生成的工具,用到的选项解释为:

-new:表示生成一个新的证书签署请求;
-x509:专用于生成CA自签证书;
-key:指定生成证书用到的私钥文件;
-out FILNAME:指定生成的证书的保存路径;
-days:指定证书的有效期限,单位为day,默认是365天;

2)颁发证书
通常来说在CA签署颁发证书需要进行以下步骤:

  • 在需要使用证书的主机上生成私钥(私钥文件位置无限制)
[root@localhost ~]# (umask;openssl genrsa -out httpd.key 4096)
0022
Generating RSA private key, 4096 bit long modulus
...................................................................................................................................................................................................++
............................................................++
e is 65537 (0x10001)
  • 生成证书签署请求;
[root@localhost ~]# 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) []:guangdong
Locality Name (eg, city) [Default City]:shenzhen
Organization Name (eg, company) [Default Company Ltd]:magedu
Organizational Unit Name (eg, section) []:ops
Common Name (eg, your name or your server's hostname) []:web.magedu.com
Email Address []:

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

  • 通过可靠的方式将证书签署请求发送给CA主机;
  • 在CA服务器上签署证书后颁发证书
[root@localhost ~]# openssl ca -in httpd.csr -out /etc/pki/CA/certs/httpd.crt -days 365
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: Apr 16 18:31:12 2018 GMT
            Not After : Apr 16 18:31:12 2019 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = guangdong
            organizationName          = magedu
            organizationalUnitName    = ops
            commonName                = web.magedu.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                D2:A2:81:85:70:1B:12:A2:06:7E:F6:FB:32:7B:56:3B:7B:CB:A2:B2
            X509v3 Authority Key Identifier: 
                keyid:43:AE:6C:A2:6F:6E:E4:E1:C3:45:3E:1D:74:E6:94:89:50:25:0C:0A

Certificate is to be certified until Apr 16 18:31:12 2019 GMT (365 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

上述命令用到了openssl命令的子命令CA,用于在CA服务器上签署或吊销证书。

  • 查看证书信息:
[root@localhost ~]# openssl x509 -in /etc/pki/CA/certs/httpd.crt -noout -serial -dates -subject
serial=01
notBefore=Apr 16 18:31:12 2018 GMT
notAfter=Apr 16 18:31:12 2019 GMT
subject= /C=CN/ST=guangdong/O=magedu/OU=ops/CN=web.magedu.com

上述查看证书使用了openssl命令的子命令x509,其选项解释为:

-noout:不输出加密的证书内容;
-serial:输出证书序列号;
-dates:显示证书有效期的开始和终止时间;
-subject:输出证书的subject;

3)吊销证书
吊销证书的步骤通常为:

  • 在使用证书的主机上获取要吊销的证书的serial和subject信息(使用查看证书的命令)
  • 根据客户提交的serial和subject信息,对比本机数据库index.txt中存储的是否一致
  • 如一致,则执行吊销证书的操作;
[root@localhost ~]# openssl ca -revoke /etc/pki/CA/newcerts/01.pem 
Using configuration from /etc/pki/tls/openssl.cnf
Revoking Certificate 01.
Data Base Updated
  • 生成吊销证书的吊销编号(第一次吊销证书时执行)
[root@localhost ~]# echo 01 > /etc/pki/CA/crlnumber
[root@localhost ~]# cat /etc/pki/CA/crlnumber
01
  • 更新证书吊销列表
[root@localhost ~]# openssl ca -gencrl -out /etc/pki/CA/crl/ca.crl
Using configuration from /etc/pki/tls/openssl.cnf

-gencrl选项为根据/etc/pki/CA/index.txt文件中的信息生成crl文件。

  • 查看crl文件
[root@localhost ~]# openssl crl -in /etc/pki/CA/crl/ca.crl -noout -text
Certificate Revocation List (CRL):
        Version 2 (0x1)
    Signature Algorithm: sha1WithRSAEncryption
        Issuer: /C=CN/ST=guangdong/L=shenzhen/O=magedu/OU=ops/CN=ca.magedu.com
        Last Update: Apr 16 18:54:35 2018 GMT
        Next Update: May 16 18:54:35 2018 GMT
        CRL extensions:
            X509v3 CRL Number: 
                1
Revoked Certificates:
    Serial Number: 01                 #吊销的证书serial
        Revocation Date: Apr 16 18:51:24 2018 GMT
    Signature Algorithm: sha1WithRSAEncryption
.....

推荐:

C/C++Linux服务器开发/高级架构师群:960994558 群内提供一些免费的C/C++Linux服务器开发/高级架构师学习资料资料包括C/C++,Linux,golang技术,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK,ffmpeg等)
在这里插入图片描述

C/C++Linux服务器开发/高级架构师 系统学习地址

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值