Manav Saxena
Manav Saxena

Reputation: 473

C++ Vigenere Cipher

I wrote this code for Vigenere Cipher in C++ (Assuming the plaintext and the key is in lowercase).

void encrypt(string& plaintext , string key){
int j = 0;

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

     //cout<<"value of key["<<j<<"] = "<<int(key[j])<<endl;

     plaintext[i] -= 97;
     key[j] -= 97;

     plaintext[i] = ((plaintext[i] + key[j])%26)+97;

     j = (j+1)%key.length();
  }
}

The problem is that when 'j' gets reset to 0 , key[j] turns out to be NULL(0). For eg. If I assume the plaintext to be 'human' and key to be 'abcd' the first 4 characters of the plaintext are encrypted correctly but for the last character the key[j] value is turning out to be 0 or Null instead of going back to 'a'.

I am not sure why this is happening. I guess string class handles Null values implicitly so that makes it even more confusing to me.

Upvotes: 0

Views: 475

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118350

key[j] -= 97;

On the first pass through the key, this chunk of code will scribble all over it.

If key was "abcd", on second pass it will now be 0.

Do not modify key in your function. Since that parameter should not be changed, it should be declared as const std::string key, or, better yet, const std::string &key. If it was done that way, the compiler would've caught this bug for you.

Upvotes: 1

Related Questions