11/21/2011

Crypto-tools - Caesar Cipher 2

The exams are over, thank God :) Now, last time I tried to explain a simple program to encrypt and decrypt Caesar cipher. The thing is I did it in a pretty silly way. I didn't explain anything, I just wrote a piece of code and let you do whatever you want with it.

Today I started something new. I am making Crypto-tools to be a real project, with explanations, comments, standardized function declarations etc. So, whenever I add something new to it, I'll write a post here and add the code to the repository, so you can download it, test it, post questions and so on.

Last time we wrote two functions: encrypt() and decrypt(), which both work if the input string is properly formatted. What's really embarrassing is that I didn't make a single comment on the code. So, here's how stuff works:

In the beginning, both functions take three arguments: input, key and output, which are of char * or int *. Inside those functions, we used some properties of strings to iterate... You know, every string of characters is ended with '\0' (ASCII 0), so if we need to parse a string of chars, we can do it char by char until we find 0, which will say: "Stop! You've reached the end", or something like that.

Now, the other thing we use is that we don't need any counters or something - we have a copy of the pointer to the beginning of an array which we will parse character by character, not going backwards at any single moment. So, we may change the pointers we get from the calling function and use them to iterate through memory. In order to understand this, you should be familiar with pointers basics, and if you're not already - a tutorial is being prepared and will be here as soon as possible, I promise :)

The steps in the functions are:
  1. Take the current letter from the input and make sure it's not zero (if it is, jump to #4)
  2. Apply encrypting (or decrypting) function as defined and assign that value to the output letter
  3. Increase input and output pointers and repeat #1
  4. Mark the end of the output string with a 0
Completing this algorithm, you will have an output string, which is encrypted (or decrypted) input with the entered key.

Now, what if the input is not properly formatted? Well, you may not know, but the output string could be shorter than the input string, it could contain non-printable characters and get some rubbish output. So, in order to use those functions "as are", you will have to pass valid arguments to them. Next time I'll give you a simple validation function, which will convert string to caps, and make sure everything non-letter will be left out of the string. That function will be used in almost every single module of Crypto-tools.

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!