2010/01/24

使用公開金鑰加密/私密金鑰解密(use openssl)


  • 使用公開金鑰加密/私密金鑰解密對檔案做加解密
  • 此範例使用 openssl RSA 的工具程式配合公開金鑰及私鑰,做加密及解密的操作
[mtchang@sc220469 key]$ openssl rsautl --help
Usage: rsautl [options]
-in file        input file
-out file       output file
-inkey file     input key
-keyform arg    private key format - default PEM
-pubin          input is an RSA public
-certin         input is a certificate carrying an RSA public key
-ssl            use SSL v2 padding
-raw            use no padding
-pkcs           use PKCS#1 v1.5 padding (default)
-oaep           use PKCS#1 OAEP
-sign           sign with private key
-verify         verify with public key
-encrypt        encrypt with public key
-decrypt        decrypt with private key
-hexdump        hex dump output
-engine e       use engine e, possibly a hardware device.
-passin arg    pass phrase source
  • 先產生 private.pem 私鑰
[mtchang@sc220469 key]$ openssl genrsa -out private.pem 1024
Generating RSA private key, 1024 bit long modulus
..++++++
..........................................++++++
e is 65537 (0x10001)
  • 由 private 私鑰產生 public.pem 公鑰
[mtchang@sc220469 key]$ openssl rsa -in private.pem -out public.pem -outform PEM -pubout
writing RSA key
  • 產生一個 file.txt 的測試檔案
[mtchang@sc220469 key]$ echo 'test to secrets with openssl RSA' > file.txt
  • 使用 openssl rsautl 及 public.pem 金鑰對 file.txt 加密,並產生 file.ssl 的加密檔案,此檔案為二進位檔案。
[mtchang@sc220469 key]$ openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl
[mtchang@sc220469 key]$ ls -l
-rw-r--r-- 1 mtchang users  128 Jan 25 03:52 file.ssl
-rw-r--r-- 1 mtchang users   33 Jan 25 03:52 file.txt
  • 現在把 file.ssl 使用 private.pem 的私鑰做解密的動作並輸出 decrypted.txt 的檔案
[mtchang@sc220469 key]$ openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt
[mtchang@sc220469 key]$ cat decrypted.txt 
test to secrets with openssl RSA
延伸閱讀:http://jangmt.com/wiki/index.php?title=253-ch3

沒有留言: