Skip to content

Instantly share code, notes, and snippets.

@chankruze
Created March 9, 2022 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chankruze/fa99385233db2e306bfa95f754ac35c9 to your computer and use it in GitHub Desktop.
Save chankruze/fa99385233db2e306bfa95f754ac35c9 to your computer and use it in GitHub Desktop.
/*
Author: chankruze (chankruze@gmail.com)
Created: Wed Mar 09 2022 10:06:36 GMT+0530 (India Standard Time)
Copyright (c) geekofia 2022 and beyond
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TEXT_LEN 100
#define MAX_KEY_LEN 10
// #define printld(x) printf("%ld\n", x)
// #define printd(x) printf("%d\n", x)
// #define what_char(x) printf("c = %c, ord(c) = %d\n", x, ord(x))
int ord(char c) {
return c;
}
char chr(int x) {
return x;
}
char* encrypt(char* plain_text, char* xor_key) {
// length of plain text
size_t len_plain_text = strlen(plain_text);
// length of key
size_t len_xor_key = strlen(xor_key);
// empty character array of encrypted text
char* encrypted = malloc(len_plain_text);
// loop over each character in plain text
for (size_t i = 0; i < len_plain_text; i++) {
// xor each character's int with key's correspondence character's int
char x = chr(ord(plain_text[i]) ^ ord(xor_key[i % len_xor_key]));
// what_char(x);
encrypted[i] = x;
}
return encrypted;
}
char* decrypt(char* cipher_text, char* xor_key) {
// length of cipher text
size_t len_cipher_text = strlen(cipher_text);
// length of key
size_t len_xor_key = strlen(xor_key);
// empty character array of cipher text
char* decrypted = malloc(len_cipher_text);
// loop over each character in cipher text
for (size_t i = 0; i < len_cipher_text; i++) {
// xor each character's int with key's correspondence character's int
char x = chr(ord(cipher_text[i]) ^ ord(xor_key[i % len_xor_key]));
// what_char(x);
decrypted[i] = x;
}
return decrypted;
}
int main() {
// plain text user input
char plain_text[MAX_TEXT_LEN];
scanf("%s", plain_text);
// xor key
char xor_key[MAX_KEY_LEN];
scanf("%s", xor_key);
char* encrypted = encrypt(plain_text, xor_key);
char* decrypted = decrypt(encrypted, xor_key);
// ui
printf("original = %s\n", plain_text);
printf("encrypted = %s\n", encrypted);
printf("decrypted = %s\n", decrypted);
// cleanup
free(encrypted);
free(decrypted);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment