插件窝 干货文章 Linux下OpenSSL命令行工具怎么用

Linux下OpenSSL命令行工具怎么用

OpenSSL 证书 bash 加密 495    来源:    2025-05-08

OpenSSL 是一个功能强大的开源加密工具包,提供了丰富的命令行工具用于加密、证书管理、SSL/TLS 测试等。以下是最常用的 OpenSSL 命令分类整理:


一、证书操作

1. 查看证书信息

openssl x509 -in certificate.crt -text -noout  # 查看证书内容
openssl x509 -in cert.pem -issuer -subject -dates -noout  # 查看颁发者、主题、有效期

2. 证书格式转换

openssl x509 -in cert.crt -out cert.pem -outform PEM  # CRT转PEM
openssl pkcs12 -in cert.pfx -out cert.pem -nodes      # PFX转PEM(含私钥)

3. 生成自签名证书

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes
# 交互式输入信息生成证书

二、密钥操作

1. 生成密钥

openssl genrsa -out private.key 2048          # 生成RSA私钥
openssl ecparam -genkey -name secp256k1 -out ec.key  # 生成ECC私钥

2. 提取公钥

openssl rsa -in private.key -pubout -out public.key

3. 检查密钥

openssl rsa -in private.key -check -noout

三、加密/解密文件

1. 对称加密(AES为例)

openssl enc -aes-256-cbc -salt -in file.txt -out file.enc  # 加密
openssl enc -d -aes-256-cbc -in file.enc -out file.txt     # 解密

2. 非对称加密

openssl rsautl -encrypt -inkey public.key -pubin -in data.txt -out data.enc  # 公钥加密
openssl rsautl -decrypt -inkey private.key -in data.enc -out data.txt        # 私钥解密

四、CSR(证书签名请求)

1. 生成CSR

openssl req -new -key private.key -out request.csr  # 使用现有私钥
openssl req -new -newkey rsa:2048 -nodes -keyout server.key -out server.csr  # 新建私钥+CSR

2. 查看CSR

openssl req -in request.csr -text -noout

五、SSL/TLS 测试

1. 测试服务器证书

openssl s_client -connect example.com:443 -showcerts  # 获取服务器证书链
openssl s_client -connect example.com:443 -tls1_2     # 指定TLS版本

2. 检查证书有效期

openssl s_client -connect example.com:443 2>/dev/null | openssl x509 -noout -dates

六、摘要与签名

1. 生成哈希摘要

openssl dgst -sha256 file.txt          # SHA256哈希
openssl sha256 -r file.txt             # 简写形式

2. 数字签名

openssl dgst -sha256 -sign private.key -out signature.bin file.txt  # 签名
openssl dgst -sha256 -verify public.key -signature signature.bin file.txt  # 验证

七、PKCS#12 操作

openssl pkcs12 -export -out bundle.p12 -inkey private.key -in cert.crt  # 生成PKCS12文件
openssl pkcs12 -in bundle.p12 -info -nodes  # 查看PKCS12内容(含私钥)

常用参数说明

  • -in:输入文件
  • -out:输出文件
  • -nodes:不加密私钥(无密码)
  • -noout:不输出编码内容
  • -text:以文本形式显示内容

注意事项

  1. 生产环境务必使用强密码保护私钥。
  2. ECC密钥推荐使用 secp384r1 或更高安全曲线。
  3. 使用 -rand-writerand 增强随机性(如:-rand /dev/urandom)。

如果需要更具体的场景示例,可以告诉我您的具体需求(如HTTPS证书生成、双向SSL配置等)。