Java教程

OpenSSL命令总结

本文主要是介绍OpenSSL命令总结,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

疑今者察之古,不知来者视之往。


导航

  • 介绍

  • 对称加密

  • 公钥加密

  • 信息摘要

  • 数字证书

  • 杂项


介绍

密码学标准和互联网协议一样,是一种大家都遵守的约定和标准,比如PKCS#1中规定了 RSA 秘钥是怎么生成的、公私钥的格式 等内容,x509标准规定了证书的格式等。
    OpenSSL 本质就是一个工具集,按照主流的密码学标准实现了常用的加密算法,证书的生成、签名、验签等功能。


对称加密

对称密钥算法在加密和解密时使用相同的密钥进行处理,这类算法众多可通过 openssl list -cipher-commands 具体查看。

(1)openssl子命令enc为对称加解密工具,还可以进行base64编码转换。
$ openssl enc --help
Usage: enc [options]

General options:
 -help               Display this summary
 -list               List ciphers
 -ciphers            Alias for -list
 -e                  Encrypt
 -d                  Decrypt
 -p                  Print the iv/key
 -P                  Print the iv/key and exit
 -engine val         Use engine, possibly a hardware device

Input options:
 -in infile          Input file
 -k val              Passphrase
 -kfile infile       Read passphrase from file

Output options:
 -out outfile        Output file
 -pass val           Passphrase source
 -v                  Verbose output
 -a                  Base64 encode/decode, depending on encryption flag
 -base64             Same as option -a
 -A                  Used with -[base64|a] to specify base64 buffer as a single line

Encryption options:
 -nopad              Disable standard block padding
 -salt               Use salt in the KDF (default)
 -nosalt             Do not use salt in the KDF
 -debug              Print debug info
 -bufsize val        Buffer size
 -K val              Raw key, in hex
 -S val              Salt, in hex
 -iv val             IV in hex
 -md val             Use specified digest to create a key from the passphrase
 -iter +int          Specify the iteration count and force use of PBKDF2
 -pbkdf2             Use password-based key derivation function 2
 -none               Don't encrypt
 -*                  Any supported cipher

Random state options:
 -rand val           Load the given file(s) into the random number generator
 -writerand outfile  Write random data to the specified file

Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms

示例一:使用一种加密算法加密文件

// 通过aes-128-cbc对称密钥算法对文件test.txt进行加密,共享密钥是pass,输出文件是test-aes-enc.txt。
openssl enc -e -aes-128-cbc -in test.txt -k pass -out test-aes-enc.txt -v

// 通过aes-128-cbc对称密钥算法对文件test-aes-enc.txt进行解密,共享密钥是pass,输出文件是test-aes-dec.txt。
openssl enc -d -aes-128-cbc -in test-aes-enc.txt -k 123 -out test-aes-dec.txt -v

公钥加密

公钥密钥算法在加密和解密时分别使用不同的密钥进行处理(一般 公钥加密,私钥解密;而签名则相反:私钥加密,公钥解密),这类算法目前只支持DH算法、RSA算法、DSA算法和椭圆曲线算法(EC)。DH算法一般用于密钥交换。RSA算法可用于密钥交换、数字签名及数据加密。DSA算法一般只用于数字签名。此处只重点介绍RSA相关指令genrsa、rsa、rsautl的使用。

(1)openssl子命令genrsa主要用于生成RSA私钥。
$ openssl genrsa --help
Usage: genrsa [options] numbits

General options:
 -help               Display this summary
 -engine val         Use engine, possibly a hardware device

Input options:
 -3                  (deprecated) Use 3 for the E value
 -F4                 Use the Fermat number F4 (0x10001) for the E value
 -f4                 Use the Fermat number F4 (0x10001) for the E value

Output options:
 -out outfile        Output the key to specified file
 -passout val        Output file pass phrase source
 -primes +int        Specify number of primes
 -verbose            Verbose output
 -traditional        Use traditional format for private keys
 -*                  Encrypt the output with any supported cipher

Random state options:
 -rand val           Load the given file(s) into the random number generator
 -writerand outfile  Write random data to the specified file

Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms

Parameters:
 numbits             Size of key in bits

示例一:生成无密码且1024字节长度的私钥

openssl genrsa -out private.pem 1024 -verbose

示例二:生成带密码的私钥(genrsa生成的私钥格式都是PEM格式)--PEM、DER格式区别

// 使用aes-128-cbc对称加密算法对私钥进行加密处理,命令执行之后会提示输入密码
openssl genrsa -aes-128-cbc -out pri.pem -verbose
(2)openssl子命令rsa用于处理rsa密钥(提取公钥、管理保护密码)、格式转换和打印信息。
$ openssl rsa --help
Usage: rsa [options]

General options:
 -help               Display this summary
 -check              Verify key consistency
 -*                  Any supported cipher
 -engine val         Use engine, possibly a hardware device

Input options:
 -in val             Input file
 -inform format      Input format (DER/PEM/P12/ENGINE
 -pubin              Expect a public key in input file
 -RSAPublicKey_in    Input is an RSAPublicKey
 -passin val         Input file pass phrase source

Output options:
 -out outfile        Output file
 -outform format     Output format, one of DER PEM PVK
 -pubout             Output a public key
 -RSAPublicKey_out   Output is an RSAPublicKey
 -passout val        Output file pass phrase source
 -noout              Don't print key out
 -text               Print the key in text
 -modulus            Print the RSA key modulus
 -traditional        Use traditional format for private keys

PVK options:
 -pvk-strong         Enable 'Strong' PVK encoding level (default)
 -pvk-weak           Enable 'Weak' PVK encoding level
 -pvk-none           Don't enforce PVK encoding

Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms

示例一:私钥文件内容查看

openssl rsa -in priv.pem -text

示例二:给秘钥添加/去除/修改对称加密的密码(注意:此处涉及密码输入的格式均为pass:pass_value)

// 为RSA密钥增加口令保护
openssl rsa -in RSA.pem -des3 -passout pass:123456 -out E_RSA.pem

// 为RSA密钥去除口令保护
openssl rsa -in E_RSA.pem -passin pass:123456 -out P_RSA.pem

// 修改加密算法为aes128,口令是123456
openssl rsa -in RSA.pem -passin pass:123456 -aes128 -passout pass:123456 -out E_RSA.pem

示例三:密钥格式转换

// 把pem格式转化成der格式,使用outform指定der格式
openssl rsa -in RSA.pem -passin pass:123456 -des -passout pass:123456 -outform der -out rsa.der

注意:DER用二进制编码的证书,PEM用ASCLL(BASE64)编码的证书,一般默认都是PEM格式。

示例四:公钥提取

openssl rsa -in private.pem -pubout -out public.pem
(3)openssl子命令rsautl能够使用RSA算法签名、验证身份、加密/解密数据。
$ openssl rsautl --help
The command rsautl was deprecated in version 3.0. Use 'pkeyutl' instead.
Usage: rsautl [options]

General options:
 -help                    Display this summary
 -sign                    Sign with private key
 -verify                  Verify with public key
 -encrypt                 Encrypt with public key
 -decrypt                 Decrypt with private key
 -engine val              Use engine, possibly a hardware device

Input options:
 -in infile               Input file
 -inkey val               Input key
 -keyform PEM|DER|ENGINE  Private key format (ENGINE, other values ignored)
 -pubin                   Input is an RSA public
 -certin                  Input is a cert carrying an RSA public key
 -rev                     Reverse the order of the input buffer
 -passin val              Input file pass phrase source

Output options:
 -out outfile             Output file
 -raw                     Use no padding
 -pkcs                    Use PKCS#1 v1.5 padding (default)
 -x931                    Use ANSI X9.31 padding
 -oaep                    Use PKCS#1 OAEP
 -asn1parse               Run output through asn1parse; useful with -verify
 -hexdump                 Hex dump output

Random state options:
 -rand val                Load the given file(s) into the random number generator
 -writerand outfile       Write random data to the specified file

Provider options:
 -provider-path val       Provider load path (must be before 'provider' argument if required)
 -provider val            Provider to load (can be specified multiple times)
 -propquery val           Property query used when fetching algorithms

示例一:使用公私钥加解密文件

// 用公钥加密文件
openssl rsautl -encrypt -in plain.text -inkey public.pem -out encrypt.text 
// 用私钥解密文件
openssl rsautl -decrypt -in encrypt.text -inkey private.pem -out replain.text

示例二:使用公私钥签名/验签文件(此处的签名过程是针对文件的,故不涉及hash计算步骤)

// 用私钥签名
openssl rsautl -sign -in plain.text -inkey private.pem -out signed.text
// 用公钥验签
openssl rsautl -verify -in signed.text -pubin -inkey public.pem -out verify.text

信息摘要

信息摘要算法是将任意长度的数据转换成固定长度的字符串的过程,它通常用于验证数据的完整性和一致性,这类算法可通过命令 openssl list -digest-commands 具体查看。

(1)openssl子命令dgst为信息摘要计算工具。
$ openssl dgst --help
Usage: dgst [options] [file...]

General options:
 -help               Display this summary
 -list               List digests
 -engine val         Use engine e, possibly a hardware device
 -engine_impl        Also use engine given by -engine for digest operations
 -passin val         Input file pass phrase source

Output options:
 -c                  Print the digest with separating colons
 -r                  Print the digest in coreutils format
 -out outfile        Output to filename rather than stdout
 -keyform format     Key file format (ENGINE, other values ignored)
 -hex                Print as hex dump
 -binary             Print in binary form
 -xoflen +int        Output length for XOF algorithms
 -d                  Print debug info
 -debug              Print debug info

Signing options:
 -sign val           Sign digest using private key
 -verify val         Verify a signature using public key
 -prverify val       Verify a signature using private key
 -sigopt val         Signature parameter in n:v form
 -signature infile   File with signature to verify
 -hmac val           Create hashed MAC with key
 -mac val            Create MAC (not necessarily HMAC)
 -macopt val         MAC algorithm parameters in n:v form or key
 -*                  Any supported digest
 -fips-fingerprint   Compute HMAC with the key used in OpenSSL-FIPS fingerprint

Random state options:
 -rand val           Load the given file(s) into the random number generator
 -writerand outfile  Write random data to the specified file

Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms

Parameters:
 file                Files to digest (optional; default is stdin)

示例一:计算文件摘要

// 计算文件的md5值
openssl dgst -md5 test.txt

示例二:文件签名及验签(此处的签名是针对文件的hash值进行的,故一定会经历hash计算步骤)

// 使用private.pem私钥对文件plain.txt的哈希值进行签名并输出到test.text文件
openssl dgst -sign private.pem  -out test.text plain.text
// 使用public.pem公钥对签名文件进行验签
openssl dgst -verify public.pem -signature test.text plain.text

数字证书

数字证书就是用一个权威的私钥(一般是CA根的私钥)对另一个第三方公司的公钥证书(即证书请求,包含公司信息、网址、自生成的公钥)进行签名来提升第三方公钥证书的可信度。

(1)openssl子命令req用于生成和处理证书请求文件及证书
$ openssl req --help
Usage: req [options]

General options:
 -help                 Display this summary
 -engine val           Use engine, possibly a hardware device
 -keygen_engine val    Specify engine to be used for key generation operations
 -in infile            X.509 request input file (default stdin)
 -inform PEM|DER       Input format - DER or PEM
 -verify               Verify self-signature on the request

Certificate options:
 -new                  New request
 -config infile        Request template file
 -section val          Config section to use (default "req")
 -utf8                 Input characters are UTF8 (default ASCII)
 -nameopt val          Certificate subject/issuer name printing options
 -reqopt val           Various request text options
 -text                 Text form of request
 -x509                 Output an X.509 certificate structure instead of a cert request
 -CA infile            Issuer cert to use for signing a cert, implies -x509
 -CAkey val            Issuer private key to use with -CA; default is -CA arg
                       (Required by some CA's)
 -subj val             Set or modify subject of request or cert
 -subject              Print the subject of the output request or cert
 -multivalue-rdn       Deprecated; multi-valued RDNs support is always on.
 -days +int            Number of days cert is valid for
 -set_serial val       Serial number to use
 -copy_extensions val  copy extensions from request when using -x509
 -addext val           Additional cert extension key=value pair (may be given more than once)
 -extensions val       Cert extension section (override value in config file)
 -reqexts val          Request extension section (override value in config file)
 -precert              Add a poison extension to the generated cert (implies -new)

Keys and Signing options:
 -key val              Key for signing, and to include unless -in given
 -keyform format       Key file format (ENGINE, other values ignored)
 -pubkey               Output public key
 -keyout outfile       File to write private key to
 -passin val           Private key and certificate password source
 -passout val          Output file pass phrase source
 -newkey val           Generate new key with [<alg>:]<nbits> or <alg>[:<file>] or param:<file>
 -pkeyopt val          Public key options as opt:value
 -sigopt val           Signature parameter in n:v form
 -vfyopt val           Verification parameter in n:v form
 -*                    Any supported digest

Output options:
 -out outfile          Output file
 -outform PEM|DER      Output format - DER or PEM
 -batch                Do not ask anything during request generation
 -verbose              Verbose output
 -noenc                Don't encrypt private keys
 -nodes                Don't encrypt private keys; deprecated
 -noout                Do not output REQ
 -newhdr               Output "NEW" in the header lines
 -modulus              RSA modulus

Random state options:
 -rand val             Load the given file(s) into the random number generator
 -writerand outfile    Write random data to the specified file

Provider options:
 -provider-path val    Provider load path (must be before 'provider' argument if required)
 -provider val         Provider to load (can be specified multiple times)
 -propquery val        Property query used when fetching algorithms

示例一:生成一个证书请求

// 使用已有的private.pem私钥去生成一个证书请求。(有个人信息问答环节)
openssl req -new -key private.pem -out request.csr

// 使用自动生成的RSA私钥去生成一个证书请求文件。(有个人信息问答环节)
openssl req -new -out request.csr

// 自动生成1024位且不加密并输出为RSA.pem的私钥,以及生成免问答的证书请求client.csr。
openssl req -new -newkey rsa:1024 -nodes -out client.csr -keyout RSA.pem -subj /C=AU/ST=Some-State/O=Internet

// 快速生成证书请求,跳过了私钥加密请求及个人信息问答环节。
openssl req -new -nodes -out request.csr -batch

注意:生成证书请求文件虽然一定需要RSA私钥的参与,但请求文件的内容中并未嵌入私钥的信息,只有从私钥中提取出来的公钥。

示例二:查看证书请求文件的内容信息

openssl req -in request.csr -text

示例三:从证书请求文件中提取公钥

openssl req -in client.csr -pubkey -noout >pub.pem

示例四:生成自签名证书(即根CA,可以拿来给其他证书请求文件做证书签名,即证书颁发)

// 首先生成一个私钥ca.key,然后根据私钥直接生成一个自签根证书ca.crt
openssl genrsa -out ca.key 2048
openssl req -new -x509 -days 365 -key ca.key -subj "/C=CN/ST=GD/L=SZ/O=Acme, Inc./CN=Acme Root CA" -out ca.crt

// 自动生成一个自签证书mycert.cer和它的私钥prvi.pem(会询问个人信息)
openssl req -x509 -nodes -days 365 -sha256 -newkey rsa:2048 -keyout prvi.pem -out mycert.cer

// 快捷验证生成的证书是否有效,网址 https://localhost:4433。(-cert所需的文件是一个私钥与证书的结合体,即 cat prvi.pem mycert.cer > mycert.pem)
openssl s_server -cert mycert.pem -www -accept 4433
(2)openssl子命令X509命令是一个多用途的证书工具,它可以显示证书信息、转换证书格式、签名证书请求以及改变证书的信任设置等。
$ openssl x509 --help
Usage: x509 [options]

General options:
 -help                      Display this summary
 -in infile                 Certificate input, or CSR input file with -req (default stdin)
 -passin val                Private key and cert file pass-phrase source
 -new                       Generate a certificate from scratch
 -x509toreq                 Output a certification request (rather than a certificate)
 -req                       Input is a CSR file (rather than a certificate)
 -copy_extensions val       copy extensions when converting from CSR to x509 or vice versa
 -inform format             CSR input file format (DER or PEM) - default PEM
 -vfyopt val                CSR verification parameter in n:v form
 -key val                   Key for signing, and to include unless using -force_pubkey
 -signkey val               Same as -key
 -keyform PEM|DER|ENGINE    Key input format (ENGINE, other values ignored)
 -out outfile               Output file - default stdout
 -outform format            Output format (DER or PEM) - default PEM
 -nocert                    No cert output (except for requested printing)
 -noout                     No output (except for requested printing)

Certificate printing options:
 -text                      Print the certificate in text form
 -dateopt val               Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822.
 -certopt val               Various certificate text printing options
 -fingerprint               Print the certificate fingerprint
 -alias                     Print certificate alias
 -serial                    Print serial number value
 -startdate                 Print the notBefore field
 -enddate                   Print the notAfter field
 -dates                     Print both notBefore and notAfter fields
 -subject                   Print subject DN
 -issuer                    Print issuer DN
 -nameopt val               Certificate subject/issuer name printing options
 -email                     Print email address(es)
 -hash                      Synonym for -subject_hash (for backward compat)
 -subject_hash              Print subject hash value
 -subject_hash_old          Print old-style (MD5) subject hash value
 -issuer_hash               Print issuer hash value
 -issuer_hash_old           Print old-style (MD5) issuer hash value
 -ext val                   Restrict which X.509 extensions to print and/or copy
 -ocspid                    Print OCSP hash values for the subject name and public key
 -ocsp_uri                  Print OCSP Responder URL(s)
 -purpose                   Print out certificate purposes
 -pubkey                    Print the public key in PEM format
 -modulus                   Print the RSA key modulus

Certificate checking options:
 -checkend intmax           Check whether cert expires in the next arg seconds
                            Exit 1 (failure) if so, 0 if not
 -checkhost val             Check certificate matches host
 -checkemail val            Check certificate matches email
 -checkip val               Check certificate matches ipaddr

Certificate output options:
 -set_serial val            Serial number to use, overrides -CAserial
 -next_serial               Increment current certificate serial number
 -days int                  Number of days until newly generated certificate expires - default 30
 -preserve_dates            Preserve existing validity dates
 -subj val                  Set or override certificate subject (and issuer)
 -force_pubkey infile       Place the given key in new certificate
 -clrext                    Do not take over any extensions from the source certificate or request
 -extfile infile            Config file with X509V3 extensions to add
 -extensions val            Section of extfile to use - default: unnamed section
 -sigopt val                Signature parameter, in n:v form
 -badsig                    Corrupt last byte of certificate signature (for test)
 -*                         Any supported digest, used for signing and printing

Micro-CA options:
 -CA infile                 Use the given CA certificate, conflicts with -key
 -CAform PEM|DER            CA cert format (PEM/DER/P12); has no effect
 -CAkey val                 The corresponding CA key; default is -CA arg
 -CAkeyform PEM|DER|ENGINE  CA key format (ENGINE, other values ignored)
 -CAserial val              File that keeps track of CA-generated serial number
 -CAcreateserial            Create CA serial number file if it does not exist

Certificate trust output options:
 -trustout                  Mark certificate PEM output as trusted
 -setalias val              Set certificate alias (nickname)
 -clrtrust                  Clear all trusted purposes
 -addtrust val              Trust certificate for a given purpose
 -clrreject                 Clears all the prohibited or rejected uses of the certificate
 -addreject val             Reject certificate for a given purpose

Random state options:
 -rand val                  Load the given file(s) into the random number generator
 -writerand outfile         Write random data to the specified file
 -engine val                Use engine, possibly a hardware device

Provider options:
 -provider-path val         Provider load path (must be before 'provider' argument if required)
 -provider val              Provider to load (can be specified multiple times)
 -propquery val             Property query used when fetching algorithms

示例一:使用自签根证书为证书请求文件签名

// 生成请求文件server.csr,然后使用自签名证书为其签名
openssl req -newkey rsa:2048 -nodes -keyout server.key -subj "/C=CN/ST=GD/L=SZ/O=Acme, Inc./CN=localhost" -out server.csr
openssl x509 -sha256 -req  -days 365 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt

image


杂项

(1)openssl子命令rand用于生成伪随机数
$ openssl rand --help
Usage: rand [options] num

General options:
 -help               Display this summary
 -engine val         Use engine, possibly a hardware device

Output options:
 -out outfile        Output file
 -base64             Base64 encode output
 -hex                Hex encode output

Random state options:
 -rand val           Load the given file(s) into the random number generator
 -writerand outfile  Write random data to the specified file

Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms

Parameters:
 num                 Number of bytes to generate

示例一:生成随机值

// 生成3个字节的随机数
openssl rand -hex 3

注意:由于生成是随机的字节,因此如果不通过-base64或-hex编码的话输出会显示乱码。
(2)openssl子命令passwd用于生成Linux用户账户的密码格式
$ openssl passwd --help
Usage: passwd [options] [password]

General options:
 -help               Display this summary

Input options:
 -in infile          Read passwords from file
 -noverify           Never verify when reading password from terminal
 -stdin              Read passwords from stdin

Output options:
 -quiet              No warnings
 -table              Format output as table
 -reverse            Switch table columns

Cryptographic options:
 -salt val           Use provided salt
 -6                  SHA512-based password algorithm
 -5                  SHA256-based password algorithm
 -apr1               MD5-based password algorithm, Apache variant
 -1                  MD5-based password algorithm
 -aixmd5             AIX MD5-based password algorithm

Random state options:
 -rand val           Load the given file(s) into the random number generator
 -writerand outfile  Write random data to the specified file

Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms

Parameters:
 password            Password text to digest (optional)

示例一:对明文密码进行加密处理

// 基本用法
openssl passwd 12345

// 使用盐值进行密码加密(默认盐值不固定,导致同一条命令每次执行都会产生不同的结果)
openssl passwd -salt 'z' 12345
(3)参考文档
  • 密码学基础

  • 使用OpenSSL证书操作详解

  • OpenSSL 中文手册

  • 《图解密码技术》读后总结


这篇关于OpenSSL命令总结的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!