我试图在Python中创建一些代码来使用DES加密/解密消息。
我似乎收到了以下错误,但却找不出原因。
‘’utf 8‘编解码器无法解码位置1中的字节0xc1 :无效开始字节’
守则如下:
from Crypto.Cipher import DES
key = 'abcdefgh'
def encrypt(msg):
cipher = DES.new(key.encode('utf-8'), DES.MODE_EAX)
ciphertext = cipher.encrypt(msg.encode('utf-8'))
return ciphertext
def decrypt(ciphertext):
cipher = DES.new(key.encode('utf-8'), DES.MODE_EAX)
plaintext = cipher.decrypt(ciphertext)
return plaintext.decode('utf-8')
ciphertext = encrypt('Python')
plaintext = decrypt(ciphertext)
print(f'Cipher text: {ciphertext}')
print(f'Plain text: {plaintext}')发布于 2022-09-22 06:33:00
我似乎无法找出您的代码的问题,但我可以建议使用密码模块的另一种方法吗?
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from base64 import urlsafe_b64encode
from socket import getfqdn
from os.path import expanduser
print(expanduser("~")) # Get current users home directory, works for linux too, example: C:\Users\username
print(getfqdn()) # Get fully qualified domain name, works for linux too, example: user.company.com
KDF = PBKDF2HMAC(algorithm=hashes.SHA512(),length=32,salt=urlsafe_b64encode(expanduser("~").encode()),iterations=400000,backend=default_backend())
FERNET_KEY = urlsafe_b64encode(KDF.derive(getfqdn().encode()))
def encryptString(string: str) -> str:
cipher: Fernet = Fernet(FERNET_KEY)
return(cipher.encrypt(string.encode()).decode())
def decryptString(string: str) -> str:
cipher: Fernet = Fernet(FERNET_KEY)
return(cipher.decrypt(string.encode()).decode())
ciphertext = encryptString("Python")
plaintext = decryptString(ciphertext)
print(f'Cipher text: {ciphertext}')
print(f'Plain text: {plaintext}')结果:
Cipher text: gAAAAABjK_6v7Wg...truncated...Q8k8HoVA==
Plain text: Python我使用扩展用户作为salt来生成一个包含400.000次迭代的密钥。然后使用派生函数和getfqdn作为密码来生成实际的密钥。
我不对任何丢失的数据或错误的使用承担任何责任。这纯粹是演示如何使用选定的模块加密字符串。
如果您正在使用Windows,则可以利用内置数据保护API (DPAPI)。必须使用pywin32安装pip install pywin32。
守则:
from win32crypt import CryptProtectData, CryptUnprotectData
def encryptString(string: str) -> str:
return(CryptProtectData(string.encode()))
def decryptString(string: str) -> str:
return(CryptUnprotectData(string)[1].decode())
ciphertext = encryptString("Python")
plaintext = decryptString(ciphertext)
print(f'Cipher text: {ciphertext}')
print(f'Plain text: {plaintext}')结果:
Cipher text: b'\x01\x00\x00\x00\xd0...truncated ...\xeei\x1bI\xd9\x14\x00\x00\x00*\xe0\xc61P\xd0 \x1f3\n\xfb\xdb\x1d\x7fC7\nwL_'
Plain text: Pythonhttps://stackoverflow.com/questions/73809889
复制相似问题