1、生成密鑰對
1.1 生成私鑰
使用genrsa
指令生成私鑰荸百,指定模的長度為 2048 bit(256byte)稽坤。
openssl genrsa -out privkey.pem 2048
生成私鑰
1.2 生成公鑰
使用rsa
指令生成公鑰,關(guān)鍵的選項(xiàng)為-pubout
渔伯,告訴openssl
需要輸出的文件為公鑰文件顶霞。
openssl rsa -in privkey.pem -pubout -out pubkey.pem
2、生成待加密/簽名明文
這只是用來測試加解密的明文锣吼,你也可以用其它形式的明文替代
echo penghuikang@foxmail.com > info.txt
3选浑、公鑰加密/私鑰解密
3.1 使用公鑰對明文進(jìn)行加密
使用rsautl
指令及-encrypt
選項(xiàng)對明文進(jìn)行加密,-pubin
選項(xiàng)告訴openssl
通過-inkey
選項(xiàng)傳入的密鑰為公鑰吐限,因?yàn)槿绻麤]有該選項(xiàng)鲜侥,openssl
默認(rèn)認(rèn)為-inkey
傳入的是私鑰。
openssl rsautl -encrypt -in info.txt -inkey pubkey.pem -pubin -out info.txt.enc
如果你需要使用一個(gè)x509證書中的RSA公鑰的進(jìn)行加密诸典,則使用-certin
選項(xiàng)來代替-pubin
描函,以此來告訴openssl
通過-inkey
選項(xiàng)傳入的是一個(gè)帶RSA公鑰的證書,使用證書中的RSA公鑰進(jìn)行加密狐粱。
openssl rsautl -encrypt -in info.txt -inkey pubkey.pem -certin -out info.txt.enc
3.2 使用私鑰解密
使用rsautl
指令及-decrypt
選項(xiàng)對明文進(jìn)行解密舀寓,如上所述,此時(shí)不需要傳入-pubin
選項(xiàng)肌蜻,因?yàn)榇藭r(shí)-inkey
傳入的是私鑰互墓。
openssl rsautl -decrypt -in info.txt.enc -inkey privkey.pem -out info_decrypt.txt
4、私鑰簽名/公鑰驗(yàn)簽
4.1 使用私鑰對明文進(jìn)行簽名
使用rsautl
指令蒋搜、-sign
選項(xiàng)及-inkey
指定的私鑰對明文進(jìn)行簽名篡撵,得到簽名文件info.txt.sign
判莉。
openssl rsautl -sign -in info.txt -inkey privkey.pem -out info.txt.sign
4.2 使用公鑰驗(yàn)簽得到明文
使用rsautl
指令、-verify
選項(xiàng)及-inkey
指定的公鑰對密文進(jìn)行驗(yàn)證育谬,并得到明文文件info_verify.txt
券盅。
openssl rsautl -verify -in info.txt.sign -inkey pubkey.pem -pubin -out info_verify.txt