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

在Python中使用RSA加解密算法保护数据安全

发布时间:2023-12-24 10:00:01

RSA是非对称加密算法,可以用于保护数据的安全性。它使用一对密钥,即公钥和私钥。公钥用于加密数据,私钥用于解密数据。下面是在Python中使用RSA算法保护数据安全的一个例子。

首先,我们需要安装cryptography库,它提供了Python中的RSA算法实现。可以使用以下命令安装该库:

pip install cryptography

在导入所需的库之前,我们需要生成RSA密钥对。使用以下代码生成1024位的RSA密钥对:

from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization

private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=1024,
)

public_key = private_key.public_key()

private_pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)

public_pem = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

with open('private_key.pem', 'wb') as f:
    f.write(private_pem)

with open('public_key.pem', 'wb') as f:
    f.write(public_pem)

以上代码将生成private_key.pem和public_key.pem两个文件,分别存储私钥和公钥。

生成RSA密钥对后,我们可以使用该密钥对来加密和解密数据。以下是加密和解密数据的示例代码:

from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization

def encrypt_data(data, public_key_file):
    with open(public_key_file, "rb") as f:
        public_key = serialization.load_pem_public_key(
            f.read(),
            backend=default_backend()
        )

    encrypted_data = public_key.encrypt(
        data,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )

    return encrypted_data

def decrypt_data(encrypted_data, private_key_file):
    with open(private_key_file, "rb") as f:
        private_key = serialization.load_pem_private_key(
            f.read(),
            password=None,
            backend=default_backend()
        )

    decrypted_data = private_key.decrypt(
        encrypted_data,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )

    return decrypted_data

# 加密示例
data = b"Hello, World!"
encrypted_data = encrypt_data(data, "public_key.pem")

# 解密示例
decrypted_data = decrypt_data(encrypted_data, "private_key.pem")

print("加密前数据:", data)
print("解密后数据:", decrypted_data)

在上述代码中,我们首先读取公钥和私钥文件。然后,我们使用公钥加密数据,并使用私钥解密数据。最后,我们将原始数据和解密后的数据打印出来。

这就是在Python中使用RSA加解密算法保护数据安全的一个例子。通过使用RSA算法,我们可以实现数据的安全传输和存储。