11/14/2011

Crypto-tools - Caesar Cipher 1

Hi guys. Sorry for not writing too long, I have a lack of time these days because of my exams. So, I'll keep it short.

I started developing some tools for cryptography, that would basically cover my cryptography course in this semester. In order to keep this post as short as possible: if you want to know more about Caesar cipher, please visit Wikipedia: Caesar cipher. Now, let's do some coding.

Caesar cipher is really simple to implement. In this basic variation, we will assume the P and C sets (plain and cipher alphabets, respectively) are {'A'-'Z'} (capital letters of the English alphabet). These sets can later be expanded to the whole ASCII table. We need to enter key - an integer from {1-25} (encrypting with 0 would give as plaintext as result), which is the number of rotations of the plain alphabet to get the cipher alphabet.

The encryption function is:
E(x) = (x + n) mod 26
for every letter x in plaintext. The decryption function is its inverse:
D(e) = (x - n) mod 26
Notice that modular operations in C don't work properly for negative numbers, so you may actually wish to add an extra 26:
D(e) = (x - n + 26) mod 26
Also notice that x is the order of letter x in alphabet rather than ASCII code for x: x('A')=0 etc. The shortest way to get the order of letters in alphabet is to subtract ASCII 'A' from it. You don't actually need an ASCII table - characters in C are stored as their ASCII codes. When you encrypt it, add 'A' to it to get it's ASCII :)

Now, let the function declarations be:
void encrypt(char *input, int *key, char *output);
void decrypt(char *input, int *key, char *output);
So, the functions will take input and output arrays of chars. But why int *key? Suppose this will be standard header for encryption and decryption functions done here, in some complex cryptosystems the key won't be a single integer as here.

Now, the functions, assuming that the input string contains only 'A'-'Z' chars, without any other characters:
void encrypt(char *input, int *key, char *output) {
  while (*input != 0) {
    *output = (*input - 'A' + *key) % 26 + 'A';
    input++;
    output++;
  }
  *output = 0;
}

void decrypt(char *input, int *key, char *output) {
  while (*input != 0) {
    *output = (*input - 'A' - *key + 26) % 26 + 'A';
    input++;
    output++;
  }
  *output = 0;
}
As you can see, they are pretty much the same. I'm really out of time now, but in the next part, I will explain the code and give some tips for modifying it. Meanwhile, you can play around with it. Just don't forget that the arguments are not checked, so you can get some weird results on wrong inputs. I'll try to write part 2 of this text as soon as possible. Thanks for reading!

No comments:

Post a Comment

If you have anything useful to say (ideas, suggestions, questions, business proposals, or just "Thank you!"), please feel free to comment! Also, you can use my e-mail and/or find me on Twitter!