C++异或加解密,把字符串加密为16进制字符串
char* XorEncryptToHex(const char* strPlainText)
{
if (strPlainText == nullptr)
{
return nullptr;
}
size_t length = strlen(strPlainText);
char* hexStr = new char[length * 2 + 1];
if (hexStr == nullptr)
{
return nullptr;
}
const unsigned char(&xorKey)[8] = {0xB2, 0x09, 0xBB, 0x55, 0x93, 0x6D, 0x44, 0x47};
const size_t xorKeyLength = sizeof(xorKey) / sizeof(xorKey[0]);
for (size_t i = 0; i < length; i++)
{
unsigned char encryptedChar = strPlainText[i] ^ xorKey[i % xorKeyLength];
sprintf_s(hexStr + i * 2, 3, "%02X", encryptedChar);
}
hexStr[length * 2] = '\0';
return hexStr;
}
char* XorDecryptFromHex(const char* strHexCipherText)
{
if (strHexCipherText == nullptr)
{
return nullptr;
}
size_t hexLength = strlen(strHexCipherText);
if (hexLength % 2 != 0)
{
return nullptr;
}
size_t length = hexLength / 2;
char* decryptedStr = new char[length + 1];
if (decryptedStr == nullptr)
{
return nullptr;
}
const unsigned char(&xorKey)[8] = {0xB2, 0x09, 0xBB, 0x55, 0x93, 0x6D, 0x44, 0x47};
const size_t xorKeyLength = sizeof(xorKey) / sizeof(xorKey[0]);
for (size_t i = 0; i < length; i++)
{
char hexByte[3] = { strHexCipherText[i * 2], strHexCipherText[i * 2 + 1], '\0' };
unsigned char encryptedChar = static_cast<unsigned char>(std::strtoul(hexByte, nullptr, 16));
decryptedStr[i] = encryptedChar ^ xorKey[i % xorKeyLength];
}
decryptedStr[length] = '\0';
return decryptedStr;
}
//调用 const char* originalText = "BKBFKDDKCB"; char* cipherText = XorEncryptToHex(originalText); char* decryptedText = XorDecryptFromHex(cipherText);
浙公网安备 33010602011771号