【问题标题】:Why my strings are not going to be XOR?为什么我的字符串不会异或?
【发布时间】:2015-09-16 21:57:58
【问题描述】:

我想加密用户输入的密码字符串,然后在屏幕上打印。还可以恢复原始密码,然后也将其打印在屏幕上。但是 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");



}

【问题讨论】:

  • 您可以将字符串拆分为字符,对每个单独的字符进行异或,然后将它们组合成新字符串
  • 谢谢先生。如何拆分字符?请告诉代码。
  • for(char c: pass) { ... }
  • 类似于for (int i = 0; i&lt;x.length;i++) {newPass+= x[i]^enc[i%enc.length]; }

标签: c++ string operator-keyword xor


【解决方案1】:

再次尝试该问题的代码库,

#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");
}

【讨论】:

    【解决方案2】:

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

    #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;
    }
    

    【讨论】:

    • 我以后会的。但现在我有声望
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多