對於C char *buf
,您可以使用Python list
編寫此代碼,對列表進行變異以使其包含結果,但更多Pythonic方法是創建包含xor編碼字節的新緩衝區並將其返回。
與舊版本的Python你創建的BUF串字符每一個的ord()
值的列表,XOR該列表與你的關鍵的元素,運用chr()
轉換整數回字符,然後join()
的個別字符回到一個單一的字符串。但是對於更現代的Python版本,您可以使用bytearray來完成大部分骯髒的工作。
#! /usr/bin/env python
def xor_crypt(key, buf):
return str(bytearray([i^key for i in bytearray(buf)]))
plaintxt = "Hello, world!"
key = 42
print 'original ', `plaintxt`
encrypted = xor_crypt(key, plaintxt)
print 'encrypted', `encrypted`
decrypted = xor_crypt(key, encrypted)
print 'decrypted', `decrypted`
輸出
original 'Hello, world!'
encrypted 'bOFFE\x06\n]EXFN\x0b'
decrypted 'Hello, world!'
但如果你真的要更加緊密地模仿C代碼和變異buf
,你可以很容易地做到這一點,就像這樣:
#! /usr/bin/env python
def xor_crypt(key, buf):
buf[:] = bytearray([i^key for i in buf])
plaintxt = "Hello, world!"
key = 42
buf = bytearray(plaintxt)
print 'original ', `buf`, str(buf)
xor_crypt(key, buf)
print 'encrypted', `buf`
xor_crypt(key, buf)
print 'decrypted', `buf`
輸出
original bytearray(b'Hello, world!') Hello, world!
encrypted bytearray(b'bOFFE\x06\n]EXFN\x0b')
decrypted bytearray(b'Hello, world!')
什麼是Python類型的輸入? –
您是否試圖遍歷數組並更改其內容? – ppalacios