C++字符串指针的加密
运行结果为什么是乱码,还有超出范围的模运算,我不太肯定是不是这样子简单地ascii码加减90
/*编制程序,将输入的一行字符(明文)加密和解密。加密时,明文的每个字符依次反复加上“4962873”中的数字,
如果范围超过ASCII码的032(空格)--122(’z’),则进行模运算。解密与加密的顺序相反。
编制加密和解密函数,打印各个过程的结果。
例如,加密:the result of 3 and 2 is not 8
(t)116+4,(h)104+9,(e)101+6,()32+2,(r)114+8,(e)1Ol+7,(s)115+3,
(u)117+4,(l)108+9,(t)116+6,( )32+2,(o)111+8,(f)102+7,( )32+3,(3)51+4,
()32+9,(a)97+6,(n)110+2,(d)100+8,( )32+7,(2)50+3,( )32+4,(i)105+9,(s)115+6,()32+2,(n)110+8,(o)111+7,(t)L16+3,( )32+4,(8)56+9
得到密文为:
xqk”zlvyuz”wm#7>gpl’s$ry”vvw$A
*/
#include
#include
using namespace std;
int main() {
//函数声明
int jia(char* str, int len, char* key);
char str[100];
char key[7] = { 4,9,6,2,8,7,3 };//密钥
char ch = 0;
int i = 0;
cout << "请输入一行字符来进行加密" << endl;
while ((ch=getchar()) != '\n') {
str[i] = ch;
i++;
}
int len = i;
jia(&str[i],len,&key[7]);
return 0;
}
int jia(char* str, int len,char* key) {
char *m = &str[0];//m为明文
char *n = &key[0];//n为密钥
char *res = new char[len];
for (int j = 0; j < len; j++) {
if (*(m + j) < ' ') {
*(res + j) = *(m + j) + 90 + *(n + j % 7);
}
if (*(m + j) > 'z') {
*(res + j) = *(m + j) - 90 + *(n + j % 7);
}
*(res + j) = *(m + j) + *(n + j % 7);
}
for (int j = 0; j < len; j++) {
cout << *(res + j);
}
return 0;
}
反反复复看,是指针的哪里出问题了啊
void jia(char *str, char *key, int len)
{
int i = 0;
char ch;
while (*str)
{
if (i == len)
i = 0;
ch = *str;
ch += key[i];
if (ch < ' ' || ch > 'z')
ch %= 'z';
*str = ch;
str++;
i++;
}
}
void jie(char *str, char *key, int len)
{
int i = 0;
char ch;
while (*str)
{
if (i == len)
i = 0;
ch = *str;
ch -= key[i];
if (ch < ' ' || ch > 'z')
ch %= 'z';
*str = ch;
str++;
i++;
}
}
int main()
{
// 函数声明
// int jia(char *str, int len, char *key);
char str[100];
char key[7] = {4, 9, 6, 2, 8, 7, 3}; // 密钥
// char ch = 0;
// int i = 0;
cout << "请输入一行字符来进行加密" << endl;
cin.getline(str, 100);
// while ((ch = getchar()) != '\n')
// {
// str[i] = ch;
// i++;
// }
// int len = i;
// jia(&str[i], len, &key[7]);
jia(str, key, 7);
cout << str << endl;
jie(str, key, 7);
cout << str;
return 0;
}
