mercredi 2 décembre 2015

using rand() and srand() in an encryption code

The question wants me to program a One-Time-Small Pad cryptosystem where the message is longer than the key. the program will use srand() and rand() to generate numbers from 0 to 4 (if the key has 5 letters) and use them on the whole sentence. the srand uses the seed which is the sum of the ASCII values of the letters of the initial key. The problem now is that the sentence encrypted is not the same as the example (attached below).

#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
#include <stdlib.h>
using namespace std;
int main ()
{
    string message, key;
    int messagevalue, keyvalue, i=0, j=0, seed=0;


    cout<<"Enter the message: ";

    getline(cin, message);

    cout << "Enter the key: ";

    getline(cin, key);

    messagevalue = message.length();
    keyvalue = key.length();

    while (key[i] != 0)
    {
        i++;
        j++;
    }


    cout << "The message is: " << setw(20)  << message << endl;

    for (i=0; i < messagevalue; i++)
    {
       seed = seed + key[i];
    }

    srand(seed);

    for(i=0; i < messagevalue; i++)
    {

    message[i] = 65 + (message[i] + key[rand()%j]) % 26;

    }

    cout <<"The cipher is: " << setw(21)  << message <<endl;


    for(i=0; i < messagevalue; i++)
    {
      message[i] = 65 + 26 + (message[i] - key[rand()%j]) % 26;

      if ((message[i] - key[i]) >= 0)
      {
          message[i] = message[i] - 26;
      }

    }

    cout << "The message again is: " << setw(14)  << message << endl;



    return 0;
}

enter image description here




Aucun commentaire:

Enregistrer un commentaire