gpt4 book ai didi

c++ - 如何在不包含奇怪字符的情况下使用XOR加密字符串?

转载 作者:行者123 更新时间:2023-12-02 10:19:49 24 4
gpt4 key购买 nike

下面的代码工作正常,但我希望在加密的字符串中不包含奇怪的字符,例如“\ x03”。如何实现呢?

string XOR_Encryption(string toBeEncrypted, string sKey)
{
string sEncrypted(toBeEncrypted);
unsigned int iKey(sKey.length()), iIn(toBeEncrypted.length()), x(0);
for (unsigned int i = 0; i < iIn; i++)
{
sEncrypted[i] = toBeEncrypted[i] ^ sKey[x];
if (++x == iKey) { x = 0; }
}
return sEncrypted;
}

用法:
    string message = "gbpi";
string Key("Q4s4R4t");

string encrypted_message = XOR_Encryption(message, Key);
cout << "encoded: " << encrypted_message << endl;

string decryptedMessage = XOR_Encryption(encrypted_message, Key);
cout << "decoded: " << decryptedMessage << endl;

最佳答案

关于 @kelalaka suggestion,以下是使用十六进制编码的解决方案:

#include "stdafx.h"

#include <stdio.h>
#include <conio.h>
#include <string>
#include <stdlib.h>
#include <iostream>

string XOR_Encryption(string toBeEncrypted, string sKey)
{
string sEncrypted(toBeEncrypted);
unsigned int iKey(sKey.length()), iIn(toBeEncrypted.length()), x(0);
for (unsigned int i = 0; i < iIn; i++)
{
sEncrypted[i] = toBeEncrypted[i] ^ sKey[x];
if (++x == iKey) { x = 0; }
}
return sEncrypted;
}

void stream2hex(const string str, string& hexstr, bool capital = false)
{
hexstr.resize(str.size() * 2);
const size_t a = capital ? 'A' - 1 : 'a' - 1;

for (size_t i = 0, c = str[0] & 0xFF; i < hexstr.size(); c = str[i / 2] & 0xFF)
{
hexstr[i++] = c > 0x9F ? (c / 16 - 9) | a : c / 16 | '0';
hexstr[i++] = (c & 0xF) > 9 ? (c % 16 - 9) | a : c % 16 | '0';
}
}

void hex2stream(const string hexstr, string& str)
{
str.resize((hexstr.size() + 1) / 2);

for (size_t i = 0, j = 0; i < str.size(); i++, j++)
{
str[i] = (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) << 4, j++;
str[i] |= (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) & 0xF;
}
}

int _tmain(int argc, _TCHAR* argv[])
{
string text = "text";
string Key("password");

string encrypted_message = XOR_Encryption(text, Key);
stream2hex(encrypted_message, encrypted_message, true);
cout << "encoded: " << encrypted_message << endl;

hex2stream(encrypted_message, encrypted_message);
string decryptedMessage = XOR_Encryption(encrypted_message, Key);
cout << "decoded: " << decryptedMessage << endl;

getch();

return 0;
}

关于c++ - 如何在不包含奇怪字符的情况下使用XOR加密字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60686526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com