Cipher Function Producing Unwanted Results in the Last Character of Output

I have been spending all day trying to figure out what I did wrong with this enciphering function I created.

The function works by taking in a keyword which it then converts to an ASCII values and then takes that value and formats it into something that will work with an alphabetical index eg: A= 0, B= 1, C= 2, etc... It then converts all of the plain text using the same method. After that it shifts over the characters of the plain text and then adds the characters value from the keyword iterating over the keyword in a loop until it is done encrypting the plain text.

It works for all my tests except for one which went like this:

Keyword is BaZ


plaintext: BaRFoo


ciphertext: CaQGoh

but the desired output is

ciphertext: CaQGon

void encipher(char* plainText, char*key)
    printf("ciphertext: ");
    char alphabeticalIndex[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    int currentKeyChar = 0;

    for(int i = 0, n = strlen(plainText); i < n; i++)
            // check if the end of they key has been reached, if so then reset it
            if(currentKeyChar >= strlen(key)) currentKeyChar = 0;

            if(isalpha(plainText[i]) == false) printf("%c", plainText[i]);

                // find the cipher character as an int then add it as the key to captialCharNum
                int capitalCipherCharNum = ((int) key[currentKeyChar] - 65);
                int capitalCharNum = (((int) plainText[i] - 65) + capitalCipherCharNum) % 26;

                printf("%c", toupper(alphabeticalIndex[capitalCharNum]));

                // same as it was for capitals but in this case its lowercase
                int lowerCipherCharNum = ((int) key[currentKeyChar] - 97);
                int lowerCharNum = (((int) plainText[i] - 97) + lowerCipherCharNum) % 26;

                printf("%c", tolower(alphabeticalIndex[lowerCharNum]));


0 Comment



Captcha image