【发布时间】: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 然后整个练习就被打破了。纯文本字符很可能与关键字符在这里和那里重叠,从而导致密文中出现零。