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

Python中的加密算法与Encrypter()的应用

发布时间:2024-01-11 10:20:16

Python中有很多加密算法可供选择,常见的有对称加密算法和非对称加密算法。

对称加密算法是指加密和解密使用相同的密钥的算法。常见的对称加密算法有DES、3DES、AES等。以下是使用AES对称加密算法进行加密和解密的例子:

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

def encrypt(message, key):
    cipher = AES.new(key, AES.MODE_EAX)
    cipher_text, tag = cipher.encrypt_and_digest(message.encode())
    return (cipher_text, cipher.nonce, tag)

def decrypt(cipher_text, nonce, tag, key):
    cipher = AES.new(key, AES.MODE_EAX, nonce)
    plain_text = cipher.decrypt_and_verify(cipher_text, tag)
    return plain_text.decode()

key = get_random_bytes(32)
message = "Hello, World!"

cipher_text, nonce, tag = encrypt(message, key)
plain_text = decrypt(cipher_text, nonce, tag, key)

print("Cipher text:", cipher_text)
print("Decrypted message:", plain_text)

非对称加密算法是指加密和解密使用不同的密钥的算法。常见的非对称加密算法有RSA、Diffie-Hellman等。以下是使用RSA非对称加密算法进行加密和解密的例子:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

def encrypt(message, public_key_path):
    key = RSA.import_key(open(public_key_path).read())
    cipher = PKCS1_OAEP.new(key)
    cipher_text = cipher.encrypt(message.encode())
    return cipher_text

def decrypt(cipher_text, private_key_path):
    key = RSA.import_key(open(private_key_path).read())
    cipher = PKCS1_OAEP.new(key)
    plain_text = cipher.decrypt(cipher_text).decode()
    return plain_text

public_key_path = "public.pem"
private_key_path = "private.pem"
message = "Hello, World!"

cipher_text = encrypt(message, public_key_path)
plain_text = decrypt(cipher_text, private_key_path)

print("Cipher text:", cipher_text)
print("Decrypted message:", plain_text)

在上述两个例子中,encrypt函数用于加密消息,decrypt函数用于解密密文。在使用这些加密算法之前,需要安装相关的加密库,如pycryptodome,可以使用pip install pycryptodome进行安装。

加密算法可以用于保护敏感信息的传输和存储,例如在网络通信中对数据进行加密保护,或者在数据库中存储用户密码时对其进行加密。