C/C++ code#include
#include
#include
char* encrypt(char* source, char* pass)
{
int source_length = strlen(source);
int pass_length = strlen(pass);
char* tmp_str = (char*)malloc((source_length + 1) * sizeof(char));
memset(tmp_str, 0, source_length + 1);
for(int i = 0; i < source_length; ++i)
{
tmp_str[i] = source[i]^pass[i%pass_length];
if(tmp_str[i] == 0) // 要考虑到XOR等于0的情况,如果等于0,就相当
{ // 于字符串就提前结束了, 这是不可以的。
tmp_str[i] = source[i]; // 因此tmp_str[i]等于0的时候,保持原文不变
}
}
tmp_str[source_length] = 0;
return tmp_str;
}
int main(int argc, char* argv[])
{
char* s = "There is a kind of hush all over the world tonight...";
char* pass = "hello";
char* encrypted_text = encrypt(s, pass);
printf("Encrypted text is:\n%s\n", encrypted_text);
char* decrypted_text = encrypt(encrypted_text, pass);
printf("Decrypted text is:\n%s\n", decrypted_text);
free(encrypted_text);
free(decrypted_text);
return 0;
}
// 输出结果:
//Encrypted text is:
//<
//
//HLHH
//
//LL L
//L
//ELoFKB
//Decrypted text is:
//There is a kind of hush all over the world tonight...