XOR错误结果,转义char

时间:2016-04-18 18:15:25

标签: c++ xor

我正在尝试xor一个小字符串,它的工作原理。当我尝试使用XORed字符串时,我甚至无法编译它。

 string str = "MyNameIsMila";
 string str_xored = "2*&.8"'*"; //you can't escape this or the result be be different 
 //Enc:2*&.8"'*:
 //Dec:MyNameIsMila:

我试图逃避字符串,但最后我得到了另一个结果。 有什么好的方向吗? 转义后的输出:

//Enc:yamesila:
//Dec:2*&.8"'*:

希望得到MyNameIsMila。

该功能如下:

 string encryptDecrypt(string toEncrypt) {
     char key = 'K'; //Any char will work
     string output = toEncrypt;   
     for (int i = 0; i < toEncrypt.size(); i++)
         output[i] = toEncrypt[i] ^ key;
     return output;
 }

2 个答案:

答案 0 :(得分:0)

我要说两件事:

  

1:字符串的值必须介于2 - >之间。 “”

 string str_xored = 2*&.8"'*;   //this is not a valid syntax = error

 //valid
 string str_xored = "2*&.8";
 str += '"';
 str += "'*";
  

2:在你的情况下我会使用迭代器:

#include <iostream>
#include <string>

//please don't use "using namespace std;"

 std::string encryptDecrypt(std::string toEncrypt) {
     char key = 'K';            //Any char will work
     std::string output = "";   //needs to be   empty   

     for (auto i = toEncrypt.begin(); i != toEncrypt.end(); i++) {
        output += *i ^ key;     //*i holds the current character to see how
                                //an iterator works have a look at my link
     }
     return output;
 }


int main() {

    std::string str = encryptDecrypt("Hello...!");

    std::cout << str << std::endl;

    return 0;
}

这里看一下(字符串)迭代器:

  

Link 1

     

Link 2

如果你觉得迭代器太难了,那就用你的

for(int i = 0; i < str.size(); i++){
    //CODE
}

有() - 环

答案 1 :(得分:0)

你不能像普通字符串那样对待xored字符串!

value ^ same_value == 0

将它们视为普通容器。

实施例:

#include <iostream>
#include <iterator>
#include <algorithm>

template<typename InputIterator, typename OutputIterator, typename Key>
void perform_xor(InputIterator begin, InputIterator end, OutputIterator out, Key const &key) {
    std::transform(begin, end, out, [key](auto &&value) { 
        return value ^ key;
    });
}

using namespace std;

int main() {
    char test[] = "(2*&.8\"\'*";

    perform_xor(begin(test), end(test), begin(test), '&');
    copy(begin(test), end(test), ostream_iterator<int>(cout, " ")); 

    cout << endl;

    perform_xor(begin(test), end(test), begin(test), '&');
    copy(begin(test), end(test), ostream_iterator<char>(cout)); 

    return 0;
}

请参阅:http://ideone.com/ryoNp5