Skip to content

Instantly share code, notes, and snippets.

@romon267
Last active February 17, 2019 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romon267/4ec1accff7c3b637992a88d5706f1450 to your computer and use it in GitHub Desktop.
Save romon267/4ec1accff7c3b637992a88d5706f1450 to your computer and use it in GitHub Desktop.
vigenere cipher
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int shift(char c);
int main(int argc, string argv[])
{
string keyw = argv[1];
if(argc == 2) // argument count validator
{
for (int i = 0; keyw[i] != '\0'; i++) // key validator
{
if (isalpha(keyw[i]) == 0)
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
}
int key;
int j = 0; // new iterator
string keyword = argv[1];
string p = get_string("plaintext: "); // ask for text
for (int i = 0; i < strlen(p); i++) // ciphering
{
j = j % strlen(keyword);
if (isalpha(p[i]) && isupper(p[i]))
{
key = shift(keyword[j]);
p[i] -= 65;
p[i] = (p[i] + key) % 26;
p[i] += 65;
}
else if(isalpha(p[i]) && islower(p[i]))
{
key = shift(keyword[j]);
p[i] -= 97;
p[i] = (p[i] + key) % 26;
p[i] += 97;
}
if (isalpha(p[i]))
{
j++;
}
}
printf("ciphertext: %s\n", p); // returns ciphered text
}
else
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
}
int shift(char c)
{
int k = (int) c;
if (isupper(c))
{
return k -= 65;
}
else if (islower(c))
{
return k -= 97;
}
else {
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment