Python中AES与Fernet加密:用户输入转字节类型问题求助
解决Python文本加密中字符串转字节的问题
嘿,这个问题其实是加密开发里的基础小坎儿——所有加密算法本质上都是对字节流进行操作的,而我们用input()获取的用户输入是字符串类型,所以只需要做个简单的编码转换就能搞定啦!我分别给你说下Fernet和AES的处理方式:
Fernet 加密的解决方案
你只需要把用户输入的字符串调用.encode('utf-8')方法转换成字节类型,加密后如果需要把结果转成可读的字符串(比如存储到文件),可以用token.decode('utf-8');解密的时候再反向操作就行。修改后的代码如下:
from cryptography.fernet import Fernet # 生成密钥(注意:实际应用中要妥善保存密钥,别每次运行都重新生成) key = Fernet.generate_key() f = Fernet(key) # 获取用户输入并转换为字节 user_input = input("请输入要加密的文本:") input_bytes = user_input.encode('utf-8') # 加密并输出 token = f.encrypt(input_bytes) print(f"加密后的结果(字节):{token}") # 如果需要字符串格式的加密结果 token_str = token.decode('utf-8') print(f"加密后的结果(字符串):{token_str}") # 解密示例 decrypted_bytes = f.decrypt(token) decrypted_text = decrypted_bytes.decode('utf-8') print(f"解密后的文本:{decrypted_text}")
AES 加密的解决方案
AES加密同样需要字节输入,处理逻辑和Fernet完全一致:先把用户输入编码成字节,加密完成后如果需要可读格式,可以用Base64编码(因为AES加密后的字节可能包含不可打印字符)。这里用pycryptodome库举个示例(需要先安装:pip install pycryptodome):
from Crypto.Cipher import AES from Crypto.Random import get_random_bytes import base64 # AES要求密钥长度为16、24或32字节,这里生成16字节密钥 key = get_random_bytes(16) cipher = AES.new(key, AES.MODE_EAX) # 获取用户输入并转字节 user_input = input("请输入要加密的文本:") input_bytes = user_input.encode('utf-8') # 加密 ciphertext, tag = cipher.encrypt_and_digest(input_bytes) # 把加密结果转成Base64字符串方便存储/传输 ciphertext_b64 = base64.b64encode(ciphertext).decode('utf-8') nonce_b64 = base64.b64encode(cipher.nonce).decode('utf-8') tag_b64 = base64.b64encode(tag).decode('utf-8') print(f"加密后的文本(Base64):{ciphertext_b64}") # 解密示例 cipher_decrypt = AES.new(key, AES.MODE_EAX, nonce=base64.b64decode(nonce_b64)) decrypted_bytes = cipher_decrypt.decrypt_and_verify(base64.b64decode(ciphertext_b64), base64.b64decode(tag_b64)) decrypted_text = decrypted_bytes.decode('utf-8') print(f"解密后的文本:{decrypted_text}")
核心要点总结:
- 字符串转字节:
字符串.encode('utf-8')(utf-8是通用编码,也可以根据需求选其他编码) - 字节转字符串:
字节.decode('utf-8') - 对于AES这类加密后可能产生不可打印字节的算法,用Base64编码转成可读字符串会更实用
内容的提问来源于stack exchange,提问作者Snow Angel
相关产品推荐
相关产品推荐

