rsa公钥加密算法代码
时间: 2024-11-05 09:10:23 浏览: 17
RSA公钥加密算法的设计与实现.docx
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,它基于大数因子分解的难度作为基础。以下是RSA公钥加密的基本流程,包括生成密钥对、加密和解密过程的简化Python代码示例:
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 生成密钥对
def generate_keys():
key = RSA.generate(2048) # 生成2048位的密钥对
public_key = key.publickey().export_key() # 公钥
private_key = key.export_key() # 私钥
return public_key, private_key
# 加密函数
def encrypt(message, public_key):
rsa_public_key = RSA.import_key(public_key)
cipher_rsa = PKCS1_OAEP.new(rsa_public_key)
ciphertext = cipher_rsa.encrypt(message.encode('utf-8'))
return ciphertext
# 解密函数
def decrypt(ciphertext, private_key):
rsa_private_key = RSA.import_key(private_key)
cipher_rsa = PKCS1_OAEP.new(rsa_private_key)
plaintext = cipher_rsa.decrypt(ciphertext).decode('utf-8')
return plaintext
# 示例
public_key, private_key = generate_keys()
message = "Hello, RSA!"
encrypted_msg = encrypt(message, public_key)
print(f"Encrypted message: {encrypted_msg.hex()}")
decrypted_msg = decrypt(encrypted_msg, private_key)
print(f"Decrypted message: {decrypted_msg}")
阅读全文