Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux OpenSSL 指令列實戰:Base64 編解碼、檔案校驗、加密解密完整教學

編輯:關於 Linux

OpenSSL 不僅是 TLS/SSL 庫,其指令列工具 openssl 更是處理編碼、雜湊、加密的利器。本文整理 Base64 編解碼、SHA1/MD5 校驗、AES/Blowfish 檔案加密解密的實戰指令與參數說明。

1. Base64 編碼 / 解碼

# 編碼:二進位檔 → 文字檔
openssl base64 -in filename.bin -out filename.txt

# 解碼:文字檔 → 二進位檔
openssl base64 -d -in filename.txt -out filename.bin

# 管道用法
cat filename.bin | openssl base64 > filename.txt
cat filename.txt | openssl base64 -d > filename.bin

2. 檔案一致性校驗(雜湊值)

# SHA1(推薦,跨平台一致)
openssl sha1 filename
# SHA1(filename)= e83a42b9bc8431a6645099be50b6341a35d3dceb

# MD5(較舊,仍常用於相容性)
openssl md5 filename
# MD5(filename)= 26e9855f8ad6a5906fea121283c729c4

# SHA256(更強)
openssl sha256 filename

# 批次產生清單
openssl sha1 * > sha1sum.txt

優勢:openssl sha1 跨平台(Linux/Unix/Windows)輸出格式一致,優於 sha1sum、md5sum 等工具在不同發行版間的細微差異。

3. 檔案加密 / 解密

推薦算法:

  • aes-128-cbc:AES 128 位元 CBC 模式,強度佳、效能好。
  • bf (Blowfish):舊版相容,現不建議新專案使用。
  • 避免:des、rc4-40(已知弱點)。

加密

openssl enc -aes-128-cbc -in filename -out filename.aes-128-cbc
# 提示輸入加密密碼(兩次確認)

解密

openssl enc -d -aes-128-cbc -in filename.aes-128-cbc -out filename
# 提示輸入解密密碼

指定密碼(腳本自動化)

# 從環境變數讀取(較安全)
export PASS=mysecret
openssl enc -aes-128-cbc -in filename -out filename.enc -pass env:PASS
openssl enc -d -aes-128-cbc -in filename.enc -out filename -pass env:PASS

# 從檔案讀取第一行
openssl enc -aes-128-cbc -in filename -out filename.enc -pass file:/path/to/pass.txt

4. 進階:數位簽章與驗證

# 產生私鑰
openssl genrsa -out private.key 2048
# 導出公鑰
openssl rsa -in private.key -pubout -out public.key

# 簽章
openssl dgst -sha256 -sign private.key -out file.sig filename

# 驗證
openssl dgst -sha256 -verify public.key -signature file.sig filename

OpenSSL 指令輸出截圖

常用參數速查

參數說明
-in / -out輸入/輸出檔案
-d解密模式
-a輸出 Base64 編碼(加密時常用)
-pass密碼來源:pass:、env:、file:、fd:、stdin
-salt / -nosalt預設使用鹽值增強安全,-nosalt 關閉
-md密鑰導出雜湊算法(預設 sha256,舊版 md5)
Copyright © Windows教程網 All Rights Reserved