[英]Simple encryption with encryption key
I am doing simple encryption. 我正在做简单的加密。 I have function called encryption(string text, string encryption_key).
我有一个叫做加密的功能(字符串文本,字符串encryption_key)。 It should replace text's a's with first letter of encryption_key, b's with second and so on.
它应该用encryption_key的第一个字母替换文本的a,用第二个字母替换b,以此类推。 I am trying to solve this with ASCII values.
我正在尝试使用ASCII值解决此问题。
I'm not sure if I think this right but I have tried something like this: 我不确定我是否认为这是正确的,但是我已经尝试过类似的方法:
void encryption(std::string text, std::string encryption_key){
for(long unsigned int i=0; i< encryption_key.length();i++){
char letter = encryption_key.at(i);
for(char j = 'a'; j<='z'; j++){
if(text.find(j) != std::string::npos){
text.at(j)= letter;
}
}
std::cout<<"Encrypted text: "<< text<<std::endl;
}
}
I am getting "terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 101) >= this->size() (which is 5) Press to close this window..." 我在抛出“ std :: out_of_range”的what()实例后得到“终止调用”:basic_string :: at:__n(101)> = this-> size()(5)按下以关闭此窗口......”
Is the idea right that I try to go through the encryption key characters first and replace the characters (az) in the text? 我尝试先通过加密密钥字符并替换文本中的字符(az)的想法正确吗?
Fix: 固定:
auto pos = text.find(j);
if(pos != std::string::npos) {
text[pos] = letter;
}
The fix to your code is text.at(text.find(j)) = letter;
您的代码的解决方法是
text.at(text.find(j)) = letter;
void encryption(std::string text, std::string encryption_key){
for(long unsigned int i=0; i< encryption_key.length();i++){
char letter = encryption_key.at(i);
for(char j = 'a'; j<='z'; j++){
if(text.find(j) != std::string::npos){
text.at(text.find(j))= letter;
}
}
std::cout<<"Encrypted text: "<< text<<std::endl;
}
}
I belive however, the algorithm is wrong from what you've described. 但我相信,根据您的描述,该算法是错误的。
EDIT: Without using libraries you can do: 编辑:不使用库,您可以执行以下操作:
void encryption(std::string text, std::string encryption_key)
{
for (int i=0; i<text.length(); i++)
{
for (char ch = 'a'; ch<='z'; ch++)
{
if (text[i] == ch)
{
text[i] = encryption_key[ch-'a'];
break;
}
}
}
std::cout<<"Encrypted text: "<< text<<std::endl;
}
With using replace
algorithm, you can simply do this. 使用
replace
算法,您可以轻松地做到这一点。 It will go through the text
string and replace all occurrences of a particular letter with the corresponding value in the encryption_key
. 它将遍历
text
字符串,并将所有出现的特定字母替换为encryption_key
的相应值。 Here encryption_key
contains encrypted values for all small letters. 在这里,
encryption_key
包含所有小写字母的加密值。
void encryption(std::string text, std::string encryption_key){
int j = 0;
for(auto i = 'a'; i <= 'z'; i++) //text has only small letters
{
std::replace( text.begin(), text.end(), i, encryption_key.at(j));
j++;
}
std::cout <<"Encrypted text: "<< text<<std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.