Openssl RSA基本加解密操作

weixin_33866037發表於2017-11-01

1. 產生私鑰 (private key)

$ openssl genrsa -out key.pem 1024

結果是生成一個私鑰檔案: key.pem

$ file key.pem 
key.pem: PEM RSA private key

2. 產生對應的公鑰 (public key)

$ openssl rsa -in key.pem -pubout -out pub.pem

結果是生成一個公鑰檔案: pub.pem

$ file pub.pem 
pub.pem: ASCII text

3. 使用公鑰來加密字串

因為openssl加密的是位元組流, 為了便於觀察, 我們的例子把所有的輸入輸出變成可讀字串,對於密文使用base64進行編碼

$ echo -n "abcd" | openssl rsautl -encrypt -oaep -pubin -inkey pub.pem | openssl enc -A -base64
V6OdcZsflfYmQw0hMmf1Vg/X3N92JU7uIg2DxXQCJLoybo1TYvP+Nh944MuoVy+Z9BxE5h1sea8TIS81RXYAhif3rIy0FPNThNZcy1ryVu5odNLX/P01WdMYzYZvj5opoWka23cw5s5DnQJBklh9hLDiPcFR+8vuf0oEj+RsB24=

4. 使用私鑰來解密前面生成的加密串

$ export CIPHER="V6OdcZsflfYmQw0hMmf1Vg/X3N92JU7uIg2DxXQCJLoybo1TYvP+Nh944MuoVy+Z9BxE5h1sea8TIS81RXYAhif3rIy0FPNThNZcy1ryVu5odNLX/P01WdMYzYZvj5opoWka23cw5s5DnQJBklh9hLDiPcFR+8vuf0oEj+RsB24="
$ echo -n ${CIPHER} | openssl enc -A -base64 -d | openssl rsautl -decrypt -oaep -inkey key.pem
abcd

5. 引數說明

  • -inkey file
    the input key file, by default it should be an RSA private key.
  • -pubin
    the input file is an RSA public key.
  • -encrypt
    encrypt the input data using an RSA public key.
  • -decrypt
    decrypt the input data using an RSA private key.
  • -oaep
    the padding algorithm is used, optimal asymmetric encryption padding (OAEP)

相關文章