欢迎访问宙启技术站
智能推送

RSA非对称加密算法在Python中的应用

发布时间:2023-12-17 16:46:32

RSA(Rivest–Shamir–Adleman)是一种非对称加密算法,被广泛应用于信息安全领域。它基于两个大质数的乘积难解因子分解问题,具有安全性高、实施简单等特点。

在Python中,我们可以使用cryptography库来实现RSA非对称加密算法。下面是一个使用RSA进行加密和解密的例子:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization

def encrypt_rsa(public_key, message):
    cipher = public_key.encrypt(
        message,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    return cipher

def decrypt_rsa(private_key, cipher):
    message = private_key.decrypt(
        cipher,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    return message

# 生成RSA密钥对
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)
public_key = private_key.public_key()

# 序列化公钥和私钥
pem_private_key = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)
pem_public_key = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

# 加密和解密示例
message = b'This is a secret message.'
cipher = encrypt_rsa(public_key, message)
decrypted_message = decrypt_rsa(private_key, cipher)

print('Original message:', message)
print('Encrypted message:', cipher)
print('Decrypted message:', decrypted_message)

在上面的例子中,首先我们使用rsa.generate_private_key函数生成了一个私钥,然后通过private_key.public_key()方法获取对应的公钥。

接着,我们使用private_key.private_bytespublic_key.public_bytes方法将私钥和公钥序列化为PEM格式的字符串,方便存储和传输。

然后,我们定义了encrypt_rsadecrypt_rsa两个函数,用于加密和解密消息。在加密和解密时,我们使用了cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey.encryptcryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey.decrypt方法,并指定了补位算法和哈希算法。

最后,我们使用生成的公钥对消息进行加密,得到密文cipher。然后使用生成的私钥对密文进行解密,得到原始消息decrypted_message。我们可以看到,解密得到的消息与原始消息完全相同。

这就是使用RSA非对称加密算法在Python中的一个简单例子。通过使用cryptography库,我们可以轻松地实现RSA的加密和解密操作,从而保证信息的安全性。