編碼的文本的原始長度是爲了對其進行解碼是已知的。可能有某種方法可以從編碼值中推斷出來,但我想不出一直會奏效的。
請注意,此代碼僅適用於8位字符(如ASCII或ISO拉丁文)。考慮到這個約束,它似乎在Python 2.7.13和3.6.1中都能正常工作。
from __future__ import print_function
#plaintext = input(">> ")
#key = input("key: ")
# hardcode for testing
plaintext = 'All Your Base Are Belong To Us'
key = 'secret'
def encode(text):
x = 0
length = len(text)
for i in range(length):
x += ord(text[i]) * (2 ** (8 * (length-i-1)))
return x
def decode(value, length):
x = value
chars = []
for i in range(length-1, -1, -1):
shift = 2 ** (8 * (length-i-1))
mask = 0xff * shift
ch = (x & mask) // shift
chars.append(chr(ch))
x -= ch * shift
return ''.join(reversed(chars))
encode_key = encode(key)
encode_pt = encode(plaintext)
print('encode_key:', encode_key)
print('encode_pt:', encode_pt)
encoded = encode_pt * encode_key
print('encoded:', encoded)
print('encoded:', hex(encoded))
decoded = decode(int(encoded // encode_key), len(plaintext))
print('decoded:', decoded)
輸出:
encode_key: 126879297332596
encode_pt: 451536573816692702021325803632147813811389735036878033208035641604986227
encoded: 57290643205829835202633022894291838201313854456908334242503703290644426431694418155292
encoded: 0x1d7d9dc35af66f834a837b1a90a43725666b520a0d802d785d43d3b5213352eaa293171cL
decoded: All Your Base Are Belong To Us
的Python版本您使用的?另外,請提供[MCVE](https://stackoverflow.com/help/mcve)。如果出現錯誤,請提供樣本輸入,預期輸出,Stacktraces。 – Kraay89
另外,我認爲你不要正確使用'chr()',請閱讀[here](https://docs.python.org/2/library/functions.html#chr)。它旨在用於單個字符編碼,範圍爲[0,256] – Kraay89