Skip to content

Instantly share code, notes, and snippets.

@camel-cdr
Created June 18, 2021 12:32
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 camel-cdr/be05f8d9519b73a54230c869132c4b01 to your computer and use it in GitHub Desktop.
Save camel-cdr/be05f8d9519b73a54230c869132c4b01 to your computer and use it in GitHub Desktop.
xor encryption using the preprocessor (Idea from https://www.reddit.com/r/C_Programming/comments/o2lgt3/constexpr_in_c/)
#include <stdio.h>
#define E2(...) E1(E1(E1(E1(E1(E1(E1(E1(E1(E1(__VA_ARGS__))))))))))
#define E1(...) __VA_ARGS__
#define EMPTY()
#define DEFER1(m) m EMPTY()
#define APPLY3(F,a,m,k) F(a,0,m,k), F(a,1,m,k), F(a,2,m,k), \
F(a,3,m,k), F(a,4,m,k), F(a,5,m,k), \
F(a,6,m,k), F(a,7,m,k), F(a,8,m,k), \
F(a,9,m,k)
#define APPLY3_() APPLY3
#define F(a,b,m,k) [(a*10+b) < sizeof(k) ? (a*10+b) : sizeof(k)] = (a*10+b < sizeof(k) ? k[a*10+b]^m[a*10+b] : 0)
#define F10(a,b,m,k) DEFER1(APPLY3_)()(F, a*100+b, m, k)
#define F100(a,b,m,k) DEFER1(APPLY3_)()(F10, a*1000+b, m, k)
#define F1000(a,b,m,k) DEFER1(APPLY3_)()(F100, a*10000+b, m, k)
#define F10000(a,b,m,k) DEFER1(APPLY3_)()(F1000, a*100000+b, m, k)
#define F100000(a,b,m,k) DEFER1(APPLY3_)()(F10000, a*1000000+b, m, k)
#define F1000000(a,b,m,k) DEFER1(APPLY3_)()(F100000, b, m, k)
#define ENCRYPT(msg,key) { E2(DEFER1(APPLY3_)()(F10, 0, msg,key)) }
char msg[] = ENCRYPT("encrypted me !!", "This secret key");
int
main(void)
{
puts(msg);
/* decrypt with "This secret key" */
for (int i = 0; i < sizeof "This secret key"; ++i)
putchar(msg[i] ^ "This secret key"[i]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment