参考文档:地址
from Crypto import Random
from Crypto.PublicKey import RSA
random_generator = Random.new().read
rsa = RSA.generate(2048, random_generator)
# 生成私钥
private_key = rsa.exportKey()
print(private_key.decode('utf-8'))
# 生成公钥
public_key = rsa.publickey().exportKey()
print(public_key.decode('utf-8'))
with open('/home/rsa_keys/rsa_private_key.pem', 'wb')as f:
f.write(private_key)
with open('/home/rsa_keys/rsa_public_key.pem', 'wb')as f:
f.write(public_key)
"""
使用公钥加密,私钥解密:防止数据泄露
"""
import base64
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5 as PKCS1_signature
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher
def get_key(key_file):
with open(key_file) as f:
data = f.read()
key = RSA.importKey(data)
return key
def encrypt_data(msg):
public_key = get_key('/home/rsa_keys/rsa_public_key.pem')
cipher = PKCS1_cipher.new(public_key)
encrypt_text = base64.b64encode(cipher.encrypt(bytes(msg.encode("utf8"))))
return encrypt_text.decode('utf-8')
def decrypt_data(encrypt_msg):
private_key = get_key('/home/rsa_keys/rsa_private_key.pem')
cipher = PKCS1_cipher.new(private_key)
back_text = cipher.decrypt(base64.b64decode(encrypt_msg), 0)
return back_text.decode('utf-8')
def test_encrypt_decrypt():
msg = "{'app_id':1, 'unid_id':'232323232', 'app_name':'小白'}"
encrypt_text = encrypt_data(msg)
print('ssss',encrypt_text)
decrypt_text = decrypt_data(encrypt_text)
print('ddd', decrypt_text)
print(msg == decrypt_text)
if __name__ == '__main__':
test_encrypt_decrypt()
"""
使用私钥来加密,使用公钥来验签:防止数据被篡改
"""
import base64
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5 as PKCS1_signature
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher
def get_key(key_file):
with open(key_file) as f:
data = f.read()
key = RSA.importKey(data)
return key
def rsa_private_sign(data):
private_key = get_key('/home/rsa_keys/rsa_private_key.pem')
signer = PKCS1_signature.new(private_key)
digest = SHA.new()
digest.update(data.encode("utf8"))
sign = signer.sign(digest)
signature = base64.b64encode(sign)
signature = signature.decode('utf-8')
return signature
def rsa_public_check_sign(text, sign):
publick_key = get_key('/home/rsa_keys/rsa_public_key.pem')
verifier = PKCS1_signature.new(publick_key)
digest = SHA.new()
digest.update(text.encode("utf8"))
return verifier.verify(digest, base64.b64decode(sign))
def test_sign():
msg = 'coolpython.net'
sign = rsa_private_sign(msg)
print(rsa_public_check_sign(msg, sign)) # True
if __name__ == '__main__':
test_sign()