c++中的加密问题

Encryption issue in c++

本文关键字:问题 加密 c++      更新时间:2023-10-16

我目前正在尝试实现一个替换密码,由于某种原因不断崩溃,代码相当直接,但我一直遇到问题,我认为起源于for循环或当我试图从文件中读取数据时。

cout << "Ener a key :";
cin >> key;
cin.ignore();
cout << endl << "Enter input file name: ";
getline(cin,fileIn);
inputfile.open(fileIn.c_str(), ios::in);

cout << endl << "Enter output file name: ";
getline(cin,fileOut);
outfile.open(fileOut.c_str(), ios::app);
cout << endl << "[E]ncryption or [D]ecryption? :";
cin >> EorD;

//Encryption
if (EorD == "E" || "e")
{
    while(!inputfile.eof()) // Reading in file data, while not end of file.
    {
        getline(inputfile,plainText);
    }
        for (int i = 0; i <= plainText.length(); i++)
        {
        char letter = plainText.at(i);
        int val = (int)letter; // getting ascii value of each letter.
        int EnVal = (val - 32) + key;
            if(EnVal > 95)
            {
                EnVal = (EnVal - 95) + 32;
            }
        char EnLetter = static_cast<char>(EnVal);
        outfile <<  EnLetter;

change

for (int i = 0; i <= plainText.length(); i++)

for (int i = 0; i <= plainText.length()-1; i++)

因为超出范围。使用iterator更好。

也改变这个:

if (EorD == "E" || "e")

if (EorD == "E" || EorD == "e")

因为前者总是正确的。

正如James Kanze指出的那样,不要使用std::string::at,你在这里不需要它,将其更改为std::string operator[]和我的建议:另外在一个漂亮的try{}catch(...){}块中覆盖你的代码

你可以考虑这样做:

#include <vector>
#include <iterator>
#include <algorithm>
int key=100;
char op(char c){
    char letter = c;
        int val = (int)letter; // getting ascii value of each letter.
        int EnVal = (val - 32) + key;
            if(EnVal > 95)
            {
                EnVal = (EnVal - 95) + 32;
            }
        char EnLetter = static_cast<char>(EnVal);
        return EnLetter;
}
int main(){
    try{
       std::string s="piotrek";
       std::vector<char> vc_in(s.begin(),s.end());
       std::vector<char> vc_out;
       std::transform (vc_in.begin(), vc_in.end(), 
          std::back_inserter(vc_out), op); //this do the thing
       std::copy(vc_out.begin(), vc_out.end(),
          std::ostream_iterator<char> (std::cout,"_")); // to print
    }catch(std::exception& e){
       cout<<"exception: "<<e.what();
    }
    return OK;
}

您在plainText字符串中循环了一个索引太远。因为它有length()个条目,第一个是0,最后一个索引是length()-1。试试这个:

for (int i = 0; i < plainText.length(); i++)

否则i太大时plainText.at(i)会崩溃