//偶然翻到一本很多年前的计算机教程,看到一段关于字符串加密的文字。当然,与现在
//计算机中加密的算法比起来显得过于简单,但对于C++的入门者,用C++实现一下,也很
//有趣。其基本原理:加密是将字符串中的每个字符的ASCII码值加上其所在位置值和整个
//字符串的长度值后替换原来的字符,形成一个新的变化了的字符串; 解密是加密的逆运
// 算。具体代码如下:
#include<iostream>
using namespace std;
#include<string>
string encryption(string strE) { //加密子程序
char temp;
for (int i = 0; i < strE.length(); i++) {
temp = strE[i];
temp = (int)temp + i + strE.length() / 2;
strE[i] = temp;
};
return strE;
}
string decryption(string strD) { //解密子程序
char temp;
for (int i = 0; i < strD.length(); i++) {
temp = strD[i];
temp = (int)temp - i - strD.length() / 2;
strD[i] = temp;
};
return strD;
}
int main() {
string a = "ABC123456789"; //运行示例
cout << "原始字符串: " << a << endl;
cout << "---------------------------" << endl;
string b = encryption(a);
cout << "加密后字符串:" << b << endl;
cout << "---------------------------" << endl;
cout << "解密后字符串:" << decryption(b) << endl;
cout << "---------------------------" << endl;
system("pause");
return 0;
}
//运行结果:
//原始字符串: ABC123456789
//-------------------------- -
//加密后字符串:GIK:<>@BDFHJ
//-------------------------- -
//解密后字符串:ABC123456789
//-------------------------- -
//请按任意键继续. . .