Skip to content

Instantly share code, notes, and snippets.

@naezith
Last active November 12, 2016 12:56
Show Gist options
  • Save naezith/c79b715789fdcc98d2ceb92af6bd4bd1 to your computer and use it in GitHub Desktop.
Save naezith/c79b715789fdcc98d2ceb92af6bd4bd1 to your computer and use it in GitHub Desktop.
Caesar Cipher
#include <stdio.h>
#include <stdlib.h>
char cap(char c) {
if(c >= 'a' && c <= 'z') c -= 32;
return c;
}
void addToSet(char* set, int* len, char c) {
int i = 0;
while(i < *len && set[i] != '\0') {
if(set[i] == c) break; // Found
++i;
}
// Not found
if((i == 36 || set[i] == '\0') && set[i] != c) set[(*len)++] = c;
}
char* caesarEncrypt(char* msg, int msg_len, char* abc, char* cae_abc) {
char* enc_msg = (char*) malloc(msg_len + 1);
enc_msg[msg_len] = '\0';
int i;
for(i = 0; i < msg_len; ++i) {
int c_idx = 0;
while(c_idx < 36 && abc[c_idx] != cap(msg[i])) ++c_idx;
enc_msg[i] = cae_abc[c_idx];
}
return enc_msg;
}
// argv[1] Key, argv[2] Message
int main(int argc, char *argv[]){
char def_abc[36]= "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char enc_abc[36]; // new alphabet
char new_key[36]; // new key
int i; for(i = 0; i < 36; ++i) enc_abc[i] = new_key[i] = '\0'; // Clear the strings
// Count message length
int m_len = 0; while(argv[2][m_len] != '\0') ++m_len;
// Count key length and capitalize it
int key_len = 0; i = 0;
while(argv[1][i] != '\0') addToSet(new_key, &key_len, cap(argv[1][i++]));
// Create the encrypted alphabet
int enc_abc_len = key_len;
for(i = 0; i < key_len; ++i) enc_abc[i] = new_key[i]; // Copy the key to start
for(i = 0; i < 36 && enc_abc_len < 36; ++i) addToSet(enc_abc, &enc_abc_len, def_abc[i]); // Copy the default alphabet
printf("Encrypted Alphabet:\t%s\n\n", enc_abc);
// Encrypt and print
char* enc_msg = caesarEncrypt(argv[2], m_len, def_abc, enc_abc);
printf("Encrypted Message:\t%s\n", enc_msg);
printf("De-encrypted Message:\t%s\n", caesarEncrypt(enc_msg, m_len, enc_abc, def_abc));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment