Python为crypt resu添加了额外的

2024-06-28 15:19:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个带有令牌的API,以便在Raspberry Pi和web服务器之间进行通信。现在我正尝试用Python生成一个令牌。你知道吗

from Crypto.Cipher import AES
import base64
import os
import time
import datetime
import requests
BLOCK_SIZE = 32
BLOCK_SZ = 14

#!/usr/bin/python
salt = "123456789123" # Zorg dat de salt altijd even lang is! (12 Chars)
iv = "1234567891234567" # Zorg dat de salt altijd even lang is! (16 Chars)


currentDate = time.strftime("%d%m%Y")
currentTime = time.strftime("%H%M")
PADDING = '{'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
secret = salt + currentTime
cipher=AES.new(key=secret,mode=AES.MODE_CBC,IV=iv)
encode = currentDate
encoded = EncodeAES(cipher, encode)

print (encoded)

问题是exta b'添加到每个编码字符串的脚本输出。。每一端都有一个“

C:\Python36-32>python.exe encrypt.py
b'Qge6lbC+SulFgTk/7TZ0TKHUP0SFS8G+nd5un4iv9iI='

C:\Python36-32>python.exe encrypt.py
b'DTcotcaU98QkRxCzRR01hh4yqqyC92u4oAuf0bSrQZQ='

希望有人能解释出哪里出了问题。你知道吗

修复!

我能把它解码成utf-8格式。你知道吗

sendtoken = encoded.decode('utf-8')

Tags: lambdaimportsizetimedeblockdatencrypt
1条回答
网友
1楼 · 发布于 2024-06-28 15:19:30

您正在运行python3.6,它对字符串文本使用Unicode(UTF-8)。我希望EncodeAES()函数返回一个ASCII字符串,Python通过在b前面加上它打印的字符串文本来指示它是bytestring而不是Unicode字符串。你知道吗

您可以将输出post Python中的b去掉,也可以print(str(encoded)),因为ASCII是有效的UTF-8

编辑:

您需要做的是将bytestring解码为UTF-8,如答案和上面的评论所述。我对str()为您进行转换的看法是错误的,您需要在希望打印的bytestring上调用decode('UTF-8')。将字符串转换为内部UTF-8表示形式,然后正确打印。你知道吗

相关问题 更多 >