Kalyan Nadimpalli Kalyan Nadimpalli - 1 year ago 180
C Question

Vigenere Cipher In C not working

I am attempting to make the vigenere cipher.
Information about it is here: https://www.youtube.com/watch?v=9zASwVoshiM
My code doesnt seem to work for a few cases.
My code is listed below please dont send me a link how to make the vigenere cipher but instead a way to fix mine. If I put the key as z for example it is value 25 acc to alphabet. Now if I put the to be encrypted text as c which is 2 the new text is of value 27 and should show b but for me it doesn't. So if the value exceeds 25 it doesn't show what I want else it works. And for the actual output example:
ab as key should change ca to cb


int main( int argc , string argv[]){
//string plaintext;

string key;
if(argc != 2){
printf("Please run the programme again this time using a command line argument!\n");
return 1;
key = argv[1];
int keys[strlen(key)];

for(int m = 0; m< strlen(key);m++){
printf("Re-Run The programme without any symbols.\n");
return 1;

for(int b = 0; b < strlen(key);b++){
if(isupper(key[b]) == false){
keys[b] = key[b] - 'a';
keys[b] = key[b] - 'A';

//printf("Enter a string which should be encrypted: \n");
string plaintext = GetString();
int plength = strlen(plaintext);
int klength = strlen(key);
string ciphertext = key;

for(int u = 0; u<plength;u++){
int value = u % klength;

ciphertext[u] = (keys[value] + plaintext[u]);
//By the more than 90 I am referring to 'z'
ciphertext[u] = ciphertext[u] ;


return 0;


Answer Source

You are correctly processing the value in the key by consistently substracting from its code the code of 'A' for an uppercase letter and 'a' for a lower case one. It gives you: A|a => 0, B|b => 1, ... , Z|z => 25. Fine till here...

But when encrypting, you are just adding this value to the code of a character without wrapping at any time.

Let us use your example: key is 'z' => value 25 in keys, fine. Take character 'c'. Its ASCII(*) code is 0x63 or 99. 99+25=124 giving in ascii table '|' ! To correctly wrap it, you must ensure that in any way 'z' + 1 => 'a'. You code could be

        /* test wrapping for lowercase letters */
        if ((islower(plaintext[u]) && (ciphertext[u]>'z')) {
            ciphertext[u] = ciphertext[u] - 'z' + 'a'  - 1;
        /* same for uppercase */
        if ((isupper(plaintext[u]) && (ciphertext[u]>'Z')) {
            ciphertext[u] = ciphertext[u] - 'Z' + 'A'  - 1;

(*) the example assumed ASCII code because it is the most common nowadays, but the code only assumes that all uppercase letters are in sequence and all lowercase letters are also in sequence without any requirement for their exact values nor the order of upper and lower case sequences.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download