关于加密和解密问题,有的加密算法是不存在解密算法的(缘由就是加密算法的不可逆性,即没法经过算法将密文还原),有的加密存在解密算法(缘由是其加密过程是可逆的,便可以经过逆向算法将密文还原)。然而单独的一种加密算法不必定可靠,这时能够将多种加密算法组合使用。至于相关的加密算法各位本身去了解。html
下面介绍一个简单的加密/解密算法实例,但愿对此加密解密算法有必定认识: ios
首先介绍加密算法: 主要加密计算为 '^' 缘由是 '^'运算是可逆的,如二进制数 1^0 = 1, 1^1 = 0; 0^1 = 1, 0^0 = 0;c++
因此 1 = 1^0^0,便是加密部分为 [1^0] = r, 解密部分为[r^0], 因此解密算法就是将密文与加密数据0在进行一次'^'运算,以此类推就能够实现多位二进制的加密解密。在计算执行的指令都是二进制数,这里就须要理解为何十进制和ASCII码一样能够使用'^'运算进行加密解密.`算法
c++源代码: windows
example_1:测试
#include <iostream> #define KEY 1313113 using namespace std; //加密算法 int encrypt(int src_pass, int key){ return src_pass^key; } //解密算法 int decrypt(int des_pass, int key){ return des_pass^key; } int main(){ int src_pass = 2000; cout<<src_pass<<endl; int des_pass = encrypt(src_pass, KEY); cout<<des_pass<<endl; int result = decrypt(des_pass, KEY); cout<<result<<endl; return 0; }
example2:加密
#include <iostream> #include <windows.h> #define L 6 using namespace std; //原始数据 int mess[L] = {-23, -28, -19, -19, -18, -10}; //对原始数据进行加密 //加密算法 void encrypt(char *arr, int len){ for(int i = 0; i < len; i++){ arr[i] |= -0x80; //但愿读者了解ascii^-0x80,这里等价于 ascii^0x80 arr[i] ^= 0x1; } } //解密算法 void decrypt(char *arr, int len){ for(int i = 0; i < len; i++){ arr[i] ^= 0x1; arr[i] ^= 0x80; //对ascii最高位进行了加密'^'运算,固然也要进行解密'^'运算 } } bool judge(char* arr, int index){ if(index < 0){ return true; }else{ if((int)arr[index] == mess[index]){ judge(arr, index-1); }else{ return false; } } return true; } //测试用 void print_(char *arr, int len){ for(int i = 0; i < len; i++){ cout<<(int)arr[i]<<", "; } cout<<endl; } //测试用 string print(char *arr, int len){ string tmp = ""; for(int i = 0; i < len; i++){ tmp += arr[i]; } return tmp; } //测试时的源代码 int main() { char *arr = new char[L]; cout<<"please input the password: "; for(int i = 0; i < L; i++){ cin>>arr[i]; } string tmp = ""; tmp = print(arr, L); cout<<tmp<<endl; encrypt(arr, L); print_(arr, L); tmp = print(arr, L); cout<<tmp<<endl; decrypt(arr, L); tmp = print(arr, L); cout<<tmp<<endl; if(judge(arr, L-1)){ cout<<"you is the user, hello!!"<<endl; }else{ cout<<"you are not the user!!!"<<endl; } system("pause"); return 0; }但愿两个小例子,各位可以有所收获。