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
#include<stdio.h>
#include<cs50.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
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++){
if(isalpha(key[m])==false){
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';
}
else{
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++){
if(isalpha(plaintext[u])==false){
printf("%c",plaintext[u]);
continue;
}
int value = u % klength;
ciphertext[u] = (keys[value] + plaintext[u]);
//By the more than 90 I am referring to 'z'
if(ciphertext[u]>90){
ciphertext[u] = ciphertext[u] ;
}
printf("%c",ciphertext[u]);
}
printf("\n");
return 0;
}
Thanks Kalyan
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.