Linux常用命令-openssl

命令

openssl

描述

OpenSSL command line tool
OpenSSL命令行工具

用法

1
openssl command [ command_opts ] [ command_args ]

选项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
STANDARD COMMANDS
ca 证书颁发机构(CA)管理
ciphers Cipher Suite Description Determination.
dgst 消息摘要计算,生成校验码
enc 加解密字符串或文件
errstr 转换错误代码和错误信息
genrsa 生成RSA私钥
genpkey 生成私钥
pkeyparam 公钥算法管理
pkey 公钥和私钥管理
passwd 生成哈希密码
rand 生成伪随机字节
req X.509证书签名请求(CSR)管理
rsa RSA密钥管理
s_client SSL/TLS客户端
s_server SSL/TLS服务端
s_time SSL连接计时器
sess_id SSL会话数据管理
speed 算法速度测试
ts 时间戳授权工具(客户端/服务器)
verify X.509证书验证
version OpenSSL版本信息
x509 X.509证书数据管理
MESSAGE DIGEST COMMANDS
md5 MD5 Digest
sha1 SHA-1 Digest
sha256 SHA-256 Digest
sha512 SHA-512 Digest
ENCODING AND CIPHER COMMANDS
base64 Base64 Encoding
des des-cbc des-cfb des-ecb des-ede des-ede-cbc des-ede-cfb des-ede-ofb des-ofb
DES Cipher
des3 desx des-ede3 des-ede3-cbc des-ede3-cfb des-ede3-ofb
Triple-DES Cipher
PASS PHRASE ARGUMENTS
-passin and -passout 部分命令支持指定密码参数,支持以下密码格式
pass:password 指定密码,如pass:123456
env:var 指定环境变量,如env:dpass
file:pathname 指定密码文件,默认第一行是密码,如果同时指定-passin和-passout读取同一个文件,则默认第一行为输入密码,第二行为输出密码
stdin 从标准输入读取

其他man命令帮助,如man ca即查看openssl ca相关命令帮助
asn1parse(1), ca(1), config(5), crl(1), crl2pkcs7(1), dgst(1), dhparam(1), dsa(1),
dsaparam(1), enc(1), gendsa(1), genpkey(1), genrsa(1), nseq(1), openssl(1), sslpasswd(1),
pkcs12(1), pkcs7(1),pkcs8(1), sslrand(1), req(1), rsa(1), rsautl(1), s_client(1), s_server(1),
s_time(1), smime(1), spkac(1), verify(1), version(1), x509(1), crypto(3), ssl(3), x509v3_config(5)

相关子命令帮助
$ man ca
$ openssl ca -help
usage: ca args
-verbose - Talk alot while doing things
-config file - A config file
-name arg - The particular CA definition to use
-gencrl - Generate a new CRL
-crldays days - Days is when the next CRL is due
-crlhours hours - Hours is when the next CRL is due
-startdate YYMMDDHHMMSSZ - certificate validity notBefore
-enddate YYMMDDHHMMSSZ - certificate validity notAfter (overrides -days)
-days arg - number of days to certify the certificate for
-md arg - md to use, see openssl dgst -h for list
-policy arg - The CA 'policy' to support
-keyfile arg - private key file
-keyform arg - private key file format (PEM or ENGINE)
-key arg - key to decode the private key if it is encrypted
-cert file - The CA certificate
-selfsign - sign a certificate with the key associated with it
-in file - The input PEM encoded certificate request(s)
-out file - Where to put the output file(s)
-outdir dir - Where to put output certificates
-infiles .... - The last argument, requests to process
-spkac file - File contains DN and signed public key and challenge
-ss_cert file - File contains a self signed cert to sign
-preserveDN - Don't re-order the DN
-noemailDN - Don't add the EMAIL field into certificate' subject
-batch - Don't ask questions
-msie_hack - msie modifications to handle all those universal strings
-revoke file - Revoke a certificate (given in file)
-subj arg - Use arg instead of request's subject
-utf8 - input characters are UTF8 (default ASCII)
-multivalue-rdn - enable support for multivalued RDNs
-extensions .. - Extension section (override value in config file)
-extfile file - Configuration file with X509v3 extentions to add
-crlexts .. - CRL extension section (override value in config file)
-engine e - use engine e, possibly a hardware device.
-status serial - Shows certificate status given the serial number
-updatedb - Updates db for expired certificates

$ man ciphers
$ openssl ciphers -help
usage: ciphers args
-v - verbose mode, a textual listing of the SSL/TLS ciphers in OpenSSL
-V - even more verbose
-ssl3 - SSL3 mode
-tls1 - TLS1 mode

