異或運算:^
定義:它的定義是:兩個值相同時,返回false,否則返回true。也就是說,XOR可以用來判斷兩個值是否不同。
特點:如果對一個值連續做兩次 XOR,會返回這個值本身。
1010 ^ 1111 // 第一次異或后結果:0101 0101 ^ 1111 // 第二次異或后結果:1010
上面代碼中,原始值是1010,再任意選擇一個值(上例是1111),做兩次 XOR,最后總是會得到原始值1010。這 在數學上是很容易證明的。
加密應用:
XOR 的這個特點,使得它可以用於信息的加密。
message XOR key // cipherText cipherText XOR key //message
上面代碼中,原始信息是message,密鑰是key,第一次 XOR 會得到加密文本cipherText。對方拿到以后,再用 key做一次 XOR 運算,就會還原得到message
c語言實現:
#include <stdio.h> #define key 0x86 int main(int argc, char *argv[]) { char text[100]; int i,j; for(i=0;i<100;i++){ text[i]=getchar(); if(text[i]=='\n'){ text[i]='\0'; break; } } for(j=0;j<i;j++){ text[j]=text[j] ^ key; } puts(text); for(j=0;j<i;j++){ text[j]=text[j] ^ key; } puts(text); return 0; }
或者:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define KEY 0x86 int main() { char p_data[16] = {"Hello World!"}; char Encrypt[16]={0},Decode[16]={0}; int i; for(i = 0; i < strlen(p_data); i++) { Encrypt[i] = p_data[i] ^ KEY; } for(i = 0; i < strlen(Encrypt); i++) { Decode[i] = Encrypt[i] ^ KEY; } printf("Initial date: %s\n",p_data); printf("Encrypt date: %s\n",Encrypt); printf("Decode date: %s\n",Decode); return 0; }