實現字符串的加密與解密


//實現字符串的加密與解密
//加密方式:將字符串中每個字符加上它在字符中的位置和一個偏移量 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM