Skip to content

Instantly share code, notes, and snippets.

@kinoute
Last active June 11, 2020 15:44
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 kinoute/1bdfc0baa5d937ea5421713a0c165e44 to your computer and use it in GitHub Desktop.
Save kinoute/1bdfc0baa5d937ea5421713a0c165e44 to your computer and use it in GitHub Desktop.
Harvard CS50 substitution
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
// the user must provide one and only argument
if (argc != 2)
{
printf("Your forgot the key, duh.\n");
return 1;
}
// we only accept a key of size 26
else if (strlen(argv[1]) != 26)
{
printf("You must provide a key with a length of 26 characters.\n");
return 1;
}
else
{
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
// check if the key is all about alphabetic
if (!isalpha(argv[1][i]))
{
printf("The key should only contain alpha characters.\n");
return 1;
}
// check if every character is only used once
for (int j = i + 1; j < n; j++)
{
if (argv[1][i] == argv[1][j])
{
printf("A key cannot have a same character more than once!\n");
return 1;
}
}
}
}
// store the key argument
string key = argv[1];
// get the text to encrypt
string plaintext = get_string("plaintext: ");
// prepare the encrypted variable
char ciphertext[strlen(plaintext)];
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
// if the character is upper of lower, the alphabet start is not the same
int alpha_index = plaintext[i] - ((isupper(plaintext[i])) ? 65 : 97);
// do nothing if the given character is not alphabetic
if (!isalpha(plaintext[i]))
{
ciphertext[i] = plaintext[i];
}
else // respect the lower or uppercase of the plaintext character
{
ciphertext[i] = islower(plaintext[i]) ? tolower(key[alpha_index]) : key[alpha_index];
}
}
// show result
printf("ciphertext: %s\n", ciphertext);
}
@Meow-ops
Copy link

nul ce code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment