介紹
密碼學標準和互聯網協議一樣,是一種大家都遵守的約定和標準,比如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具體查看。
(x)openssl子命令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 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
示例二:使用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的使用。
(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密鑰去除口令保護(去掉-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.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具體查看。
(x)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 [:] or [: ] or param: -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.pem,然后根據私鑰直接生成一個自簽根證書ca.cer openssl genrsa -out ca.pem 2048 openssl req -new -x509 -days 365 -key ca.pem -subj "/C=CN/ST=GD/L=SZ/O=Acme, Inc./CN=Acme 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或其他一些應用中使用的話就需要注意了。
(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,然后使用自簽名根證書ca.cer及其私鑰ca.pem為其簽名生成簽名證書server.cer openssl req -newkey rsa:2048 -nodes -keyout server.pem -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.cer -CAkey ca.pem -CAcreateserial -out server.cer
雜項
(1)openssl子命令rand用于生成偽隨機數
// 生成3個字節的隨機數 openssl rand -hex 3 注意:由于生成是隨機的字節,因此如果不通過-base64或-hex編碼的話輸出會顯示亂碼。
(2)openssl子命令passwd用于生成Linux用戶賬戶的密碼格式
// 對明文密碼進行加密處理 openssl passwd 12345 // 使用鹽值進行密碼加密(默認鹽值不固定,導致同一條命令每次執行都會產生不同的結果) openssl passwd -salt 'z' 12345
(3)openssl子命令verify用于驗證授權機構頒發的證書
openssl verify cert.pem // 輸出如下,則表示:驗證成功 OK // 輸出如下,則表示:證書過期,通常證書都是有有效期的,一般是一年 error 10 at 0 depth lookup:certificate has expired // 輸出如下,則表示:自簽名證書 error 18 at 0 depth lookup:self signed certificate
(4) openssl子命令s_server和s_client的使用
// 運行一個TLS服務端 openssl s_server -cert mycert.pem -www -accept 4433 // 向TLS服務端發起連接 openssl s_client -connect remote.host:4433
鏈接:https://www.cnblogs.com/kqdssheng/p/17945857
-
互聯網
+關注
關注
54文章
11167瀏覽量
103467 -
Linux
+關注
關注
87文章
11320瀏覽量
209842 -
命令
+關注
關注
5文章
688瀏覽量
22055
原文標題:Linux之OpenSSL命令指南
文章出處:【微信號:magedu-Linux,微信公眾號:馬哥Linux運維】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
相關推薦
評論