首页 > 解决方案 > 如何从文件中解码编码为base64的行?

问题描述

我需要解码文件中的行。

到目前为止,这是我的代码:

    def decode(self) -> list:
        """
        Decode file with key.

        For correct answer you have to convert file lines from base64 to utf-8.

        To decode one line you have to take a UNICODE value of a letter, subtract cipher step and take mod of 255.
        After that you have to convert that number back to a character.
        Example: key = 'test', decoded_data = "+%'"
        '+' -> (43 - 448) % 255 -> 'i' -> ... -> 'ice'

        :return: List of decoded lines
        """
        decoded_lines1 = []
        decoded_lines = []
        lines = self.read_code_from_file()
        for line in lines:
            decoded_lines.append(base64.b64decode(line).decode())
        for decoded_line in decoded_lines:
            for letter in decoded_line:
                decoded_lines1.append(chr((ord(letter) - sum([ord(i) for i in self.key])) % 255))
        return decoded_lines1

解码线:

[')-.7)-\x06\x06AOO', '-57)-0\x06\x06JASJAOOASJ', ')07)2\x06\x06AJSAJAJOAJJAAO',...]

由于某种原因,我的输出具有单独的所有字母,下面的输出的一小部分等于解码后的 decoded_lines 的第一个列表元素我的输出:

['-', '1', '2', ';', '-', '1', '\n', '\n', 'E', 'S', 'S', ...]

预期输出:

['-12;-1\n\nESS', ...]

有没有办法让行用逗号分隔而不是每个字母用逗号分隔?非硬编码密钥等于 1016。

标签: pythonbase64

解决方案


一行中只有一个单词吗?它是一个词吗?它由多个单词组成,然后您的第二个循环应该在单词上,然后第三个循环应该在字母上。代码应该是这样的

def decode(self) -> list:
        """
        Decode file with key.

        For correct answer you have to convert file lines from base64 to utf-8.

        To decode one line you have to take a UNICODE value of a letter, subtract cipher step and take mod of 255.
        After that you have to convert that number back to a character.
        Example: key = 'test', decoded_data = "+%'"
        '+' -> (43 - 448) % 255 -> 'i' -> ... -> 'ice'

        :return: List of decoded lines
        """
        decoded_lines1 = []
        decoded_lines = []
        lines = self.read_code_from_file()
        for line in lines:
            decoded_lines.append(base64.b64decode(line).decode())
        for decoded_line in decoded_lines:
            for word in decoded_line.split():
                docoded_word=''
                for letter in word:
                    docoded_word+=(chr((ord(letter) - sum([ord(i) for i in self.key])) % 255))
                decoded_lines1.append(docoded_word)
        return (decoded_lines1)

推荐阅读