Skip to content

Instantly share code, notes, and snippets.

@toshvelaga
Created July 25, 2018 23:41
Show Gist options
  • Save toshvelaga/2f0dc789fd67dcc37f454c8485923a65 to your computer and use it in GitHub Desktop.
Save toshvelaga/2f0dc789fd67dcc37f454c8485923a65 to your computer and use it in GitHub Desktop.
CS50 Vigenere
/* CS50 solution. Feel free to check with any online compiler. To get credit from Harvard you may have to make a few changes.
hmu at s.velaga@uky.edu if you have any questions. Also I haven't learned about proper code style and formatting -
if you wanna hmu to tell me this looks like shit and how to make it look better pls do */
#include <stdio.h> //includes fget and stdin //
#include <ctype.h> // used for isupper, islower, toupper, tolower
#include <stdlib.h>
#include <string.h> //used for strlen
int main()
{
// Asks the user for some plaintext to cipher //
char plaintext[100];
printf("\nPlease enter some text that you want encrypted. . . . ");
fgets(plaintext,sizeof(plaintext),stdin);
// Asks the user to enter in a keyword (k) that will be used as a key //
char k[50];
printf("\nPlease enter some keyword that will be used as your key. . . . ");
fgets(k,sizeof(plaintext),stdin);
// loops through the key and assigns each charater in the key to an integer
// from 0 - 26 for the letters in the alphabet
int knum[50];
int klen; // is the length of the keyword
klen = strlen(k) -1;
for (int i = 0, klen = strlen(k); i < klen; i++)
{
if (k[i]>= 'A' && k[i] <= 'Z')
{
knum[i] = k[i] - 65;
}
else if (k[i] >= 'a' && k[i] <= 'z')
{
knum[i] = k[i] - 97;
}
}
printf("\n\n");
// get the ciphertext by adding the plain text values to the keyword values //
int m;
int j;
int plaintextnum[100];
for (j = 0, m = strlen(plaintext); j < m; j++)
{
if (plaintext[j] >= 'A' && plaintext[j] <= 'Z')
{
plaintextnum[j] = (plaintext[j] + knum[j % klen]);
if (plaintextnum[j] > 90)
{
plaintextnum[j] = plaintextnum[j] - 26;
}
else
{
plaintextnum[j] = plaintextnum[j];
}
printf("%c", plaintextnum[j]);
}
else if (plaintext[j] >= 'a' && plaintext[j] <= 'z')
{
plaintextnum[j] = (plaintext[j] + knum[j % klen]);
if (plaintextnum[j] > 96 && plaintextnum[j] < 123)
{
plaintextnum[j] = plaintextnum[j];
}
else
{
plaintextnum[j] = plaintextnum[j] - 26;
}
printf("%c", plaintextnum[j]);
}
}
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment