为什么我的琴弦不会是XOR?

时间:2015-06-30 07:53:54

标签: c++ string operator-keyword xor

我想加密用户输入的密码字符串,然后将其打印在屏幕上。还要恢复原始密码,然后将其打印在屏幕上。但XOR运算符不使用字符串。我该如何操纵它?

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
   string pass;
  string enc="akdhigfohre";
  string x;


   cout<<"Enter new password:  ";
   cin>>pass;
   cout<<"\n\nYour New Password is:" << pass<<endl;

   x=pass^enc;
   cout<<"\n\nEncrypted Version: "<<x;

   x=x^enc;
   cout<<"\n\nRecovred Password:  "<<x;

   system("pause");



}

2 个答案:

答案 0 :(得分:0)

好的,我有一个可以解决您问题的解决方案。希望它对你有所帮助。

#include <iostream>

using namespace std;

#include<iostream>
using std::string;

string XOR(string value,string key)
{
    string retval(value);

    short unsigned int klen=key.length();
    short unsigned int vlen=value.length();
    short unsigned int k=0;
    short unsigned int v=0;

    for(v;v<vlen;v++)
    {
        retval[v]=value[v]^key[k];
        k=(++k<klen?k:0);
    }

    return retval;
}

int main()
{
    std::string value("Phuc Nguyen");
    std::string key("akdhigfohre");

    std::cout<<"Plain text: "<<value<<"\n\n";
    value=XOR(value,key);
    std::cout<<"Cipher text: "<<value<<"\n\n";
    value=XOR(value,key);
    std::cout<<"Decrypted text: "<<value<<std::endl;

    std::cin.get();
    return 0;
}

enter image description here

答案 1 :(得分:0)

再试一次问题的代码库,

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
  string pass;
  string enc="akdhigfohre";
  string x = "";
  string y = "";

   cout<<"Enter new password:  ";
   cin>>pass;
   cout<<"\n\nYour New Password is:" << pass<<endl;

   for(size_t i = 0; i < pass.size(); ++i){
     x += pass.at(i)^enc.at(i%enc.size());
   }
   cout<<"\n\nEncrypted Version: "<<x;

   for(size_t i = 0; i < x.size(); ++i){
     y += x.at(i)^enc.at(i%enc.size());
   }

   cout<<"\n\nRecovred Password:  "<<y;

   system("pause");
}