$ man dgst
$ openssl dgst -help
options are
-c to output the digest with separating colons
-r to output the digest in coreutils format
-d to output debug info
-hex output as hex dump
-binary output in binary form
-hmac arg set the HMAC key to arg
-non-fips-allow allow use of non FIPS digest
-sign file sign digest using private key in file
-verify file verify a signature using public key in file
-prverify file verify a signature using private key in file
-keyform arg key file format (PEM or ENGINE)
-out filename output to filename rather than stdout
-signature file signature to verify
-sigopt nm:v signature parameter
-hmac key create hashed MAC with key
-mac algorithm create MAC (not neccessarily HMAC)
-macopt nm:v MAC algorithm parameters or key
-engine e use engine e, possibly a hardware device.
-md4 to use the md4 message digest algorithm
-md5 to use the md5 message digest algorithm
-ripemd160 to use the ripemd160 message digest algorithm
-sha to use the sha message digest algorithm
-sha1 to use the sha1 message digest algorithm
-sha224 to use the sha224 message digest algorithm
-sha256 to use the sha256 message digest algorithm
-sha384 to use the sha384 message digest algorithm
-sha512 to use the sha512 message digest algorithm
-whirlpool to use the whirlpool message digest algorithm

$ man enc
$ openssl enc -help
options are
-in <file> input file
-out <file> output file
-pass <arg> pass phrase source
-e encrypt
-d decrypt
-a/-base64 base64 encode/decode, depending on encryption flag
-k passphrase is the next argument
-kfile passphrase is the first line of the file argument
-md the next argument is the md to use to create a key from a passphrase. See openssl dgst -h for list.
-salt use a salt in the key derivation routines. This is the default.
-S salt in hex is the next argument
-K/-iv key/iv in hex is the next argument
-[pP] print the iv/key (then exit if -P)
-bufsize <n> buffer size
-nopad disable standard block padding
-engine e use engine e, possibly a hardware device.
Cipher Types
-aes-128-cfb
-aes-128-ctr
-des
-des3
...

$ man genrsa
$ openssl genrsa --help
usage: genrsa [args] [numbits]
-des encrypt the generated key with DES in cbc mode
-des3 encrypt the generated key with DES in ede cbc mode (168 bit key)
-idea encrypt the generated key with IDEA in cbc mode
-seed encrypt PEM output with cbc seed
-aes128, -aes192, -aes256
encrypt PEM output with cbc aes
-camellia128, -camellia192, -camellia256
encrypt PEM output with cbc camellia
-out file output the key to 'file
-passout arg output file pass phrase source
-f4 use F4 (0x10001) for the E value
-3 use 3 for the E value
-engine e use engine e, possibly a hardware device.
-rand file:file:...
load the file (or the files in the directory) into
the random number generator

$ openssl genpkey -help
Usage: genpkey [options]
where options may be
-out file output file
-outform X output format (DER or PEM)
-pass arg output file pass phrase source
-<cipher> use cipher <cipher> to encrypt the key
-engine e use engine e, possibly a hardware device.
-paramfile file parameters file
-algorithm alg the public key algorithm
-pkeyopt opt:value set the public key algorithm option <opt>
to value <value>
-genparam generate parameters, not key
-text print the in text

$ openssl pkey -help
Usage pkey [options]
where options are
-in file input file
-inform X input format (DER or PEM)
-passin arg input file pass phrase source
-outform X output format (DER or PEM)
-out file output file
-passout arg output file pass phrase source
-engine e use engine e, possibly a hardware device.

$ man sslpasswd
$ openssl passwd -help
Usage: passwd [options] [passwords]
where options are
-crypt standard Unix password algorithm (default)
-1 MD5-based password algorithm
-apr1 MD5-based password algorithm, Apache variant
-salt string use provided salt
-in file read passwords from file
-stdin read passwords from stdin
-noverify never verify when reading password from terminal
-quiet no warnings
-table format output as table
-reverse switch table columns

$ openssl rand -help
Usage: rand [options] num
where options are
-out file - write to file
-engine e - use engine e, possibly a hardware device.
-rand file:file:... - seed PRNG from files
-base64 - base64 encode output
-hex - hex encode output

$ openssl req -help
req [options] <infile >outfile
where options are
-inform arg input format - DER or PEM
-outform arg output format - DER or PEM
-in arg input file
-out arg output file
-text text form of request
-pubkey output public key
-noout do not output REQ
-verify verify signature on REQ
-modulus RSA modulus
-nodes don't encrypt the output key
-engine e use engine e, possibly a hardware device
-subject output the request's subject
-passin private key password source
-key file use the private key contained in file
-keyform arg key file format
-keyout arg file to send the key to
-rand file:file:...
load the file (or the files in the directory) into
the random number generator
-newkey rsa:bits generate a new RSA key of 'bits' in size
-newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'
-newkey ec:file generate a new EC key, parameters taken from CA in 'file'
-[digest] Digest to sign with (see openssl dgst -h for list)
-config file request template file.
-subj arg set or modify request subject
-multivalue-rdn enable support for multivalued RDNs
-new new request.
-batch do not ask anything during request generation
-x509 output a x509 structure instead of a cert. req.
-days number of days a certificate generated by -x509 is valid for.
-set_serial serial number to use for a certificate generated by -x509.
-newhdr output "NEW" in the header lines
-asn1-kludge Output the 'request' in a format that is wrong but some CA's
have been reported as requiring
-extensions .. specify certificate extension section (override value in config file)
-reqexts .. specify request extension section (override value in config file)
-utf8 input characters are UTF8 (default ASCII)
-nameopt arg - various certificate name options
-reqopt arg - various request text options

$ openssl rsa -help
rsa [options] <infile >outfile
where options are
-inform arg input format - one of DER NET PEM
-outform arg output format - one of DER NET PEM
-in arg input file
-sgckey Use IIS SGC key format
-passin arg input file pass phrase source
-out arg output file
-passout arg output file pass phrase source
-des encrypt PEM output with cbc des
-des3 encrypt PEM output with ede cbc des using 168 bit key
-idea encrypt PEM output with cbc idea
-seed encrypt PEM output with cbc seed
-aes128, -aes192, -aes256
encrypt PEM output with cbc aes
-camellia128, -camellia192, -camellia256
encrypt PEM output with cbc camellia
-text print the key in text
-noout don't print key out
-modulus print the RSA key modulus
-check verify key consistency
-pubin expect a public key in input file
-pubout output a public key
-engine e use engine e, possibly a hardware device.

$ openssl s_client -help
usage: s_client args
-host host - use -connect instead
-port port - use -connect instead
-connect host:port - who to connect to (default is localhost:4433)
-verify_hostname host - check peer certificate matches "host"
-verify_email email - check peer certificate matches "email"
-verify_ip ipaddr - check peer certificate matches "ipaddr"
-verify arg - turn on peer certificate verification
-verify_return_error - return verification errors
-cert arg - certificate file to use, PEM format assumed
-certform arg - certificate format (PEM or DER) PEM default
-key arg - Private key file to use, in cert file if not specified but cert file is.
-keyform arg - key format (PEM or DER) PEM default
-pass arg - private key file pass phrase source
-CApath arg - PEM format directory of CA's
-CAfile arg - PEM format file of CA's
-trusted_first - Use trusted CA's first when building the trust chain
-no_alt_chains - only ever use the first certificate chain found
-reconnect - Drop and re-make the connection with the same Session-ID
-pause - sleep(1) after each read(2) and write(2) system call
-prexit - print session information even on connection failure
-showcerts - show all certificates in the chain
-debug - extra output
-msg - Show protocol messages
-nbio_test - more ssl protocol testing
-state - print the 'ssl' states
-nbio - Run with non-blocking IO
-crlf - convert LF from terminal into CRLF
-quiet - no s_client output
-ign_eof - ignore input eof (default when -quiet)
-no_ign_eof - don't ignore input eof
-psk_identity arg - PSK identity
-psk arg - PSK in hex (without 0x)
-ssl3 - just use SSLv3
-tls1_2 - just use TLSv1.2
-tls1_1 - just use TLSv1.1
-tls1 - just use TLSv1
-dtls1 - just use DTLSv1
-fallback_scsv - send TLS_FALLBACK_SCSV
-mtu - set the link layer MTU
-no_tls1_2/-no_tls1_1/-no_tls1/-no_ssl3/-no_ssl2 - turn off that protocol
-bugs - Switch on all SSL implementation bug workarounds
-cipher - preferred cipher to use, use the 'openssl ciphers'
command to see what is available
-starttls prot - use the STARTTLS command before starting TLS
for those protocols that support it, where
'prot' defines which one to assume. Currently,
only "smtp", "pop3", "imap", "ftp", "xmpp",
"xmpp-server", "irc", "postgres", "lmtp", "nntp",
"sieve" and "ldap" are supported.
-xmpphost host - Host to use with "-starttls xmpp[-server]"
-name host - Hostname to use for "-starttls lmtp" or "-starttls smtp"
-krb5svc arg - Kerberos service name
-engine id - Initialise and use the specified engine
-rand file:file:...
-sess_out arg - file to write SSL session to
-sess_in arg - file to read SSL session from
-servername host - Set TLS extension servername in ClientHello
-tlsextdebug - hex dump of all TLS extensions received
-status - request certificate status from server
-no_ticket - disable use of RFC4507bis session tickets
-serverinfo types - send empty ClientHello extensions (comma-separated numbers)
-curves arg - Elliptic curves to advertise (colon-separated list)
-sigalgs arg - Signature algorithms to support (colon-separated list)
-client_sigalgs arg - Signature algorithms to support for client
certificate authentication (colon-separated list)
-nextprotoneg arg - enable NPN extension, considering named protocols supported (comma-separated list)
-alpn arg - enable ALPN extension, considering named protocols supported (comma-separated list)
-legacy_renegotiation - enable use of legacy renegotiation (dangerous)
-use_srtp profiles - Offer SRTP key management with a colon-separated profile list
-keymatexport label - Export keying material using label
-keymatexportlen len - Export len bytes of keying material (default 20)

