Skip to content

Instantly share code, notes, and snippets.

@sivsivsree
Created January 13, 2022 20:18
Show Gist options
  • Save sivsivsree/9a057e983e25b743311dff0872640daa to your computer and use it in GitHub Desktop.
Save sivsivsree/9a057e983e25b743311dff0872640daa to your computer and use it in GitHub Desktop.
Vigenere Chiper
/**
* Author: Siv Sugaman
* Created: 13-01-2021
*
* (c) Copyright by Siv S<sivsivsree@gmail.com>.
**/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
// The key hash will buffer the key to the length of
// the Message
const char* keyHash(int len, char key[]){
int i, j;
int keyLen = strlen(key);
char *newKey = malloc(len+1);
for(i = 0, j = 0; i < len; ++i, ++j){
if(j == keyLen) {
j = 0;
}
newKey[i] = key[j];
}
newKey[i] = '\0';
// printf("key.. %s\n", newKey);
return newKey;
}
// Encrypt routine will encrypt by using the below
// formula, I have used the algorithm
// E(i) = { [ msg(i) + keyBuffer(i)] % 26 } + 'A' -> for char encode
const char* encrypt(char msg[], char key[]){
int msgLen = strlen(msg);
int i, j;
char *encryptedMsg = malloc(msgLen);
char *newKey = keyHash(msgLen, key);
for(i = 0; i < msgLen; ++i){
char encode = ((msg[i] + newKey[i]) % 26) + 'A';
encryptedMsg[i] = encode;
}
encryptedMsg[i] = '\0';
return encryptedMsg;
}
// Decrypt routine has the logic
// to decrypt the message using the key
const char* decrypt(char message[], char key[]) {
int msgLen = strlen(message), i, j;
char *dMsg = malloc(msgLen);
char *newKey = keyHash(msgLen, key);
for(i = 0; i < msgLen; ++i){
dMsg[i] = (((message[i] - newKey[i]) + 26) % 26) + 'A';
}
dMsg[i] = '\0';
printf("%s", dMsg);
return dMsg;
}
int main(){
int sel, defer;
char passphrase[254];
char key[35];
while (1){
printf(" 1. Encryption \n 2. Decryption \n 3. Clear Screen \n 4. Exit \n");
scanf("%d", &sel);
switch(sel) {
case 1:
printf("Please enter MESSSAGE to ENCRYPT: ");
scanf("%s", passphrase);
printf("Please enter KEY: ");
scanf("%s", key);
// Encryption Logic call
char *encryptedMsg = encrypt(passphrase, key);
printf("\nEncrypted Message: '%s' \n", encryptedMsg);
printf("\npress any key to continue...");
scanf("%d", &defer);
break;
case 2:
printf("Please enter MESSSAGE to DECRYPT: ");
scanf("%s", passphrase);
printf("Please enter KEY: ");
scanf("%s", key);
// Decription Logic call
char *decryptedMsg = decrypt(passphrase, key);
printf("\nDecrypted Message: '%s'\n", decryptedMsg);
printf("\npress any key to continue...");
scanf("%d", &defer);
break;
case 3:
// ASCII clear screen
printf("\e[1;1H\e[2J");
break;
case 4:
exit(0);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment