【问题标题】:decrypt/encrypt xor algorithm in CC中的解密/加密异或算法
【发布时间】:2021-05-16 11:33:02
【问题描述】:

在这里,我正在尝试使用 XOR 加密消息。但是,当我运行程序时,我得到了奇怪的输出(随机输出)。我想我在这里遗漏了一些东西。

我的代码示例:

/*
* Description: Decipher the message using XOR and print it.
* Parameters:
*   cipher: The cipher of the message (With the key embedded at the start)
*   keyLength: The length of the key at the start of the message
*Return:
*   None.
*Note:
    Do not use any additional variables for this challenge.
*/

void print_cipher_message(unsigned char cipher[], int keyLength) {
    // TODO: complete the function
    //keyLength = 3;
    for (int i = 0; i < strlen(cipher) && i <= keyLength; i++) {
        
            i % keyLength;
    
        cipher[i] = cipher[i] ^ keyLength;
      // i% keyLength;// i % ;//cipher[i] % sizeof(keyLength);
        
        printf("%c", cipher);
    }

}


int main() {
    
    unsigned char cipher[] = "\x12\x56\xd4\x61\x26\xbb\x7b\x3a\xbd\x7c\x31\xf4\x61\x3e\xbb\x65\x25\xf4\x7b\x25\xf4\x73\x76\x97\x40\x1f\x99\x57";
    int keyLength = 3;


    //print the cipher message
    print_cipher_message(cipher, keyLength);
    
    return 0;
}

预期结果如下:

/*
    EXAMPLE:
    cipher="\x31\xf4\x61\x7a\x33\xb8\x7e\x39\xf4\x65\x39\xa6\x7e\x32\xf5\x33"
    keyLength=3;

    then the cipher is:
    "\x31\xf4\x61\x7a\x33\xb8\x7e\x39\xf4\x65\x39\xa6\x7e\x32\xf5\x33"
    ^----Key-----^^-------------------Message------------------------^

    */

非常感谢您的帮助。谢谢。

【问题讨论】:

  • 你对i % keyLength;这行有什么期望?此外,您与keyLength 进行异或,即 3,所以实际上只是翻转最低两位
  • 您不能将strlen 与理论上可能在中间包含零字节的内容一起使用。
  • 我希望这是一个玩具项目,因为 XOR 本质上是不安全的,除非 key-length >= message-length(即使这样,这种方法也存在问题)。
  • @EugeneSh。没有传递长度参数,所以它必须是一个以 NUL 结尾的字符串。
  • @WillisBlackburn 然后整个练习就被打破了。纯文本字符很可能与关键字符在这里和那里重叠,从而导致密文中出现零。

标签: c xor


【解决方案1】:

我马上看到的几个问题:

  1. 您要求printf 打印char (%c),但传递的是指向char 而不是char 的指针。

  2. 有一行i % keyLength 不做任何事情,它只是执行计算并丢弃结果。

此外,您每次通过循环都调用strlen,这会有点贵。

我认为您应该在这里做的是有两个索引,一个在 0 到 keyLength 的范围内循环,另一个遍历字符串以进行编码(从索引 keyLength 开始)。当第二个索引到达字符串末尾时,函数结束。

【讨论】:

    【解决方案2】:

    首先,您需要正确理解问题。您的问题表明密钥嵌入在密码的开头,其长度为keyLength。因此,您需要将这部分分开并与密码的其余部分进行异或。

    代码应该是这样的:

    void print_cipher_message(unsigned char cipher[], int keyLength) {
        for (int i = 0; i < strlen((char*)cipher) - keyLength; i++) {
            cipher[i + keyLength] = cipher[i + keyLength] ^ cipher[i % keyLength];
        }
    
        printf("%s", cipher + keyLength);
    }
    

    我在没有调试的情况下很快就写好了,所以它可能有错误。此外,问题本身并不正确。它需要密码长度,我们不能真正使用strlen()

    【讨论】:

    • 由于数组不是以 NUL 结尾的字符串,并且可能在密文中的任何位置包含 NUL 字节,因此不应使用 strlen。相反,数组的大小应该从main 传递给函数。
    • 非常感谢。我不太了解算法,而且我对这门语言还很陌生。如果我理解正确,这里的密钥嵌入到密文的第一个,而密码本身是用该密钥解密的?
    • @Bodo 似乎函数体是预定义的,这就是我告诉问题不正确的原因。
    • @hadeelKh 是的,但是您所说的内容是有问题的。仔细阅读。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多