首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Xor字符串加密/解密输出错误

Xor字符串加密/解密输出错误
EN

Stack Overflow用户
提问于 2019-11-25 13:52:22
回答 1查看 287关注 0票数 0

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

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

代码语言:javascript
复制
Hello world!
<
    U
Hello world!
\x3c\x0\x1f\x18\x1b\x45\x4\x1b\x6\x9\x17\x55

下面是Python中加密的工作原理。

代码语言:javascript
复制
    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

并且实际调用加密方法如下所示。

代码语言:javascript
复制
            tmp2 = tmp2.strip('"')
            encryption = Encryption(self.key)
            encrypted_string = encryption.encrypt(tmp2)
            byte_string = encryption.to_byte_string(
                encrypted_string.encode('utf-8'))

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

代码语言:javascript
复制
#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;
    }

非常感谢在这方面的一些帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-25 14:26:40

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

代码语言:javascript
复制
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&,因为您没有更改输入字符串ciphertext

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59025937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档