Skip to content

Instantly share code, notes, and snippets.

@Adeniyii
Created August 11, 2020 17:12
Show Gist options
  • Save Adeniyii/0f4ef1fe50c079b3c9cebcb9eeb6f5f3 to your computer and use it in GitHub Desktop.
Save Adeniyii/0f4ef1fe50c079b3c9cebcb9eeb6f5f3 to your computer and use it in GitHub Desktop.
A program implementing Caesar's cipher to encrypt plaintext.
/*
A program to encrypt messages using a Caesar cipher.
Usage: ./caesar key
- Where key is the number of places to move your letters by.
*/
// Include libraries
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Declare functions
char encrypt(char alpha, int key);
void extract_alpha(string plaintext, int key);
// Main program
int main(int argc, string argv[])
{
string key = argv[1];
// Check if there are more or less than 2 command-line arguments
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
else
{
for (int i = 0; i < strlen(key); i++)
{
// Check if key is not a number
if ((int) key[i] > 57 || (int) key[i] < 48)
{
printf("Usage: ./caesar key\n");
return 1;
}
else
{
continue;
}
}
}
// Convert key to integer
int num = atoi(argv[1]);
string input = get_string("plaintext: ");
// Extract alphabets from plaintext
extract_alpha(input, num);
}
// Function to extract alphabets from plaintext
void extract_alpha(string plaintext, int 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;
}
}
printf("ciphertext: ");
for (int i = 0; i < txtlength; i++)
{
printf("%c", cipherarray[i]);
}
printf("\n");
}
// Function to encrypt plaintext to ciphertext
char encrypt(char alpha, int key)
{
int places = key % 26;
int position = places + (int) alpha;
// Check if uppercase
if (isupper(alpha))
{
// Check if encrypted char exceeds ASCII uppercase alphabets
if (position > 90)
{
int p3 = position - 90;
char final = (char)(p3 + 64);
return final;
}
else
{
return (char) position;
}
}
else
{
// Check if encrypted char exceeds ASCII lowercase alphabets
if (position > 122)
{
int p3 = position - 122;
char final = (char)(p3 + 96);
return final;
}
else
{
return (char) position;
}
}
}
// VICTORY!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment