0

I am having some issues trying to get my code to work. It prints ALMOST the right data but maybe it isn't looping correctly? I don't think it repeats the key through the alphabet. It's all lowercase and doesn't exceed 26.

void vigenereEncrypt( const char  plaintext[], char ciphertext[], const char key[] )

{
int idx;
int j;

for( idx = 0, j = 0; idx <= strlen(plaintext); idx++ )
{
    if ( CHAR_OUT_OF_RANGE(plaintext[idx]) )
    {
        ciphertext[idx] = plaintext[idx];
    }
    else
    {
        ciphertext[idx] = plaintext[idx];
        ciphertext[idx] += key[j] - MIN_ASCII_VALUE;

        if (ciphertext[idx] >= MAX_ASCII_VALUE) ciphertext[idx] += -MAX_ASCII_VALUE + MIN_ASCII_VALUE - 1;
    }
    j = (j + 1) % strlen(key);
}

ciphertext[idx] = 0;    
}

for instance: if I enter the plaintext toner with a key of jerry the output will be csevé. It should change it to csevp

2 Answers2

0

Your loop is going one-to-far. You should use < instead of <=. And I assume you should be testing for > MAX_ASCII_VALUE, not >= (but you haven't shown what MAX_ASCII_VALUE is).

But your basic problem is a signed vs. unsigned char problem. With signed chars, when it goes above 127 it wraps around and becomes negative, so the > test will fail when it should have passed.

void vigenereEncrypt(const char plaintext[], char ciphertext[], const char key[])
{
    size_t i, j;
    for(i = 0, j = 0; i < strlen(plaintext); ++i )
    {
        ciphertext[i] = plaintext[i];
        if (!CHAR_OUT_OF_RANGE(plaintext[i]))
        {
            ciphertext[i] += (uchar)key[j] - (uchar)MIN_ASCII_VALUE;

            if ((uchar)ciphertext[i] > (uchar)MAX_ASCII_VALUE)
                ciphertext[i] -= (uchar)MAX_ASCII_VALUE - (uchar)MIN_ASCII_VALUE + 1;
        }
        j = (j + 1) % strlen(key);
    }

    ciphertext[i] = 0;
}
ooga
  • 15,423
  • 2
  • 20
  • 21
  • It still doesn't seem to be working ooga. When I used your code it didn't compile, however I changed what you've pointed out. It still gives me the same output :( – user3269626 Feb 04 '14 at 07:22
0

Do everybody (especially yourself) a favor, and use std::string instead of C-style strings. Then use a standard algorithm instead of writing messing up the loops on your own.

#include <iostream>
#include <iterator>
#include <algorithm>

class crypt {
    std::string key;
    size_t pos;
public:
    crypt(std::string const &k) : key(k), pos(0) { }

    char operator()(char input) { 
        char ret = input ^ key[pos]; 
        pos = (pos + 1) % key.size(); 
        return ret; 
    }
};

int main() {
    std::string input("This is some input to be encrypted by the crappy encryption algorithm.");

    std::transform(input.begin(), input.end(),
        std::ostream_iterator<char>(std::cout),
        crypt("This is the key"));
    return 0;
}
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111