RSA 加解密

  • 加密--公鑰
  • 解密--私鑰
  • 簽名--私鑰
  • 驗(yàn)證--公鑰

如果使用私鑰對(duì)數(shù)據(jù)進(jìn)行加密的話(huà),加密就沒(méi)有意義,因?yàn)槊總€(gè)人都可以擁有公鑰,所以每個(gè)人都可以用公鑰進(jìn)行解密。所以,通常使用私鑰對(duì)摘要進(jìn)行加密,然后把加密后的摘要追加到明文的后面,再使用對(duì)稱(chēng)密鑰對(duì)明文和摘要進(jìn)行整體加密。假如a為私鑰擁有者,那么接收者b拿到密文后,可以用對(duì)稱(chēng)密鑰解密,使用公鑰對(duì)摘要進(jìn)行解密,通過(guò)對(duì)比摘要,可以證明密文是否被篡改,也可以證明密文是否來(lái)自私鑰的擁有者a,這也就是驗(yàn)簽。如果b要向a發(fā)送消息,可以使用公鑰對(duì)消息進(jìn)行加密,因?yàn)橹挥衋擁有私鑰,所以只有a可以解密。整體來(lái)說(shuō),通常是,公鑰加密、私鑰解密。

公鑰與私鑰的理解

  • (1)私鑰用來(lái)進(jìn)行解密和簽名,是給自己用的。
  • (2)公鑰由本人公開(kāi),用于加密和驗(yàn)證簽名,是給別人用的。
  • (3)當(dāng)該用戶(hù)發(fā)送文件時(shí),用私鑰簽名,別人用他給的公鑰驗(yàn)證簽名,可以保證該信息是由他發(fā)送的。當(dāng)該用戶(hù)接受文件時(shí),別人用他的公鑰加密,他用私鑰解密,可以保證該信息只能由他接收到。

密鑰對(duì)生成

//generates a private Key with 8196 Bit
openssl genrsa -out private.pem 8196

//strips out the public key from the private key
openssl rsa -in private.pem -out public.pem -outform PEM -pubout

加密過(guò)程

生成 AES KEY

//generate a Radnom 32 Byte (256 Bit) AES Key
openssl rand -base64 32 -out aesKey.txt

使用 AES 加密文件

//encryp the file.txt with the generated AES Key to the file.enc
openssl enc -aes-256-cbc -salt -in file.txt -out file.enc -pass file:./aesKey.txt

使用 RSA 公鑰加密 AES Key

//encrpyt the AES Key with the RSA Public Key
openssl rsautl -encrypt -inkey public.pem -pubin -in aesKey.txt -out aesKey.txt.crypted

解密過(guò)程

通過(guò) RSA 私鑰解密 AES Key

//decrypt the AES Key with the Private RSA Key
openssl rsautl -decrypt -inkey private.pem -in aesKey.txt.crypted -out aesKey.txt.decrypted

通過(guò) AES Key 解密文件

//decrypt the encrypted file with the encrypted AES Key
openssl enc -d -aes-256-cbc -in file.enc -out file.txt.decrypted -pass file:./aesKey.txt.decrypted

簽名過(guò)程

對(duì)文件生成簽名

//Generate the signature.txt for the file.txt
openssl dgst -sha256 -sign private.pem -out signature.txt file.txt 

對(duì)文件驗(yàn)簽

openssl dgst -sha256 -verify public.pem -signature signature.txt file.txt
# in case of success: prints "Verified OK"
# in case of failure: prints "Verification Failure"

links

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容