【问题标题】:Xor String Encryption/Decryption Output ErrorXor 字符串加密/解密输出错误
【发布时间】:2020-03-20 09:31:27
【问题描述】:

我正在尝试对 Python 中的字符串进行异或加密,但由于某种原因,我在终端中得到了这个奇怪的输出。尽管解密运行良好,但传输此数据似乎会导致错误。

第1行是明文字符串,2-3是输出的加密字符串,第4行是解密后的加密字符串,第5行是加密字符串的字节串。

Hello world!
<
    U
Hello world!
\x3c\x0\x1f\x18\x1b\x45\x4\x1b\x6\x9\x17\x55

这是加密在 Python 中的工作方式。

    def encrypt(self, plaintext: str) -> str:
        ciphertext = ""

        for i in range(len(plaintext)):
            current = plaintext[i]
            current_key = self.key[i%len(self.key)]
            ciphertext += chr(ord(current) ^ ord(current_key))

        return ciphertext

而真正调用加密方法如下。

            tmp2 = tmp2.strip('"')
            encryption = Encryption(self.key)
            encrypted_string = encryption.encrypt(tmp2)
            byte_string = encryption.to_byte_string(
                encrypted_string.encode('utf-8'))

我想要对输出的最后一行(字节字符串)做的是在 C++ 程序中解密这个异或字符串。然而,该程序的输出只是给了我一个 H.

#define POLY_ENGINE_KEY "test"

static string Decrypt(string ciphertext)
    {
        string plaintext = ciphertext;

        for (int i = 0; i < ciphertext.size(); i++)
            plaintext[i] = ciphertext[i] ^ POLY_ENGINE_KEY[i % (sizeof(POLY_ENGINE_KEY) / sizeof(char))];

        return plaintext;
    }

非常感谢您对此的帮助。

【问题讨论】:

    标签: python c++ encryption terminal xor


    【解决方案1】:

    ciphertext 的长度/大小很可能是 Decrypt() 中的 1。可能是因为该加密文本包含第二位的 0x00(NULL) ascii 值。因此,将该字符数组转换为 std::string (我猜你在代码中所做的)会生成一个只有一个字符的字符串。仅接受字符数组的字符串构造函数期望字符数组以 NULL 结尾。因此,当它在第二个位置遇到NULL 时,它会创建一个仅包含第一个字符的字符串。您可以尝试在字符数组旁边创建提及数组长度的字符串。像这些 -

    char ciphered_bytes[] = {....};
    int size = sizeof(ciphered_bytes)/sizeof(ciphered_bytes[0]);
    std::string ciphertext(ciphered_bytes, size); // instead of only ciphertext(ciphered_bytes)
    
    // Then call the Decrypt
    std::string plaintext = Decrypt(ciphertext);
    

    此外,您可能希望将Decrypt() 中的string 更改为const string&amp;,因为您没有更改输入字符串ciphertext

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多