Skip to content

Instantly share code, notes, and snippets.

@pdhixenbaugh
Created July 16, 2020 01:39
Show Gist options
  • Save pdhixenbaugh/8d07c731d5b7b63b7b76ff9156ca0d43 to your computer and use it in GitHub Desktop.
Save pdhixenbaugh/8d07c731d5b7b63b7b76ff9156ca0d43 to your computer and use it in GitHub Desktop.
// Encrypts text with caesar's cypher
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>
#include <math.h>
// prototypes
int error(void);
string cyp_caesar(int key, string plaintext, int n);
int main(int argc, string argv[])
{
// Check input
if (argc != 2)
{
return error();
}
int argLen = strlen(argv[1]);
for (int i = 0; i < argLen; i++)
{
if (isdigit(argv[1][i]) == 0)
{
return error();
}
}
// Convert key
int key = atoi(argv[1]);
key = key % 27;
// Ask plaintext, Encrypt, Print Cyphertext
string plain = get_string("plaintext: ");
int plainLen = strlen(plain);
plainLen--;
string cyphertext = cyp_caesar(key, plain, plainLen);
printf("Cyphertext: %s\n",cyphertext);
}
int error(void)
{
printf("Usage: ./caesar key\n");
return 1;
}
//converts plaintext to cypertext
string cyp_caesar(int key, string plaintext, int n)
{
//stop recursing
if (n == -1)
{
return "";
}
cyp_caesar(key, plaintext, n - 1);
// convert string element if alpha
char debug = plaintext[n];
if (isalpha(plaintext[n] != 0))
{
int upperCase = isupper(plaintext[n]);
// int lowerCase = islower(plaintext[n])
plaintext[n] = (int) plaintext[n] + key;
// Rotate from Z or z back to A or a
if (upperCase > 0 && plaintext[n] > 90)
{
plaintext[n] = plaintext[n] - 27;
}
//if (lowerCase > 0 && plaintext[n] > 122)
//{
// plaintext[n] = plaintext[n] - 27;
//}
else if (plaintext[n] > 122)
{
plaintext[n] = plaintext[n] - 27;
}
}
return plaintext;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment