Rsa加密机制
属于非对称加密,公钥用于加密数据,私钥用于解密数据,两者不可逆。公钥和私钥是同时生成的,且一一对应。比如 a拥有公钥,b拥有公钥和私钥。a将数据通过公钥进行加密后,发给b,b通过私钥和公钥进行解密
AES属于对称加密公钥和私钥是一样的,可以加密也可以解密
在python中要使用这些加密方法要使用到pycryptodome这个包
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_ciper
random_generator = Random.new().read
ras = RSA.generate(2048,random_generator)
#生成公钥
public_key=ras.public_key().exportKey()
with open("public_a.rsa","wb") as writers:
writers.write(public_key)
#生成私钥
private_key = ras.exportKey()
with open("private_key_a.rsa",'wb') as writers:
writers.write(private_key)
#使用上面的一对公钥和私钥对数据data加密
data = input("请输入待加密的文本字符:")
with open("public_a.rsa",'r') as f:
key = f.read()
pub_key = RSA.import_key(str(key))
cipher = PKCS1_ciper.new(pub_key)
rsa_text = cipher.encrypt(data.encode('utf-8'))
#发送给客户端
with open("private_key_a.rsa",'r') as reader:
key = reader.read()
pri_key = RSA.import_key(key)
cipher = PKCS1_ciper.new(pri_key)
raw_date = cipher.decrypt(rsa_text,0)
print(f"使用私钥解密{rsa_text}后等于{raw_date.decode('utf-8')}")
Aes加密
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
data ='python'
key = get_random_bytes(16)
mode = AES.MODE_OFB#选择加密模式
aes_cryptor = AES.new(key,mode,b'0000000000000000')
length, count = 16, len(data)
add = 0
if count % length != 0:
add = length - (count % length)
data += '\0' * add
cipher_text = aes_cryptor.encrypt(data.encode('utf-8'))
print(cipher_text)
aes_cryptor = AES.new(key,mode,b'0000000000000000')
raw_text = aes_cryptor.decrypt(cipher_text)
print(raw_text.decode('utf-8'))