$ openssl s_server -help
usage: s_server [args ...]
-accept arg - port to accept on (default is 4433)
-verify_hostname host - check peer certificate matches "host"
-verify_email email - check peer certificate matches "email"
-verify_ip ipaddr - check peer certificate matches "ipaddr"
-context arg - set session ID context
-verify arg - turn on peer certificate verification
-Verify arg - turn on peer certificate verification, must have a cert.
-verify_return_error - return verification errors
-cert arg - certificate file to use
(default is server.pem)
-serverinfo arg - PEM serverinfo file for certificate
-auth - send and receive RFC 5878 TLS auth extensions and supplemental data
-auth_require_reneg - Do not send TLS auth extensions until renegotiation
-no_resumption_on_reneg - set SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION flag
-crl_check - check the peer certificate has not been revoked by its CA.
The CRL(s) are appended to the certificate file
-crl_check_all - check the peer certificate has not been revoked by its CA
or any other CRL in the CA chain. CRL(s) are appened to the
the certificate file.
-certform arg - certificate format (PEM or DER) PEM default
-key arg - Private Key file to use, in cert file if
not specified (default is server.pem)
-keyform arg - key format (PEM, DER or ENGINE) PEM default
-pass arg - private key file pass phrase source
-dcert arg - second certificate file to use (usually for DSA)
-dcertform x - second certificate format (PEM or DER) PEM default
-dkey arg - second private key file to use (usually for DSA)
-dkeyform arg - second key format (PEM, DER or ENGINE) PEM default
-dpass arg - second private key file pass phrase source
-dhparam arg - DH parameter file to use, in cert file if not specified
or a default set of parameters is used
-named_curve arg - Elliptic curve name to use for ephemeral ECDH keys.
Use "openssl ecparam -list_curves" for all names
(default is nistp256).
-nbio - Run with non-blocking IO
-nbio_test - test with the non-blocking test bio
-crlf - convert LF from terminal into CRLF
-debug - Print more output
-msg - Show protocol messages
-state - Print the SSL states
-CApath arg - PEM format directory of CA's
-CAfile arg - PEM format file of CA's
-trusted_first - Use trusted CA's first when building the trust chain
-no_alt_chains - only ever use the first certificate chain found
-nocert - Don't use any certificates (Anon-DH)
-cipher arg - play with 'openssl ciphers' to see what goes here
-serverpref - Use server's cipher preferences
-quiet - No server output
-no_tmp_rsa - Do not generate a tmp RSA key
-krb5svc arg - Kerberos service name
-keytab arg - Kerberos keytab filename
-psk_hint arg - PSK identity hint to use
-psk arg - PSK in hex (without 0x)
-ssl3 - Just talk SSLv3
-tls1_2 - Just talk TLSv1.2
-tls1_1 - Just talk TLSv1.1
-tls1 - Just talk TLSv1
-dtls1 - Just talk DTLSv1
-dtls1_2 - Just talk DTLSv1.2
-timeout - Enable timeouts
-mtu - Set link layer MTU
-chain - Read a certificate chain
-no_ssl2 - No-op, SSLv2 is always disabled
-no_ssl3 - Just disable SSLv3
-no_tls1 - Just disable TLSv1
-no_tls1_1 - Just disable TLSv1.1
-no_tls1_2 - Just disable TLSv1.2
-no_dhe - Disable ephemeral DH
-no_ecdhe - Disable ephemeral ECDH
-bugs - Turn on SSL bug compatibility
-hack - workaround for early Netscape code
-www - Respond to a 'GET /' with a status page
-WWW - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>
-HTTP - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>
with the assumption it contains a complete HTTP response.
-engine id - Initialise and use the specified engine
-id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'
-rand file:file:...
-servername host - servername for HostName TLS extension
-servername_fatal - on mismatch send fatal alert (default warning alert)
-cert2 arg - certificate file to use for servername
(default is server2.pem)
-key2 arg - Private Key file to use for servername, in cert file if
not specified (default is server2.pem)
-tlsextdebug - hex dump of all TLS extensions received
-no_ticket - disable use of RFC4507bis session tickets
-legacy_renegotiation - enable use of legacy renegotiation (dangerous)
-sigalgs arg - Signature algorithms to support (colon-separated list)
-client_sigalgs arg - Signature algorithms to support for client
certificate authentication (colon-separated list)
-nextprotoneg arg - set the advertised protocols for the NPN extension (comma-separated list)
-use_srtp profiles - Offer SRTP key management with a colon-separated profile list
-alpn arg - set the advertised protocols for the ALPN extension (comma-separated list)
-keymatexport label - Export keying material using label
-keymatexportlen len - Export len bytes of keying material (default 20)
-status - respond to certificate status requests
-status_verbose - enable status request verbose printout
-status_timeout n - status request responder timeout
-status_url URL - status request fallback URL

