使用python3代码写出base加解密程序
以下是Python 3的基本加解密程序:
import base64
def encrypt(text):
# 将字符串编码为字节流
message = text.encode('utf-8')
# 对字节流进行base64编码
encrypted_message = base64.b64encode(message)
# 将base64编码后的字节流转换为字符串
return encrypted_message.decode('utf-8')
def decrypt(encrypted_text):
# 将字符串解码为字节流
encrypted_message = encrypted_text.encode('utf-8')
# 对字节流进行base64解码
decrypted_message = base64.b64decode(encrypted_message)
# 将base64解码后的字节流转换为字符串
return decrypted_message.decode('utf-8')
# 测试加解密函数
text = 'Hello, World!'
encrypted_text = encrypt(text)
print('加密后的字符串:', encrypted_text)
decrypted_text = decrypt(encrypted_text)
print('解密后的字符串:', decrypted_text)
输出结果:
加密后的字符串: SGVsbG8sIFdvcmxkIQ==
解密后的字符串: Hello, World!
在上面的代码中,我们使用了Python标准库中的base64模块来进行加解密操作。encrypt函数将字符串先编码为字节流,然后再对字节流进行base64编码,并将编码后的结果转换为字符串返回。decrypt函数则是将字符串先解码为字节流,然后对字节流进行base64解码,并将解码后的结果转换为字符串返回
原文地址: https://www.cveoy.top/t/topic/cVXx 著作权归作者所有。请勿转载和采集!