我创建了一些代码,可以通过将明文和密钥转换为ascii代码并将它们相乘来加密文本。我知道它不安全但我正在为密码学课做这件事。
这是我的代码
plaintext = input(">> ")
key = input("key: ")
def ascii(text):
x = 0
for i in range(len(text)):
x += ord(text[i])*2**(8 * (len(text) -i -1 ))
#end
return x
#end
ascii_pt = ascii(plaintext)
ascii_key = ascii(key)
# debug
#print(ascii_pt)
#print(ascii_key)
encoded = ascii_pt * ascii_key
print(encoded)
我尝试过encoded / ascii_key
无济于事。任何帮助都会很棒!
修改
decoded = int(encoded / ascii_key)
print(chr(decoded))
这适用于小字符,但无法解码大字符:L
答案 0 :(得分:0)
必须知道编码文本的原始长度才能对其进行解码。可能有某种方法可以从编码值中推断出这一点,但我想不到一个总会有效的方法。
请注意,此代码仅适用于8位字符(如ASCII或ISO-Latin)。鉴于这种约束,它似乎在我的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