$ openssl s_time -help
usage: s_time <args>
-connect host:port - host:port to connect to (default is localhost:4433)
-nbio - Run with non-blocking IO
-ssl3 - Just use SSLv3
-bugs - Turn on SSL bug compatibility
-new - Just time new connections
-reuse - Just time connection reuse
-www page - Retrieve 'page' from the site
-time arg - max number of seconds to collect data, default 30
-verify arg - turn on peer certificate verification, arg == depth
-cert arg - certificate file to use, PEM format assumed
-key arg - RSA file to use, PEM format assumed, key is in cert file
file if not specified by this option
-CApath arg - PEM format directory of CA's
-CAfile arg - PEM format file of CA's
-trusted_first - Use trusted CA's first when building the trust chain
-cipher - preferred cipher to use, play with 'openssl ciphers'

$ openssl sess_id -help
usage: sess_id args
-inform arg - input format - default PEM (DER or PEM)
-outform arg - output format - default PEM
-in arg - input file - default stdin
-out arg - output file - default stdout
-text - print ssl session id details
-cert - output certificate
-noout - no CRL output
-context arg - set the session ID context

$ openssl speed -help
Available values:
md5 hmac sha1 sha256 sha512
rsa512 rsa1024 rsa2048 rsa4096
dsa512 dsa1024 dsa2048
ecdsap256 ecdsap384 ecdsap521 ecdsa
ecdhp256 ecdhp384 ecdhp521 ecdh
des aes rsa
Available options:
-elapsed measure time in real time instead of CPU user time.
-engine e use engine e, possibly a hardware device.
-evp e use EVP e.
-decrypt time decryption instead of encryption (only EVP).
-mr produce machine readable output.
-multi n run n benchmarks in parallel.

$ openssl x509 -help
usage: x509 args
-inform arg - input format - default PEM (one of DER, NET or PEM)
-outform arg - output format - default PEM (one of DER, NET or PEM)
-keyform arg - private key format - default PEM
-CAform arg - CA format - default PEM
-CAkeyform arg - CA key format - default PEM
-in arg - input file - default stdin
-out arg - output file - default stdout
-passin arg - private key password source
-serial - print serial number value
-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
-hash - synonym for -subject_hash
-subject - print subject DN
-issuer - print issuer DN
-email - print email address(es)
-startdate - notBefore field
-enddate - notAfter field
-purpose - print out certificate purposes
-dates - both Before and After dates
-modulus - print the RSA key modulus
-pubkey - output the public key
-fingerprint - print the certificate fingerprint
-alias - output certificate alias
-noout - no certificate output
-ocspid - print OCSP hash values for the subject name and public key
-ocsp_uri - print OCSP Responder URL(s)
-trustout - output a "trusted" certificate
-clrtrust - clear all trusted purposes
-clrreject - clear all rejected purposes
-addtrust arg - trust certificate for a given purpose
-addreject arg - reject certificate for a given purpose
-setalias arg - set certificate alias
-days arg - How long till expiry of a signed certificate - def 30 days
-checkend arg - check whether the cert expires in the next arg seconds
exit 1 if so, 0 if not
-signkey arg - self sign cert with arg
-x509toreq - output a certification request object
-req - input is a certificate request, sign and output.
-CA arg - set the CA certificate, must be PEM format.
-CAkey arg - set the CA key, must be PEM format
missing, it is assumed to be in the CA file.
-CAcreateserial - create serial number file if it does not exist
-CAserial arg - serial file
-set_serial - serial number to use
-text - print the certificate in text form
-C - print out C code forms
-<dgst> - digest to use, see openssl dgst -h output for list
-extfile - configuration file with X509V3 extensions to add
-extensions - section from config file with X509V3 extensions to add
-clrext - delete extensions before signing and input certificate
-nameopt arg - various certificate name options
-engine e - use engine e, possibly a hardware device.
-certopt arg - various certificate text options
-checkhost host - check certificate matches "host"
-checkemail email - check certificate matches "email"
-checkip ipaddr - check certificate matches "ipaddr"

