基于异或,取反和循环移位实现一个简单的加密解密函数

// 字节循环右移
unsigned char RorByte(unsigned char bData, size_t shift)
{
	unsigned char temp = bData >> (8 - shift);
	bData = bData << shift;
	bData = bData | temp;
	return bData;
}

// 加密函数:先与密钥异或,然后取反,然后右移3位
void NaiveEncrypt(void *pData, size_t byteDataLen, const void *pKey, const size_t byteKeyLen)
{
    size_t uDataIndex = 0, uKeyIndex = 0;
    for (; uDataIndex < byteDataLen; uDataIndex++)
    {
        ((char *)pData)[uDataIndex] = ((char*)pData)[uDataIndex] ^ ((char *)pKey)[uKeyIndex];
		((char *)pData)[uDataIndex] = ~((char *)pData)[uDataIndex];
		RorByte(((unsigned char *)pData)[uDataIndex], 3);
		uKeyIndex++;
        if (uKeyIndex == byteKeyLen) uKeyIndex = 0;
    }	
}

// 解密函数:先右移5位,再取反,在与密钥异或
void NaiveDecrypt(void *pData, size_t byteDataLen, const void *pKey, const size_t byteKeyLen)
{
	size_t uDataIndex = 0, uKeyIndex = 0;
	for (; uDataIndex < byteDataLen; uDataIndex++)
	{
		RorByte(((unsigned char *)pData)[uDataIndex], 5);
		((char *)pData)[uDataIndex] = ~((char *)pData)[uDataIndex];
		((char *)pData)[uDataIndex] = ((char *)pData)[uDataIndex] ^ ((char *)pKey)[uKeyIndex];
		uKeyIndex++;
		if (uKeyIndex == byteKeyLen) uKeyIndex = 0;
	}
}

使用起来也是非常简单

int main()
{
	// 这里用字符串演示,实际上可以加密任意字节流
	char data[] = "some plain text";
	size_t dataLen = strlen(data);
	char key[] = "123456";
	size_t keyLen = strlen(key);
	printf("加密前\n");
	for (size_t i = 0; i < dataLen; i++)
	{
		printf("%02X ", (unsigned char)data[i]);
	}
	printf("\n\n");
	// 加密
	NaiveEncrypt(data, dataLen, key, keyLen);
	printf("加密后\n");
	for (size_t i = 0; i < dataLen; i++)
	{
		printf("%02X ", (unsigned char)data[i]);
	}
	printf("\n\n");
	// 解密
	NaiveEncrypt(data, dataLen, key, keyLen);
	printf("解密后\n");
	for (size_t i = 0; i < dataLen; i++)
	{
		printf("%02X ", (unsigned char)data[i]);
	}
	printf("\n\n");
	
	
    return 0;
}


基于异或,取反和循环移位实现一个简单的加密解密函数_第1张图片

你可能感兴趣的:(C/C++)