介紹如何使用 OpenSSL 指令產生檔案的數位簽章,並驗證簽章的有效性。

建立 RSA 金鑰

首先使用以下 OpenSSL 指令產生長度為 8912 位元的 RSA 私鑰,並設定保護金鑰的密碼。

# 產生 8912 位元的 RSA 私鑰,以 AES256 加密保護
openssl genrsa -aes256 -out private.pem 8912
Generating RSA private key, 8912 bit long modulus (2 primes)
..................................................................+++
.........................+++
e is 65537 (0x010001)
Enter pass phrase for private.pem:
Verifying - Enter pass phrase for private.pem:

有了 RSA 私鑰(private.pem)之後,再用私鑰產生公鑰(public.pem):

# 從 RSA 私鑰產生 RSA 公鑰
openssl rsa -in private.pem -pubout -out public.pem
Enter pass phrase for private.pem:
writing RSA key

RSA 的私鑰可以用來對檔案產生數位簽章,而公鑰則可用來驗證數位簽章的有效性。

產生數位簽章

使用 RSA 私鑰對檔案產生數位簽章:

# 產生數位簽章
openssl dgst -sha512 -sign private.pem -out digest.sha512 myfile.txt
Enter pass phrase for private.pem:

在使用私鑰之前,鑰先輸入私鑰的保護密碼,將私鑰解開之後,才會以私鑰產生檔案的數位簽章檔案 digest.sha512

驗證數位簽章

將原始檔案 myfile.txt 與數位簽章檔案 digest.sha512 一起傳送給接收者後,接收者即可使用 RSA 公鑰 public.pem 驗證數位簽章的有效性:

# 驗證數位簽章
openssl dgst -sha512 -verify public.pem -signature digest.sha512 myfile.txt
Verified OK

驗證數位簽章時若出現 Verified OK 就代表簽章是有效的,亦即原始檔案 myfile.txt 沒有被竄改過。

如果出現 Verification Failure 的訊息,就代表數位簽章有問題,myfile.txt 可能損毀或是遭到竄改。

參考資料