</pre><pre code_snippet_id="1666199" snippet_file_name="blog_20160429_2_7838133" name="code" class="cpp"><span style="font-size:24px;">字符串 加密解密的入门练习,</span>
#include<stdio.h>
#include<stdlib.h>
//按照密码加密
//文件加密
//字符串加密
char *stringEncrypt(char *password, char *string);
char *stringDecode(char *password, char *string);
#include "passw.h"
//异或的加密解密函数是一样的
//字符串加密
char *stringEncrypt(char *password, char *string)
{
int passLength = strlen(password);//获取加密长度
int stringLength = strlen(string);//获取字符串长度
if (stringLength%passLength == 0)//字符串长度是密码长度的整数倍
{
int times = stringLength/passLength;
for (int i = 0; i < times; i++)
{
for (int j = 0; j < passLength; j++)
{
string[i*passLength+j] ^= password[j];
//这里的下标计算画图很容易理解
}
}
}
else
{
int times = stringLength / passLength;
for (int i = 0; i < times; i++)
{
for (int j = 0; j < passLength; j++)
{
string[i*passLength + j] ^= password[j];
}
}
int lastLength = stringLength%passLength;
//不能整除的,也就是余数长度
for (int i = 0; i < lastLength; i++)
{
string[passLength*(stringLength / passLength) + i] ^= password[i];
//这里的解密要从前边已经整除完成的后一个位置开始,
//假如说stringLength = 10,passLength = 4;那么除不尽的加密就从下标8开始,
//(10 / 4)*4 = 8.
}
}
return string;
}
//字符串解密
char *stringDecode(char *password, char *string)
{
int passLength = strlen(password);//获取加密长度
int stringLength = strlen(string);//获取字符串长度
if (stringLength % passLength == 0)//字符串长度是密码长度的整数倍
{
int times = stringLength/passLength;
for (int i = 0; i < times; i++)
{
for (int j = 0; j < passLength; j++)
{
string[i*passLength + j] ^= password[j];
}
}
}
else
{
int times = stringLength / passLength;
for (int i = 0; i < times; i++)
{
for (int j = 0; j < passLength; j++)
{
string[i*passLength + j] ^= password[j];
}
}
int lastLength = stringLength%passLength;
//不能整除的,也就是余数长度
for (int i = 0; i < lastLength; i++)
{
string[passLength*(stringLength / passLength) + i] ^= password[i];
//这里的解密要从前边已经整除完成的后一个位置开始,
//假如说stringLength = 10,passLength = 4;那么除不尽的加密就从下标8开始,
//(10 / 4)*4 = 8.
}
}
return string;
}
//测试代码
#include<stdio.h>
#include<stdlib.h>
#include "passw.h"
void main()
{
char str[20] = "abcdefghijk";
char *password = "123";
printf("%s\n", stringEncrypt(password, str));
printf("%s\n", stringDecode(password, str));
system("pause");
}