Why?
In a recent code golf contest, the goal was to write a useful program within 100 characters tops…
What does the program do?
This program can encode and decode any kind of data (text, binary data…), using a user-defined key (passphrase) of any desired length.
It has been adaptated from the Vigenère cypher, replacing the traditional 26-characters latin alphabet with the 256 values a byte can take.
The code
Here is what I submitted to the contest, in C:
i;main(int c,char**a){for(a+=2;1+(c=getchar());)putchar(c+(**(a-1)-69?1:-1)**(*a+i++%strlen(*a)));} |
Well sorry for the lack of readability… this is what happen when you are not allowed to use more than 100 characters! Please find the expanded and commented code below:
int main(int argc, char** argv) { // retrieve the first argument passed to the program (action) char action = argv[1][0]; // retrieve the second argument passed to the program (key) char* key = argv[2]; // initialize character position in the key int i = 0; // initialize the current input character int c = 0; // loop until we reach the end of input while (c != -1) { // get a character from stdin c = getchar(); if (action == 'E') { // encode the current character putchar(c + key[i]); } else { // decode the current character putchar(c - key[i]); } // increment the position in the key, without overflow i = (i + 1) % strlen(key); } } |
Usage
Encode a string with a given key and display the result:
echo "a string I would like to encode" | ./crypto E "the key we use to encode the string" |
Encode a string with a given key and store the result in a file:
echo "a string I would like to encode" | ./crypto E "the key we use to encode the string" > path/to/encodedStringFile.txt |
Encode the contents of a file with a given key and store it:
cat path/to/clearFile | ./crypto E "the key we use to encode the string" > path/to/encodedFileName |
Decode the contents of a file with a given key and output it:
cat path/to/encodedFile | ./crypto D "the key we use to encode the string" |
Decode the contents of a file with a given key and store it:
cat path/to/encodedFile | ./crypto D "the key we use to encode the string" > path/to/decodedFileName |
I will definitely try this program