openssl の使い方
暗号・鍵・証明書の道具
書き方
openssl rand -base64|-hex バイト数 openssl enc -aes-256-cbc -pbkdf2 -salt -in 元 -out 暗号文 [-pass file:パスワードのファイル] openssl enc -d -aes-256-cbc -pbkdf2 -in 暗号文 -out 元 openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out 鍵 openssl pkey -in 鍵 -pubout -out 公開鍵 openssl req -new -key 鍵 -out CSR -subj '/CN=名前' openssl req -x509 -newkey rsa:2048 -nodes -keyout 鍵 -out 証明書 -days 日数 -subj … openssl x509 -in 証明書 -noout -subject -issuer -dates -fingerprint -checkend 秒 openssl s_client -connect ホスト:443 -servername ホスト openssl dgst -sha256 ファイル
-pass pass:… はパスワードがコマンドの履歴や ps に残るので、file: や env: を使います。-pbkdf2 を付けないと古い鍵の作り方の警告が出ます。秘密鍵は 600 で作られます。echo | openssl s_client … 2>/dev/null | openssl x509 -noout -enddate で相手の証明書の期限を調べられます。
よく使うオプション
| オプション | 意味 |
|---|---|
req -x509 -newkey rsa:2048 -nodes | 鍵と自己署名の証明書をまとめて作る(-nodes で鍵にパスワードを付けない) |
req -new -key 鍵 | 証明書の申請(CSR)を作る |
x509 -noout -subject -dates | 証明書の名前と有効期限を出す |
s_client -connect ホスト:443 | サーバーにつなぎ、返ってきた証明書を見る |
rand -hex バイト数 | 乱数を作る |
-days 日数 | 証明書の有効な日数 |
例
$ sudo openssl req -x509 -newkey rsa:2048 -nodes -keyout /etc/pki/tls/private/web.key -out /etc/pki/tls/certs/web.crt -days 365 -subj '/CN=web.example.lan'
試しの HTTPS のために、鍵と自己署名の証明書を作ります。ssl.conf の SSLCertificateFile・SSLCertificateKeyFile に書くファイルです。
$ openssl x509 -in /etc/pki/tls/certs/web.crt -noout -subject -datessubject=CN = web.example.lan
notBefore=Nov 6 01:20:00 2026 GMT
notAfter=Nov 6 01:20:00 2027 GMT証明書の名前と、いつからいつまで使えるかを確かめます。
$ openssl s_client -connect web.example.lan:443 -servername web.example.lan < /dev/null | head -5
サーバーが本当にその証明書を返しているか、外から確かめます。
$ openssl x509 -in /etc/pki/tls/certs/web.crt -noout -checkend 2592000Certificate will not expire30 日(2592000 秒)より先も使えるかを確かめます。期限が近いと Certificate will expire と出ます。
よくある間違い・注意
- 鍵のファイル(.key)はほかの人に読ませません。chmod 600 にします。
- 自己署名の証明書は、ブラウザに「安全ではない」と出ます。公開するサイトでは認証局の証明書を使います。
- 鍵と証明書の組み合わせを間違えると httpd が起動しません。openssl x509 -noout -modulus と openssl rsa -noout -modulus の値が同じか比べます。
実際に打って練習する
Linux レベル2 コースの Lv73「館に鍵 mod_ssl」で覚えます(第6章 館と広間(Web と共有のサーバー))。ブラウザの中のシミュレーターで、本物と同じように打って確かめられます。
すべてのレベルが、ゴールド以上のプランで遊べます。