使用Python实现文本加密和解密功能
发布时间:2023-12-04 08:50:09
要实现文本加密和解密功能,可以使用一些常见的加密算法,例如凯撒密码、栅栏密码、AES加密等。下面是使用Python实现凯撒密码和AES加密的示例代码。
1. 凯撒密码加密和解密
凯撒密码是一种替换密码,它通过将字母表中的每个字母向后移动固定数量的位置来进行加密。以下是凯撒密码的加密和解密函数的实现代码:
def caesar_encrypt(plain_text, shift):
encrypted_text = ""
for char in plain_text:
if char.isalpha():
ascii_code = ord(char)
shifted_code = (ascii_code - ord('a') + shift) % 26 + ord('a')
encrypted_text += chr(shifted_code)
else:
encrypted_text += char
return encrypted_text
def caesar_decrypt(encrypted_text, shift):
plain_text = ""
for char in encrypted_text:
if char.isalpha():
ascii_code = ord(char)
shifted_code = (ascii_code - ord('a') - shift) % 26 + ord('a')
plain_text += chr(shifted_code)
else:
plain_text += char
return plain_text
# 使用例子
plain_text = "hello world"
shift = 3
encrypted_text = caesar_encrypt(plain_text, shift)
print("加密后:", encrypted_text)
decrypted_text = caesar_decrypt(encrypted_text, shift)
print("解密后:", decrypted_text)
输出结果:
加密后: khoor zruog 解密后: hello world
2. AES加密和解密
AES(Advanced Encryption Standard)是一种对称加密算法,用于保护计算机系统中的敏感数据。Python提供了Crypto库来实现AES加密和解密。以下是使用Crypto库实现AES加密和解密的示例代码:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def aes_encrypt(plain_text, key):
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
encrypted_text, tag = cipher.encrypt_and_digest(plain_text.encode())
return encrypted_text, nonce, tag
def aes_decrypt(encrypted_text, nonce, tag, key):
cipher = AES.new(key, AES.MODE_EAX, nonce)
plain_text = cipher.decrypt_and_verify(encrypted_text, tag)
return plain_text.decode()
# 使用例子
plain_text = "hello world"
key = get_random_bytes(16)
encrypted_text, nonce, tag = aes_encrypt(plain_text, key)
print("加密后:", encrypted_text)
decrypted_text = aes_decrypt(encrypted_text, nonce, tag, key)
print("解密后:", decrypted_text)
输出结果:
加密后: b'\xadm\x9c\xdby\xdfJ\x8f5M$xP' 解密后: hello world
以上是使用Python实现凯撒密码和AES加密算法的示例代码。根据实际需求,可以选择适合的加密算法来进行文本的加密和解密操作。
