非对称加密(RSA)
- 非对称加密。加密和解密的秘钥不是同一个秘钥。这里需要两把钥匙。一个公钥,一个私钥。公钥发送给客户端。发送端用公钥对数据进行加密。在发送给接收端,接收端使用私钥来对数据解密。由于私钥只存放在接收端这边。所以即使数据被截获了,也是无法进行解密的。
- 公钥和私钥
- 常见的非对称加密算法:RSA/DSA等等,我们就介绍一个,RSA加密,也是最常见的一种加密方案。
- 创建公钥和私钥
from Crypto.PublicKey import RSA
rsakey=RSA.generate(1024)
with open("rsa.public.pem",mode="wb") as f:
f.write(rsakey.publickey().exportKey())
with open("rsa.private.pem",mode="wb") as f:
f.write(rsakey.exportKey())
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_V1_5
import base64
data='我喜欢你'
with open("rsa.public.pem",mode='r') as f:
pk=f.read()
rsa_pk=RSA.importKey(pk)
rsa=PKCS1_v1_5.new(rsa_pk)
result=rsa.encrypt(data.encode("utf-8"))
b64_result=base64.b64encode(result).decode("utf-8")
print(b64_result)
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_V1_5
import base64
data='BkiKG8jzVGzbWOl4m8NXJEYglgtxhOB05MGmap8JSP97GzoewPBmDTs7c5iACUof3k/uJf0H88GygajVgBvkcbckJp7oO+Qj6VSUQYTOHhKN/VG2a8v+WzL34EO/S7BYoj2oOxIDAr8wDLxYxjBeXq/Be6Q1yBbnZcKaMkifhP8='
with open("rsa.private.pem",mode="r") as f:
prikey=f.read()
rsa_pk=RSA.importKey(prikey)
rsa=PKCS1_V1_5.new(rsa_pk)
result=rsa.decrypt(base64.b64decode(data),None)
print("rsa解密数据:::",result.decode("utf-8"))