1

假设我得到了字符串(应该是一个字节):

"b'YzJGNVltYzJGNVltOTBlbk5oZVdKdmRIcHpZWGxpYjNSNmMyRjVZbTkwZW5OaGVXSnZkSHB6WVhsaWIzUjZjMkY1WW05MGVnOTBlblJsYzNRPXNheWJvdHo='"

我想解码它,但它说它必须以字节为单位,所以我必须以某种方式把它变成这个

b'YzJGNVltYzJGNVltOTBlbk5oZVdKdmRIcHpZWGxpYjNSNmMyRjVZbTkwZW5OaGVXSnZkSHB6WVhsaWIzUjZjMkY1WW05MGVnOTBlblJsYzNRPXNheWJvdHo='

我正在开发一个聊天客户端,当它发送数据(字节)时,它会在通过服务器时以某种方式变成一个字符串,当它到达另一端时,它无法解码

ps:是ENCRYPT,解码会给出随机数和字母,客户端会解密

哦,而且,我真的不知道“=”符号是否应该存在,当我在我和我的朋友之间的测试中获得数据时,我得到了它就像那个字符串(顶部的那个)错误说它必须是字节。

客户端中的部分代码(就一行给大家看,其余保密):

base64.b64decode(that_string).decode('ascii')

它主要使用ascii,所以我认为这是对的,对吧?

更多信息:

base64.b64encode(message.encode('ascii'))

这里的消息是用于获取从另一端发送的字符串

Room.message(str(secretEncrypt(par, codes())))

我不知道我是怎么想念这个的,它在发送之前先将它 str =.= 好吧,它仍然需要将它转换为字节,我是怎么做到的?

4

3 回答 3

3

以下非常有效

>>> import base64
>>> s = "Hello StackOwerflow!"
>>> b = s.encode()
>>> c = base64.b64encode(b)
>>> c
b'SGVsbG8gU3RhY2tPd2VyZmxvdyE='
>>> b1 = base64.b64decode(c) 
>>> b1
b'Hello StackOwerflow!'
>>> b1.decode()
'Hello StackOwerflow!'

展示如何编码字符串

于 2013-02-03T21:07:53.130 回答
3

问题在这里:

Room.message(str(secretEncrypt(par, codes())))

secretEncrypt(...)返回字节,但随后您执行str(b"thereturnvalue")的操作不符合您的要求:

>>> my_bytes = b"abc"
>>> type(my_bytes)
<class 'bytes'>
>>> str(my_bytes)
"b'abc'"
>>> type(str(my_bytes))
<class 'str'>

它将你的字节的字符串表示(repr)放入一个字符串中,这就是为什么你的字符串以b"

如何最好地解决这个问题取决于周围的代码.. 要么:

  • 如果secretEncrypt函数返回字节,则Room.message也接受字节(并删除str(...)强制转换)。
  • 使secretEncrypt返回一个字符串,消除对str(...)演员表的需要
  • Least elegant solution: decode the bytes returned from secretEncrypt, turning it into a string. Something like this:

    encrypted = secretEncrypt(par, codes())
    Room.message(encrypted.decode("whatever-encoder-was-used"))
    

    Where whatever-encoding-was-used is the text encoding (likely utf-8 or ascii, but it is impossible to tell without seeing the rest of your code)

于 2013-02-03T21:55:01.397 回答
0

and i was right, no need to over think it

the string:

"b'YzJGNVltYzJGNVltOTBlbk5oZVdKdmRIcHpZWGxpYjNSNmMyRjVZbTkwZW5OaGVXSnZkSHB6WVhsaWIzUjZjMkY1WW05MGVnOTBlblJsYzNRPXNheWJvdHo='"

just need to be split, eg:

string = "b'YzJGNVltYzJGNVltOTBlbk5oZVdKdmRIcHpZWGxpYjNSNmMyRjVZbTkwZW5OaGVXSnZkSHB6WVhsaWIzUjZjMkY1WW05MGVnOTBlblJsYzNRPXNheWJvdHo='"
string = string.split("'")[1]

and that would get me a string without the b':

"YzJGNVltYzJGNVltOTBlbk5oZVdKdmRIcHpZWGxpYjNSNmMyRjVZbTkwZW5OaGVXSnZkSHB6WVhsaWIzUjZjMkY1WW05MGVnOTBlblJsYzNRPXNheWJvdHo="

then i just need to bytes it:

string = bytes(string, "ascii")

which would get me the b' outside the string:

b"YzJGNVltYzJGNVltOTBlbk5oZVdKdmRIcHpZWGxpYjNSNmMyRjVZbTkwZW5OaGVXSnZkSHB6WVhsaWIzUjZjMkY1WW05MGVnOTBlblJsYzNRPXNheWJvdHo="

ps: to everyone out there who say things about cracking my code, it got randoms mumbo jumbo things with the id dump into it, if you manage to crack it, it not much use and anyway, it just a chat client for a mini chatroom games for kids

于 2013-02-04T10:38:54.360 回答