实现字符串的加密与解密

//实现字符串的加密与解密
//加密方式:将字符串中每个字符加上它在字符中的位置和一个偏移量 5
//列如:zhnglie中,第一个字符z在字符中的位置为0,那么对应密文是'm'+0+5

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 
 5 #define KEY 5      //偏移量 或者 是 密钥 以字符的方式来偏移   不要越界
 6                   //无符号char 型   0-255
 7 
 8 /**
 9  *加密传入的字符串
10  *参数1:要加密的字符串
11  *返回值:返回值加密后的字符串
12  */
13 
14  
15  //原函数
16 char * encrypt(char []);    //加密
17 
18 char * dencrypt(char []);   //解密
19 
20 int main()
21 {
22 
23     char password[50] = "123456";
24 
25     encrypt(password);
26     printf("加密后的字符串为:%s\n",password);
27 
28 
29     dencrypt(password);
30     printf("解密后的字符串为:%s\n",password);
31 
32 
33     return 0;
34 }
35 
36 //加密
37 char * encrypt(char password[])
38 {
39 
40     int i = 0;
41     int count = strlen(password);     //字符串的长度
42     for(i = 0;i <strlen(password); i++)
43     {
44         ////加密方式:将字符串中每个字符加上它在字符中的位置和一个偏移量 5
45         password[i] = password[i] + i + KEY;
46 
47     }
48     return password;
49 
50     //字符串最后的\0是否需要替换?----不需要
51 }
52 
53 //解密
54 char * dencrypt(char password[])
55 {
56 
57     int i = 0;
58     int count = strlen(password);     //字符串的长度
59     for(i = 0;i <strlen(password); i++)
60     {
61         ////加密方式:将字符串中每个字符加上它在字符中的位置和一个偏移量 5
62         password[i] = password[i] - i - KEY;
63 
64     }
65     return password;
66 
67     //字符串最后的\0是否需要替换?----不需要
68 }

 

posted on 2021-07-28 09:00  Bytezero!  阅读(1122)  评论(0编辑  收藏  举报