简体   繁体   English

Python3自定义解码

[英]Python3 custom decode

When i migrate my code from python2 to python3.My code is not producing desired result instead it generate error: code snippet and error log as shown below. 当我将代码从python2迁移到python3时,我的代码未产生期望的结果,而是生成错误:代码片段和错误日志,如下所示。

import os
import sys
import base64
def decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc)
    print(enc)
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        print(key_c)
        dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
        print(dec_c)
        dec.append(dec_c)
    return "".join(dec)

contents = "p6KisaignLOinZqgmqKin6OT0uTZ0tSTlaKmpI+klJ+loI"
decodedLicense = decode('crab',contents)

Error Log: 错误日志:

File "s.py", line 16, in decode
    dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
TypeError: ord() expected string of length 1, but int found

I have no idea if the final result is correct since you didn't indicate what the desired or expected output was in your question, which makes that very difficult to determine. 我不知道最终结果是否正确,因为您没有指出问题中期望的或期望的输出,这使得确定起来非常困难。

Anyhow, as I said in a comment, initially I was getting a different error complaining about the the length of contents having Incorrect padding , so the first thing I did was add something to fix that. 无论如何,正如我在评论说,最初我得到一个不同的错误抱怨的长度contentsIncorrect padding ,所以我做的第一件事就是添加了一些解决这个问题。 Afterwards. 然后。 I started getting the TypeError: ord() expected string of length 1, but int found exception you did mention in your question. 我开始得到TypeError: ord() expected string of length 1, but int found您在问题中确实提到的异常。

That was fixed by just using the bytes that base64.urlsafe_b64decode() returned direct and not trying to take their ord() . 通过仅使用base64.urlsafe_b64decode()直接返回的字节而不尝试获取其ord()

Here's code with these changes made that at least runs...: 这些更改的代码至少可以运行...:

import os
import sys
import base64

def decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc).decode('latin1')
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + enc[i] - ord(key_c)) % 256)  # ord(enc[i]) -> enc[i]
        dec.append(dec_c)

    return "".join(dec)

contents = "p6KisaignLOinZqgmqKin6OT0uTZ0tSTlaKmpI+klJ+loI"  # 46 chars

# Pad contents so its length is a multiple of 3 and it's valid Base64 data.
contents = contents + {0: '', 1: '==', 2: '='}[len(contents) % 3]

decodedLicense = decode('crab', contents)
print(decodedLicense)  # -> D0AOE.;Q?+9>70A=@!q?v`s120EB,23=B.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM