python RSA加密解密

RSA加密和解密是一种常见的非对称加密方法,主要用于保护数据的安全性。在RSA加密中,使用公钥对数据进行加密,使用私钥进行解密。

pip install pycryptodome
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii

def generate_keys():
    # 生成RSA密钥对
    key = RSA.generate(2048)
    private_key = key.export_key()
    public_key = key.publickey().export_key()

    return private_key, public_key

def encrypt_message(public_key, message):
    # 使用公钥加密消息
    rsa_public_key = RSA.import_key(public_key)
    cipher = PKCS1_OAEP.new(rsa_public_key)
    encrypted_message = cipher.encrypt(message.encode('utf-8'))
    
    return binascii.hexlify(encrypted_message).decode('utf-8')

def decrypt_message(private_key, encrypted_message):
    # 使用私钥解密消息
    rsa_private_key = RSA.import_key(private_key)
    cipher = PKCS1_OAEP.new(rsa_private_key)
    decrypted_message = cipher.decrypt(binascii.unhexlify(encrypted_message))
    
    return decrypted_message.decode('utf-8')

# 示例使用
if __name__ == "__main__":
    # 生成密钥对
    private_key, public_key = generate_keys()
    print("Public Key:", public_key.decode('utf-8'))
    print("Private Key:", private_key.decode('utf-8'))
    
    # 要加密的消息
    message = "Hello, RSA!"
    print("Original Message:", message)
    
    # 加密消息
    encrypted = encrypt_message(public_key, message)
    print("Encrypted Message:", encrypted)
    
    # 解密消息
    decrypted = decrypt_message(private_key, encrypted)
    print("Decrypted Message:", decrypted)
posted @ 2024-11-18 16:03  二月雪  阅读(166)  评论(0编辑  收藏  举报