簡體   English   中英

Python-3.x - 將bytearray的字符串表示形式轉換回字符串

[英]Python-3.x - Converting a string representation of a bytearray back to a string

這里的背景故事有點冗長,但基本上我想采用像b'\\x04\\x0e\\x1d'這樣的字符串並將其轉換回bytearray。

我正在研究一次性填充的基本實現,其中我采用明文A和共享密鑰B來生成符合等式A⊕B=C的密文C 然后我用公式C⊕B=A反轉過程。

我已經發現了很多python3函數來將字符串編碼為字節然后xor字節,如下所示:

def xor_strings(xs, ys):
    return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys)).encode()

xor_strings()調用然后返回一個bytearray:

print( xor_strings("foo", "bar"))

但是當我將它打印到屏幕上時,我所展示的實際上是一個字符串。 所以我假設python只是在bytearray上調用一些str()函數,我得到的內容如下所示:

b'\\x04\\x0e\\x1d'

這就是問題所在。 我想從該字符串創建一個新的bytearray。 通常我會在bytearray上調用decode() 但是如果輸入'b'\\ x04 \\ x0e \\ x1d'作為輸入,python會將其視為字符串,而不是字節數組!

如何將b'\\x04\\x0e\\x1d'這樣的字符串作為用戶輸入並將其轉換回bytearray?

如評論中所述,使用base64以文本形式發送二進制數據。

import base64

def xor_strings(xs, ys):
    return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys)).encode()

# ciphertext is bytes
ciphertext = xor_strings("foo", "bar")
# >>> b'\x04\x0e\x1d'

# ciphertext_b64 is *still* bytes, but only "safe" ones (in the printable ASCII range)
ciphertext_b64 = base64.encodebytes(ciphertext)
# >>> b'BA4d\n'

現在我們可以傳輸字節:

# ...we could interpret them as ASCII and print them somewhere
safe_string = ciphertext_b64.decode('ascii')
# >>> BA4d

# ...or write them to a file (or a network socket)
with open('/tmp/output', 'wb') as f:
    f.write(ciphertext_b64)

收件人可以通過以下方式檢索原始郵件:

# ...reading bytes from a file (or a network socket)
with open('/tmp/output', 'rb') as f:
    ciphertext_b64_2 = f.read()

# ...or by reading bytes from a string
ciphertext_b64_2 = safe_string.encode('ascii')
# >>> b'BA4d\n'

# and finally decoding them into the original nessage
ciphertext_2 = base64.decodestring(ciphertext_b64_2)
# >>> b'\x04\x0e\x1d'

當然,在將字節寫入文件或網絡時,首先將它們編碼為base64是多余的。 如果它是唯一的文件內容,您可以直接寫/讀密文。 只有當密文成為更高結構(JSON,XML,配置文件......)的一部分時,才需要將其編碼為base64。

關於使用“解碼”和“編碼”一詞的說明。

  • 字符串進行編碼意味着將其從抽象含義(“字符列表”)轉換為可存儲表示(“字節列表”)。 此操作的確切結果取決於正在使用的字節編碼。 例如:

    • ASCII編碼將一個字符映射到一個字節(作為權衡,它不能映射Python字符串中可能存在的所有字符)。
    • UTF-8編碼將一個字符映射到1-5個字節,具體取決於字符。
  • 解碼字節數組意味着再次將其從“字節列表”轉回“字符列表”。 這當然需要事先知道字節編碼最初是什么。

上面的ciphertext_b64是一個字節列表,在Python控制台上表示為b'BA4d\\n'

它的字符串等效, safe_string ,當打印到控制台時看起來非常相似'BA4d\\n' ,因為base64是ASCII的子集。

然而,數據類型仍然根本不同。 不要讓控制台輸出欺騙你。

僅回答最后一個問題。

>>> type(b'\x04\x0e\x1d')
<class 'bytes'>
>>> bytearray(b'\x04\x0e\x1d')
bytearray(b'\x04\x0e\x1d')
>>> type(bytearray(b'\x04\x0e\x1d'))
<class 'bytearray'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM