字符串加密解密
/**
* 原理 a = 1111;//二进制(需加密的数据)
* b = 1010;//二进制(密码)
* # 加密
* 加密运算:a = a ^ b;
* a = 1111 ^ 1010
* 加密后:a = 0101
* # 解密
* 解密运算:a = a ^ b;
* a = 0101 ^ 1010
* 解密后的:a = 1111
*/
#include <stdio.h>
#include <string.h>
/**
* src : helloworldhelloworld
* 加密: AccowoAccowoAccowoAc
*/
/**
* @brief 加密数据and解密数据
* @param
* @src 要加密的数据
* @srclen 数据的长度
* @passworld 加密的密码
* @passwordLen 密码的长度
* @note 传入长度而不用内部strlen的原因是防止加密后的数据出现'\0'的情况,导致strlen计算长度错误
* @retval 加密后的字符串
*/
char* encryptData(char *src, int srcLen, const char *password, int passwordLen)
{
int i;
int j;
for (j = 0; j < srcLen / passwordLen; j++)
{
for (i = 0; i < passwordLen; i++)
{
//密码加密到src上
src[j * passwordLen + i] ^= password[i];
}
}
// src的长度不是密码长度整数倍的情况,处理剩余的数据
if ((j = srcLen/passwordLen * passwordLen) != srcLen)
{
for (i = j; i < srcLen; i++)
{
src[i] ^= password[i - j];
}
}
return src;
}
void test(const char *testName, char *src, int srcLen, const char *password, int passwordLen){
printf("=========%s=========\n", testName);
printf("src:\n%s\n", src);
//加密
encryptData(src, srcLen, password, passwordLen);
printf("encrypt src:\n%s\n", src);
//解密
encryptData(src, srcLen, password, passwordLen);
printf("After decryption---src:\n%s\n", src);
}
int main(){
char src[] = "hello world";
char password[] = "accowo";
test("数据长度大于密码长度",src, sizeof(src) / sizeof(*src) - 1,
password, sizeof(password) / sizeof(*password) - 1);
strcpy(src, "hell6");
test("数据长度等于密码长度",src, sizeof(src) / sizeof(*src) - 1,
password, sizeof(password) / sizeof(*password) - 1);
strcpy(src, "he");
test("数据长度小于密码长度",src, sizeof(src) / sizeof(*src) - 1,
password, sizeof(password) / sizeof(*password) - 1);
return 0;
}
执行结果
=========数据长度大于密码长度=========
src:
hello world
encrypt src:
═╚O
╚
After decryption---src:
hello world
=========数据长度等于密码长度=========
src:
hell6
encrypt src:
═╚Ao
╚
After decryption---src:
hell6
=========数据长度小于密码长度=========
src:
he
encrypt src:
═c╚Ao
╚
After decryption---src:
he