注意

openssl默认配置文件路径,CentOS系统为/etc/pki/tls/openssl.cnf,Ubuntu系统为/etc/ssl/openssl.cnf

添加自签名CA证书到系统中,证书后缀为.crt
CentOS系统路径为/etc/pki/ca-trust/source/anchors/,更新命令为update-ca-trust
Ubuntu系统路径为/usr/local/share/ca-certificates/,更新命令为update-ca-certificates

建议保存证书使用Base64编码格式,而非二进制的DER编码格式

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
$ openssl version
OpenSSL 1.0.2k-fips 26 Jan 2017

# openssl配置文件中默认定义的目录和文件名如下
$ grep dir /etc/pki/tls/openssl.cnf
dir = /etc/pki/CA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crlnumber = $dir/crlnumber # the current crl number
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem # The private key

## 生成CA证书
# 生成CA私钥ca.key
$ openssl genrsa -out ca.key 2048
# 生成CA证书ca.crt
$ openssl req -x509 -new -key ca.key -out ca.crt -days 730 -subj "/C=CN/ST=BJ/O=a.com/CN=CA_default"
# 查看CA证书信息
$ openssl x509 -in ca.crt -noout -subject -dates

## 生成自签名证书
# 生成私钥cert.key
$ openssl genrsa -out cert.key 2048
# 推荐使用如下命令生成私钥
$ (umask 077;openssl genrsa -out cert.key 2048)
# 生成证书申请文件cert.req,以下指定为泛域名*.a.com
$ openssl req -new -out cert.req -key cert.key -subj "/C=CN/ST=BJ/O=a.com/CN=*.a.com"
# 生成自签名证书cert.crt,由如上CA机构签发
$ openssl x509 -req -in cert.req -out cert.crt -CAkey ca.key -CA ca.crt -days 730 -CAcreateserial -CAserial serial
# 查看自签名证书信息
$ openssl x509 -in cert.crt -noout -subject -dates

# 如果签发不同组织的域名则会出现报错提示,解决如下
The organizationName field needed to be the same in the
CA certificate (a.com) and the request (b.com)
# 修改配置文件
$ vim /etc/pki/tls/openssl.cnf
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
# 修改为
[ policy_match ]
countryName = optional
stateOrProvinceName = optional
organizationName = optional

# 生成校验码dgst
$ echo password | md5sum
286755fad04869ca523320acce0dc6a4 -
$ echo password | openssl md5
(stdin)= 286755fad04869ca523320acce0dc6a4
$ echo password | openssl dgst
(stdin)= 286755fad04869ca523320acce0dc6a4
$ echo password | openssl dgst -md5
(stdin)= 286755fad04869ca523320acce0dc6a4
$ echo password | openssl dgst -md5 -r
286755fad04869ca523320acce0dc6a4 *stdin
$ echo password | openssl dgst -md5 -c
(stdin)= 28:67:55:fa:d0:48:69:ca:52:33:20:ac:ce:0d:c6:a4
$ echo password | openssl dgst -md5 -r -out file
$ cat file
286755fad04869ca523320acce0dc6a4 *stdin
$ md5sum file
354aab42e50db2e4625dc082c2b2ac0b file
$ cat file | openssl dgst -md5
(stdin)= 354aab42e50db2e4625dc082c2b2ac0b
$ cat file | openssl dgst -md5 -r
354aab42e50db2e4625dc082c2b2ac0b *stdin
$ openssl dgst -md5 -r file
354aab42e50db2e4625dc082c2b2ac0b *file
# sha1校验码
$ sha1sum file
3ba40435e62ef3810ad9f0a6872820dacd259e04 file
$ openssl sha1 file
SHA1(file)= 3ba40435e62ef3810ad9f0a6872820dacd259e04
$ openssl sha1 -r file
3ba40435e62ef3810ad9f0a6872820dacd259e04 *file

# base64编码
$ echo password > file
$ cat file
password
$ base64 file
cGFzc3dvcmQK
$ openssl enc -in file -out file.enc -e -base64
$ cat file.enc
cGFzc3dvcmQK
$ openssl enc -in file.enc -out file.new -d -base64
$ cat file.new
password
# des3加密文件,加密后文件内容显示为乱码,建议同时添加-base64进行编码,避免查看时显示为乱码
$ echo password > file
# -e 加密, -des3 算法, -base64 编码格式, -salt 加盐, -k 指定密码, -in 原文件 -out 加密后文件
$ openssl enc -e -des3 -base64 -salt -k centos -in file -out file.des3
$ file file file.des3
file: ASCII text
file.des3: ASCII text
$ cat file file.des3
password
U2FsdGVkX19gRJmKQPCY/ncdVWF+yyOAw4xkS5AQSCM=
$ openssl enc -d -des3 -base64 -salt -k centos -in file.des3 -out file.out
$ cat file.out
password
$ cat file
password


# 生成密钥,无加密密码
$ openssl genrsa -out key.pem 2048
# 生成加密密钥,使用des加密,提示输入密码
$ openssl genrsa -des -out key.pem 2048
Enter pass phrase for key.pem:
Verifying - Enter pass phrase for key.pem:
$ file key.pem
key.pem: PEM RSA private key
$ cat key.pem
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-CBC,8F175D0695911F6A
# 查看密钥信息需要输入密码
$ openssl pkey -in key.pem -noout -text
Enter pass phrase for key.pem:
# 删除密码
$ openssl pkey -in key.pem -out keyout.pem
Enter pass phrase for key.pem:
$ file keyout.pem
keyout.pem: ASCII text
$ cat keyout.pem
-----BEGIN PRIVATE KEY-----
# 查看密钥无需输入密码
$ openssl pkey -in keyout.pem -noout -text
Private-Key: (2048 bit)
# 使用des3加密密钥
$ openssl pkey -in key.pem -des3 -out keyout.pem
# 转换密钥格式,转换PEM格式为DER
$ openssl pkey -in key.pem -outform DER -out keyout.der
# 显示密钥的公共部分
$ openssl pkey -in key.pem -text_pub -noout
# 保存密钥的公共部分
$ openssl pkey -in key.pem -pubout -out pubkey.pem

# 生成加密密码,支持指定多个密码加密
$ openssl passwd centos
2hnI7MxxUxxec
$ openssl passwd a b c
aen7WRH8RGA3Y
zJguUnlZziMrg
JfX1Gk6ubt4gc
# -1 基于MD5加密算法,注意默认不加salt,所以每次生成的密码均不同
$ openssl passwd -1 centos
$1$GTWxvFoI$cPhegR0561DBxmJHhtsNb0
$ openssl passwd -1 centos
$1$ScJ.nJ5w$GASBt1U2G0nCt1EZeBf.s1
# -apr1 使用apache-md5格式
$ openssl passwd -apr1 centos
$apr1$DBHTkd.Y$aWPCovvdabUUR4citH4ae0
# -salt 加盐之后生成的密码保持不变
$ openssl passwd -salt aaa centos
aaQkYsTR0XUSE
$ openssl passwd -salt aaa centos
aaQkYsTR0XUSE
$ openssl passwd -1 -salt aaa centos
$1$aaa$rdc2IkKw4Ngb97rw3/FUf/
$ openssl passwd -1 -salt aaa centos
$1$aaa$rdc2IkKw4Ngb97rw3/FUf/
# -stdin 从标准输入读取密码
$ echo centos | openssl passwd -1 -salt aaa -stdin
$1$aaa$rdc2IkKw4Ngb97rw3/FUf/
# 显示原密码和加密后的密码
$ echo centos | openssl passwd -1 -salt aaa -stdin -table
centos $1$aaa$rdc2IkKw4Ngb97rw3/FUf/
# 注意格式,密码必须为最后一个参数,否则后续正常选项也会被当作密码,如下-table选项被误认为是密码
$ openssl passwd -1 -salt aaa centos -table
$1$aaa$rdc2IkKw4Ngb97rw3/FUf/
$1$aaa$/RWmEi20FWKjmEGRjsqrh1
$ openssl passwd -1 -salt aaa -table centos
centos $1$aaa$rdc2IkKw4Ngb97rw3/FUf/
$ openssl passwd -1 -salt aaa -table -reverse centos
$1$aaa$rdc2IkKw4Ngb97rw3/FUf/ centos
$ echo centos > file
# -in 读取文件中的密码加密
$ openssl passwd -1 -in file -salt aaa
$1$aaa$rdc2IkKw4Ngb97rw3/FUf/
# 生成sha512加密的密码,可直接用于用户密码文件/etc/shadow
openssl passwd -6 centos # 每次随机密码
openssl passwd -6 --salt user centos # 加盐后每次密码固定

