使用随机生成的替换密码解码文本

时间:2015-02-03 10:46:54

标签: c++ encryption random decode

我差不多完成了一个用于编码和解码的随机密码的程序。但是,我无法让我的程序也解码消息。它让我感到困惑,因为我没有密码的密钥,因为每次都会以随机的方式替换字母,所以我不知道这个程序的解密代码应该是什么样子。我应该采取什么方法?

以下是代码:

void randomizer()       //cipher
{
    srand(time(0));     //seed for rand()
    static char alphabet[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //static array to hold uppercase Latin letters
    static char alphabetlow[]="abcdefghijklmnopqrstuvwxyz"; //lower-case Latin letters
    const int LENGTH=sizeof(alphabet)-1;     //length of the array

    int r;
    char temp;
    char tempb;
    for (unsigned int i=0; i<LENGTH; i++)   //loop which shuffles the array
    {
        r=rand() % LENGTH;  //generate a sequnce of pseudo-random numbers

        temp=alphabet[i];          //temp gets the int values of the array elements
        alphabet[i] = alphabet[r];  //randomized letters are copied into the ordered alphabet (now scrambled)
        alphabet[r]=temp;   //ordered letters are copied into the scrambled alphabet

        tempb=alphabetlow[i];   //shuffle second array
        alphabetlow[i]=alphabetlow[r];
        alphabetlow[r]=tempb;
    }
    string text, textb;
    getline(cin,text);

    for (unsigned int i=0; i<text.length(); i++)     //loop to encrypt
    {
        if (isalpha(text[i]))   //encrypt only input text which is Latin letters
        {
            if (islower(text[i]))   //checks if input text is lowercase letters
            {
                text[i]=alphabetlow[text[i] - 'a']; //scrambles lowercase letters
            }
            else
            {
                text[i]=alphabet[text[i] - 'A'];    //scrambles uppercase letters
            }
        }
    }
    cout<<"Encrypted: "<<text<<endl;

    getline (cin, textc);
    for (unsigned i=0; i<textc.length(); i++)
    {
        //supposedly code to decode should be here
    }
    cout<<"Decrypted: "<<textc;

0 个答案:

没有答案