加密是将明文转换为密文的过程,解密则是将密文还原为明文的过程。在编程中,常用的加密算法有很多种,比如常见的对称加密算法(如DES、AES)和非对称加密算法(如RSA)等。
下面以AES对称加密算法为例,介绍一下如何进行字符串的加密和解密。
首先,需要安装 PyCryptodome 库来使用 AES 加密算法。可以使用 `pip install pycryptodome` 命令进行安装。
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt(key, data):
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data.encode())
return cipher.nonce + tag + ciphertext
def decrypt(key, data):
nonce = data[:16]
tag = data[16:32]
ciphertext = data[32:]
cipher = AES.new(key, AES.MODE_EAX, nonce)
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
return plaintext.decode()
使用上面的代码示例,可以通过 `encrypt` 函数对字符串进行加密,通过 `decrypt` 函数对加密后的字符串进行解密。其中 `key` 是用于加密和解密的密钥,必须是16、24或者32字节的长度;`data` 是待加密或解密的字符串。
以下是一个使用示例:
key = get_random_bytes(16) # 生成一个16字节的随机密钥
plaintext = "Hello, world!" # 待加密的字符串
encrypted_data = encrypt(key, plaintext) # 加密
decrypted_data = decrypt(key, encrypted_data) # 解密
print(decrypted_data) # 输出解密后的结果
这样,就可以实现字符串的加密和解密了。请注意,密钥的保密性非常重要,一定要妥善保存。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |