Skip to content

Instantly share code, notes, and snippets.

@touatily
Created April 30, 2021 22:58
Show Gist options
  • Save touatily/e2edad8b43d964580b0218140616771f to your computer and use it in GitHub Desktop.
Save touatily/e2edad8b43d964580b0218140616771f to your computer and use it in GitHub Desktop.
Implementation of mono-alphabetic substitution based encryption
#include <stdbool.h>
#include "substitution.h"
void genkey(char * key){
int i;
strncpy(key, "abcdefghijklmnopqrstuvwxyz", 27);
srand(time(NULL));
for(i = 0; i < 100; i++){
int k, l;
k = rand()%26; l = rand()%26;
char tmp = key[k];
key[k] = key[l];
key[l] = tmp;
}
}
void encrypt(const char * text, const char * key, char * ciphertext){
if(! check(key)){
ciphertext[0] = '\0';
return;
}
int i;
for(i = 0; text[i] != 0; i++){
if( (text[i] >= 'a') && ( text[i] <= 'z') ){
short rang = text[i] - 'a';
ciphertext[i] = key[rang];
}
else if( (text[i] >= 'A') && ( text[i] <= 'Z') ){
short rang = text[i] - 'A';
ciphertext[i] = toupper(key[rang]);
}
else
ciphertext[i] = text[i];
}
ciphertext[i] = '\0';
}
void decrypt(const char * ciphertext, const char * key, char * text){
if(! check(key)){
text[0] = '\0';
return;
}
int i;
for(i=0; ciphertext[i] != '\0'; i++){
if( (ciphertext[i] >= 'a') && ( ciphertext[i] <= 'z') ){
char * pos = strchr(key, ciphertext[i]);
short rang = pos - key;
text[i] = 'a' + rang;
}
else if( (ciphertext[i] >= 'A') && ( ciphertext[i] <= 'Z') ){
char * pos = strchr(key, tolower(ciphertext[i]));
short rang = pos - key;
text[i] = 'A' + rang;
}
else
text[i] = ciphertext[i];
}
text[i] = '\0';
}
#include <stdbool.h>
void genkey(char * key);
void encrypt(const char * text, const char * key, char * ciphertext);
void decrypt(const char * ciphertext, const char * key, char * text);
bool check(const char * key);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment