尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

OpenSSL 命令总结

OpenSSL 命令总结 疑今者察之古不知来者视之往。导航介绍对称加密公钥加密信息摘要数字证书杂项介绍密码学标准和互联网协议一样是一种大家都遵守的约定和标准比如PKCS#中规定了 RSA 秘钥是怎么生成的、公私钥的格式 等内容x509标准规定了证书的格式等。 命令行OpenSSL 本质就是一个工具集它按照主流的密码学标准实现了常用的对称加密算法、非对称加密算法、摘要算法、证书的生成/签名/验签等功能。$ openssl --help help: // openssl所有子命令 Standard commands asn1parse ca ciphers cmp cms crl crl2pkcs7 dgst dhparam dsa dsaparam ec ecparam enc engine errstr fipsinstall gendsa genpkey genrsa help info kdf list mac nseq ocsp passwd pkcs12 pkcs7 pkcs8 pkey pkeyparam pkeyutl prime rand rehash req rsa rsautl s_client s_server s_time sess_id smime speed spkac srp storeutl ts verify version x509 // openssl支持的摘要算法 Message Digest commands (see the dgst command for more details) blake2b512 blake2s256 md4 md5 rmd160 sha1 sha224 sha256 sha3-224 sha3-256 sha3-384 sha3-512 sha384 sha512 sha512-224 sha512-256 shake128 shake256 sm3 // openssl支持的对称加密算法 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 aria-128-cbc aria-128-cfb aria-128-cfb1 aria-128-cfb8 aria-128-ctr aria-128-ecb aria-128-ofb aria-192-cbc aria-192-cfb aria-192-cfb1 aria-192-cfb8 aria-192-ctr aria-192-ecb aria-192-ofb aria-256-cbc aria-256-cfb aria-256-cfb1 aria-256-cfb8 aria-256-ctr aria-256-ecb aria-256-ofb 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 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 sm4-cbc sm4-cfb sm4-ctr sm4-ecb sm4-ofb对称加密对称密钥算法在加密和解密时使用相同的密钥进行处理这类算法众多可通过openssl list -cipher-commands具体查看。xopenssl子命令enc为对称加解密工具。$ 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 Dont 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示例二使用base64加密算法加密字符串// 对字符串进行base64编码 echo -n 12345 | openssl enc -e -base64 -in - // 对字符串进行base64解码 echo MTIzNDU | openssl enc -d -base64 -in - 注意字符串编码时如果echo不加-n则会在字符串结尾添加一个换行符那么换行符也会一块编码。示例三加密文件并将密文输出为base64格式// 对加密后的数据进行base64编码(-a或-base64) openssl enc -aes-256-cbc -a -salt -in file.txt -out file.enc // 解密base64格式的加密数据 openssl enc -d -aes-256-cbc -a -in file.enc公钥加密公钥密钥算法在加密和解密时分别使用不同的密钥进行处理一般 公钥加密私钥解密而签名则相反私钥加密公钥解密这类算法目前只支持DH算法、RSA算法、DSA算法和椭圆曲线算法EC。DH算法一般用于密钥交换。RSA算法可用于密钥交换、数字签名及数据加密。DSA算法一般只用于数字签名。此处只重点介绍RSA相关指令genrsa、rsa、rsautl的使用。1openssl子命令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 -verbose2openssl子命令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 Dont 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 Dont 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密钥去除口令保护(去掉-passin选项亦可只是会询问密码) 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.pem3openssl子命令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具体查看。xopenssl子命令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根的私钥对另一个第三方公司的公钥证书即证书请求包含公司信息、网址、自生成的公钥进行签名来提升第三方公钥证书的可信度。1openssl子命令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 CAs) -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 keyvalue 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 Dont encrypt private keys -nodes Dont 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 /CAU/STSome-State/OInternet // 快速生成证书请求跳过了私钥加密请求及个人信息问答环节。 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可以拿来给其他证书请求文件做证书签名即证书颁发但是不能用来当作 HTTPS 的证书使用因为 Web Server 只认服务器证书类型不认根证书类型。// 首先生成一个私钥ca.pem然后根据私钥直接生成一个自签根证书ca.cer openssl genrsa -out ca.pem 2048 openssl req -new -x509 -days 365 -key ca.pem -subj /CCN/STGD/LSZ/OAcme, Inc./CNAcme Root CA -out ca.cer // 自动生成一个自签证书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 注意命令中的后缀pem、csr、cer只是为了便于理解文件的类型在命令行中使用可以是任意值。但在windows或其他一些应用中使用的话就需要注意了。2openssl子命令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示例一使用自签根证书为证书请求文件签名即生成 HTTPS 可用的证书注证书生成网站ssleye、bkssl// 生成请求文件server.csr然后使用自签名根证书ca.cer及其私钥ca.pem为其签名生成签名证书server.cer openssl req -newkey rsa:2048 -nodes -keyout server.pem -subj /CCN/STGD/LSZ/OAcme, Inc./CNlocalhost -out server.csr openssl x509 -sha256 -req -days 365 -in server.csr -CA ca.cer -CAkey ca.pem -CAcreateserial -out server.cer杂项1openssl子命令rand用于生成伪随机数// 生成3个字节的随机数 openssl rand -hex 3 注意由于生成是随机的字节因此如果不通过-base64或-hex编码的话输出会显示乱码。2openssl子命令passwd用于生成Linux用户账户的密码格式// 对明文密码进行加密处理 openssl passwd 12345 // 使用盐值进行密码加密默认盐值不固定导致同一条命令每次执行都会产生不同的结果 openssl passwd -salt z 123453openssl子命令verify用于验证授权机构颁发的证书openssl verify cert.pem // 输出如下则表示验证成功 OK // 输出如下则表示证书过期通常证书都是有有效期的一般是一年 error 10 at 0 depth lookup:certificate has expired // 输出如下则表示自签名证书 error 18 at 0 depth lookup:self signed certificate4 openssl子命令s_server和s_client的使用// 运行一个TLS服务端 openssl s_server -cert mycert.pem -www -accept 4433 // 向TLS服务端发起连接 openssl s_client -connect remote.host:44335参考文档密码学基础使用OpenSSL证书操作详解OpenSSL 中文手册《图解密码技术》读后总结OpenSSL示例我的博客园
返回列表