Skip to content

Instantly share code, notes, and snippets.

@Adeniyii
Created August 17, 2020 20:51
Show Gist options
  • Save Adeniyii/e99c24442a71843bdc5c5bdc07f71c9e to your computer and use it in GitHub Desktop.
Save Adeniyii/e99c24442a71843bdc5c5bdc07f71c9e to your computer and use it in GitHub Desktop.
A program using the substitution method to encrypt messages.
/*
A program that implements a substitution cipher.
*/
// Include libraries
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
// Declare implementation details
int check_duplicate(string key);
int validate_key(string key, int count);
char encrypt(char plaintext, string key);
void extract_alpha(string plaintext, string key);
// Main program
int main(int argc, string argv[])
{
string key = argv[1];
int count = argc;
// Validate user provided key
int validated = validate_key(key, count);
if (validated == 0)
{
// Get plaintext from user
string plaintext = get_string("plaintext: ");
// Begin encryption
extract_alpha(plaintext, key);
}
else
{
return 1;
}
}
// Function to validate user provided key
int validate_key(string key, int count)
{
// Check no. of command-line arguments
if (count != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
else
{
// Check key length
if (strlen(key) != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
// Check for non-alphabetic chars in key
else
{
for (int i = 0; i < 26; i++)
{
if (ispunct(key[i]) || isdigit(key[i]))
{
printf("Key must contain only alphabetic characters.\n");
return 1;
}
}
// Check for duplicate chars in key
int duplicate = check_duplicate(key);
return duplicate;
}
}
return 0;
}
// Function to check for duplicate characters in key
int check_duplicate(string key)
{
for (int i = 0; i < strlen(key); i++)
{
for (int j = 0; j < strlen(key); j++)
{
if (i == j)
{
continue;
}
else
{
if (key[i] == key[j])
{
printf("Key must not contain duplicate alphabetic characters.\n");
return 1;
}
else
{
continue;
}
}
}
}
return 0;
}
// Function to extract alphabets from plaintext
void extract_alpha(string plaintext, string key)
{
int txtlength = strlen(plaintext);
char cipherarray[txtlength];
for (int i = 0; i < txtlength; i++)
{
// Check for symbols, spaces and digits
if (ispunct(plaintext[i]) || isblank(plaintext[i]) || isdigit(plaintext[i]))
{
cipherarray[i] = plaintext[i];
}
// Check for alphabets
else if (isalpha(plaintext[i]))
{
// Encrypt plaintext
char newchar = encrypt(plaintext[i], key);
cipherarray[i] = newchar;
}
}
// Assign a null char to last index in array
cipherarray[txtlength] = '\0';
printf("ciphertext: %s\n", cipherarray);
}
// Function to encrypt plaintext to ciphertext
char encrypt(char plaintext, string key)
{
if (isupper(plaintext))
{
int index = (int) plaintext - 65;
return toupper(key[index]);
}
else
{
int index = (int) plaintext - 97;
return tolower(key[index]);
}
}
// Victory!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment