有两个关于我的解密程序的问题,有些是关于C ++的

时间:2014-10-22 02:34:29

标签: c++ encryption

所以我的程序中的某些内容并不像我认为的那样。如果我能得到一些帮助,我会很感激。我将解释它应该如何首先工作并从最重要的问题开始跟进我的问题,因为我坚持下去并且它不允许我继续前进。 / p>

所以我写了一个加密程序,要求用户输入一个字符串然后加密它并创建一个名为" secret.dat"并将加密的短语放在那里。

如果用户要输入短语:

hello world 123

它会将其发送到文件中:

11spwwzshzcwoh234&6#12

" 11"表示字母向右移动了多少个字母。接下来是他加密输入的短语。 '&'字符显示加密结束的位置。他的短语中的每个空格都使用前一个字母并将其移过4,最后在'&'之后。字符它告诉空格分隔的位置的数字位置#'#'字符。

我正在编写的当前程序解密" secret.dat"文件并在屏幕上显示他的短语。

这是我到目前为止所做的:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    //Declare Variables
    int shift;
    ifstream inData;
    string input;
    string output;
    int length;

    //Open file
    inData.open("secret.dat");

    //Begin program
    inData >> shift;

    getline(inData, input, '&'); 

    length = input.length();

    for (int count = 0; count < length; count++)
    {
        if (input[count] >= 'a' && input[count] <= 'z')
        {
            output += ((input[count] - 'a' - shift) % 26) + 'a';
        }
        else if (input[count] >= '0' && input[count] <= '9')
        {
            output += ((input[count] - '0' - shift) % 10) + '0';
        }       
    }

    //Declare variables for location of spaces
    int i = 0;
    char ignore;
    int spaces[20];
    int location;

    //Begin finding the spaces
    while (!EOF)
    {
        inData >> location;
        spaces[i] = location;
        inData >> ignore;
    }

    //Preview each result to compare and make sure they are working right
    cout << shift << endl;
    cout << input << endl;
    cout << output << endl;
    cout << spaces[0] << endl;
    cout << spaces[1] << endl;

    return 0;
}

这就是我得到的结果

11
spwwzshzswoh234
helloh]oXld]'()
4704512
0

显然最后3行不能正常工作(注意:这不是我要显示它的方式,我只是将它们打印到屏幕上,这样我就能看到结果是什么,并确保它是正确的,哪个它不是。

所以,我的第一个也是最重要的问题是为什么我的while循环没有正常工作。它在第一个数组插槽中给出了一堆随机数,它应该在第一个位置放置一个6,然后它应该跳过下一个字符,然后在数组中的第二个位置放一个12,它只是在那里放0 。如果我只是在while循环之外的文件中调用一个整数,它给我一个6没问题,所以我不确定它为什么这样做。我想它会将第一个整数放在数组的第一个槽中,然后跳过下一个字符,然后将下一个整数放入数组中并跳过下一个字符,依此类推,直到文件结束。这部分是阻止我继续学习的部分,所以我把它作为最重要的部分。

其次,我的公式将角色转移回来有什么问题?我使用这个相同的公式来为我的加密程序向前移动字符,除了我添加了移位,所以我假设只是减去移位会解密它。

感谢愿意提供帮助的任何人!

1 个答案:

答案 0 :(得分:1)

在您的加密方案中,角色&#39; h&#39;代表字母&#39; w&#39;明文。

让我们了解您的代码如何尝试解码它:

if (input[count] >= 'a' && input[count] <= 'z')
{
    output += ((input[count] - 'a' - shift) % 26) + 'a';
}

input[count]是字符&#34; h&#34;。 &#39; H&#39; - &#39; a&#39;是你的价值#34; shift&#34;是11。

您的表达式计算(7-11)%26或-4%26。

流行测验:什么是-4%26?得知答案是-4,你会感到惊讶。添加-4到&#39; a&#39;生成字符&#39;]&#39;,这是您在输出中的相应位置看到的。

要解决此问题,请将此行更改为:

output += ((input[count] - 'a' - shift + 26) % 26) + 'a';

以相同的方式更改数字的另一行。