Last active
February 17, 2019 14:21
-
-
Save romon267/4ec1accff7c3b637992a88d5706f1450 to your computer and use it in GitHub Desktop.
vigenere cipher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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