虽然我经常使用C ++,但我正在努力克服C差异(主要是在字符串中)。
你能否告诉我一个简单的单一功能,它使用XOR比较用密钥加密消息。
谢谢你
编辑: 密钥和消息都是char *
答案 0 :(得分:9)
好吧,我在这里乱了一会儿,想出了这个(只是模糊地测试过):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * xorencrypt(char * message, char * key) {
size_t messagelen = strlen(message);
size_t keylen = strlen(key);
char * encrypted = malloc(messagelen+1);
int i;
for(i = 0; i < messagelen; i++) {
encrypted[i] = message[i] ^ key[i % keylen];
}
encrypted[messagelen] = '\0';
return encrypted;
}
int main(int argc, char * argv[]) {
char * message = "test message";
char * key = "abc";
char * encrypted = xorencrypt(message, key);
printf("%s\n", encrypted);
free(encrypted);
return 0;
}
请注意,函数xorencrypt
会分配并返回一个新字符串,因此调用者有责任在完成后释放它。
答案 1 :(得分:4)
C非常接近Assembler,所以这个例子很简短:
while (*string)
*string++ ^= key;
假设char *string;
和char key
。
答案 2 :(得分:3)
为了它的价值,结合@ ott--&amp;的答案。 @Tim组建Xortron。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *xor(char *string, const char *key)
{
char *s = string;
size_t length = strlen(key), i = 0;
while (*s) {
*s++ ^= key[i++ % length];
}
return string;
}
int main(int argc, char **argv)
{
const char *key = "abc";
if (argc < 2) {
fprintf(stderr, "%s: no input\n", argv[0]);
return EXIT_FAILURE;
}
printf("%s\n", xor(xor(argv[1], key), key));
return EXIT_SUCCESS;
}