字符串加密解密
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串加密解密相关的知识,希望对你有一定的参考价值。
字符串加密(指定加密密钥)
如字符串"Good good study,day day up! You can you up,no can no bibi!",加密密钥为"marchfour",对字符串进行加密
原理很简单,就是字符之间的异或
错误的代码:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 void encrypt_decode(char *str, char *password) 5 { 6 int len_str = strlen(str); 7 int len_password = strlen(password); 8 if (len_str%len_password == 0) 9 { 10 for (int i = 0; i < len_str / len_password; i++) 11 { 12 for (int j = 0; j < len_password; j++) 13 { 14 str[i*len_password + j] ^= password[j]; 15 } 16 } 17 } 18 else 19 { 20 for (int i = 0; i < len_str / len_password; i++) 21 { 22 for (int j = 0; j < len_password; j++) 23 { 24 str[i*len_password + j] ^= password[j]; 25 } 26 } 27 for (int k = 0; k < len_str%len_password; k++) 28 { 29 str[k + len_str / len_password*len_password] ^= password[k]; 30 } 31 } 32 } 33 void main() 34 { 35 char str[100] = "Good good study,day day up! You can you up,no can no bibi!"; 36 char password[30] = "marchfour"; 37 printf("加密前:%s\n", str); 38 encrypt_decode(str, password); 39 printf("加密后:%s\n", str); 40 encrypt_decode(str, password); 41 printf("解密后:%s\n", str); 42 system("pause") 43 }
输出截图:
修改后的代码:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 void encrypt_decode(char *str, char *password, int length) 5 { 6 int len_str = length; 7 int len_password = strlen(password); 8 if (len_str%len_password == 0) 9 { 10 for (int i = 0; i < len_str / len_password; i++) 11 { 12 for (int j = 0; j < len_password; j++) 13 { 14 str[i*len_password + j] ^= password[j]; 15 } 16 } 17 } 18 else 19 { 20 for (int i = 0; i < len_str / len_password; i++) 21 { 22 for (int j = 0; j < len_password; j++) 23 { 24 str[i*len_password + j] ^= password[j]; 25 } 26 } 27 for (int k = 0; k < len_str%len_password; k++) 28 { 29 str[k + len_str / len_password*len_password] ^= password[k]; 30 } 31 } 32 } 33 void main() 34 { 35 char str[100] = "Good good study,day day up! You can you up,no can no bibi!"; 36 char password[30] = "marchfour"; 37 int length = strlen(str); 38 printf("加密前:%s\n", str); 39 encrypt_decode(str, password, length); 40 printf("加密后:%s\n", str); 41 encrypt_decode(str, password, length); 42 printf("解密后:%s\n", str); 43 system("pause"); 44 }
输出截图:
说明:
1.第一段代码错误的原因?因为对字符串加密时,可能加密后的字符是“\0”,但是在解密时,字符串的长度是遇到“\0”就结束,所以解密的长度会出现问题
以上是关于字符串加密解密的主要内容,如果未能解决你的问题,请参考以下文章