1

使用 XOR 加密时某些字符为空的原因是什么?此外,解密时如何补偿?

例如:

....
void basic_encrypt(char *to_encrypt) {
    char c;
    while (*to_encrypt) {
        *to_encrypt = *to_encrypt ^ 20;
        to_encrypt++;
    }
}

将为角色返回“无” k。显然,字符衰减对于解密是有问题的。

我认为这是由位运算符引起的,但我对二进制不是很好,所以我想知道是否有人可以解释。

在这种情况下,它是否将元素转换k为一些无空格的 ASCII 字符?这可以通过选择一些 y < x < z 运算符来补偿,其中 x 是运算符?

最后,如果没有得到补偿,除了猜测和检查之外,还有没有现实的填空解密策略呢?

4

3 回答 3

6

'k'具有 ASCII 值107 = 0x6B200x14,所以

'k' ^ 20 == 0x7F == 127

如果您的字符集与 ASCII 兼容。127\DELASCII码,是不可打印的字符,打印出来就不会显示。

于 2013-01-09T21:12:29.213 回答
3

You will have to know the difference between bytes and characters to understand which is happening. On the one hand you have the C char type, which is simply a presentation of a byte, not a character.

In the old days each character was mapped to one byte or octet value in a character encoding table, or code page. Nowadays we have encodings that take more bytes for certain characters, e.g. UTF-8, or even encodings that always take more than one byte such as UTF-16. The last two are unicode encodings, which means that each character has a certain number value and the encoding is used to encode this number into bytes.

Many computers will interpret bytes in ISO/IEC 8859-1 or Latin-1, sometimes extended by Windows-1252. These code pages have holes for control characters, or byte values that are simply not used. Now it depends on the runtime system how these values are handled. Java by default substitutes an ? character in place of the missing character. Other runtimes will simply drop the value or - of course - execute the control code. Some terminals may use the ESC control code to set the color or to switch to another code page (making a mess of the screen).

This is why ciphertext should be converted to another encoding, such as hexadecimals or Base64. These encodings should make sure that the result is readable text. This takes care of the cipher text. You will have to choose a character set for your plain text too, e.g. simply perform ASCII or UTF-8 encoding before encryption.

于 2013-01-09T21:23:07.900 回答
1

从加密中获得零值并不重要,因为一旦您使用相同的异或密钥重新异或,您就会获得原始值。

value == value
value XOR value == 0 [encryption]
( value XOR value ) XOR value == value [decryption]

如果您使用的是零终止字符串机制,那么您有两种主要策略来防止“字符退化”

  • 在加密之前存储字符串的长度,并确保在解密时至少解密该数量的字符
  • 解码字符检查零字符
于 2013-01-09T21:11:49.000 回答