# 生成随机字符串
$ openssl rand 3
$ openssl rand 8
# -base64 使用base64编码显示
$ openssl rand 3 -base64
tauy
# -hex 使用十六进制编码显示
$ openssl rand 3 -hex
fce414
$ openssl rand 8 -base64
AL47oaOWTVw=
$ openssl rand 8 -hex
3dfcfe6ce6cedb8d
# -out 保存到文件
$ openssl rand 8 -base64 -out file
$ cat file
pOf6Jz7EXKs=

# 密钥文件内容格式说明
The PEM private key format uses the header and footer lines:
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
The PEM public key format uses the header and footer lines:
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
The PEM RSAPublicKey format uses the header and footer lines:
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
# 删除RSA私钥的密码
$ openssl rsa -in key.pem -out keyout.pem
# 使用des3加密密钥
$ openssl rsa -in key.pem -des3 -out keyout.pem
# 转换密钥格式,转换PEM为DER
$ openssl rsa -in key.pem -outform DER -out keyout.der
# 显示密钥内容
$ openssl rsa -in key.pem -text -noout
# 显示密钥公共内容
$ openssl rsa -in key.pem -pubout -out pubkey.pem
# 以RSAPublicKey格式显示密钥的公共内容
$ openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem

# 查询域名ssl证书过期时间
$ echo | openssl s_client -servername www.a.com -connect "www.a.com":443 2>/dev/null | openssl x509 -noout -enddate
# 转换时间格式,转换为秒数后可以和当前时间作对比
$ date --date="May 22 07:39:19 2023 GMT" +%F-%T
2023-05-22-15:39:19
$ date --date="May 22 07:39:19 2023 GMT" +%s
1684741159

# centos7安装自签名的根证书(root certificates)
# 需要安装update-ca-trust软件包
$ yum install ca-certificates
# 添加自签名的ca证书
# 将证书复制到 /etc/pki/ca-trust/source/anchors/
$ cp myca-cert.cer /etc/pki/ca-trust/source/anchors/
# 运行 update-ca-trust 更新系统的证书
$ update-ca-trust
# 执行如上命令会自动将新的ca证书内容追加到系统默认的ca证书文件中/etc/ssl/certs/ca-bundle.crt(注意此为软连接文件)
# 如下,过滤^#可以看到MY_CA(自定义的名称)自签名的CA证书已经添加到文件的最上面
$ grep ^# /etc/ssl/certs/ca-bundle.crt | head
# MY_CA
# ACCVRAIZ1
# AC RAIZ FNMT-RCM
$ head /etc/ssl/certs/ca-bundle.crt
$ ll /etc/ssl/certs/ca-bundle.crt
lrwxrwxrwx. 1 root root 49 Nov 27 05:42 /etc/ssl/certs/ca-bundle.crt -> /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
$ ll /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
-r--r--r--. 1 root root 216090 Nov 27 05:42 /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
$ head /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
# 删除自签名的ca证书
rm /etc/pki/ca-trust/source/anchors/myca-cert.cer
# 重新执行更新命令
update-ca-trust

# ubuntu添加根证书
# 将根证书文件(后缀为.crt)复制到/usr/local/share/ca-certificates
$ sudo cp MY_CA.crt /usr/local/share/ca-certificates/
# 执行更新ca证书命令
$ sudo update-ca-certificates
# 执行如上命令会将新的根证书内容追加到系统默认的CA证书文件/etc/ssl/certs/ca-certificates.crt
# 显示系统当前的ca证书信息
$ awk -v cmd='openssl x509 -noout -subject' ' /BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt |tail

# 注意Firefox和Chrome浏览器需要单独导入根证书