Vigenere密码解密问题

问题描述 投票:0回答:1
key = "password"
def cipher(text): #my example cipher method
    encoded_chars = []
    for i in range(len(text)):
        key_c = key[i % len(key)]
        encoded_c = chr(ord(text[i]) + ord(key_c) % 256)
        encoded_chars.append(encoded_c)
    encoded_string = ''.join(encoded_chars)
    return (encoded_string)


def decipher(text):
    dec = []
    text = base64.urlsafe_b64encode(b"'{text}'").decode()
    print('text')
    for i in range(len(text)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(text[i]) - ord(key_c)) % 256)
        dec.append(text)
    return str(dec_c)
    enter code here
print(decipher("test"))

用vigenere密码成功加密后,我得到的是这样的:b'\xc2\xbd\xc2\xb8\xc3\x83\xc3\x80'我想使用上面的代码解密此字符串,然后将其转换回文本“密码”,但是当我尝试解密文本时,它会留下另一个编码字符串。有人可以解释我的解密错误吗?

python encryption cypher encode
1个回答
0
投票

尚不清楚您要使用base64库做什么。另外,您在解密方法中混合了一些变量:

    dec.append(text) # text is the passed in argument.
                     # Why append it to the result
return str(dec_c)    # this is the last element in the loop
                     # why return this rather than the list you made above?

以上两件事都没有多大意义。也许像这样的事情会使它朝着正确的方向发展:

key = "password"
def cipher(text): #my example cipher method
    encoded_chars = []
    for i in range(len(text)):
        key_c = key[i % len(key)]
        encoded_c = chr(ord(text[i]) + ord(key_c) % 256)
        encoded_chars.append(encoded_c)
    encoded_string = ''.join(encoded_chars)
    return (encoded_string)


def decipher(text):
    dec = []
    for i in range(len(text)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(text[i]) - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)

plain = "some text to encrypt"

encrypted = cipher(plain)
print("encrypted: ", encrypted)

decrypted = decipher(encrypted)   
print("decrypted: ", decrypted)

打印:

encrypted:  ãÐàØã×ÜäçâÔàÇâÚãç
decrypted:  some text to encrypt
© www.soinside.com 2019 - 2024. All rights reserved.