In his infamous rant
Why Pascal Is Not My Favorite Programming Language Brian Kernighan says
"There is a paucity of operators ... In particular, there are no bit-manipulation operators (AND, OR, XOR, etc.). I simply gave up trying to write the following trivial encryption program in Pascal:
i := 1;
while getc(c) <> ENDFILE do begin
putc(xor(c, key[i]));
i := i mod keylen + 1
end
because I couldn't write a sensible 'xor' function."
The amazing part of this statement is that I cannot fathom why he found it so hard to write an xor function. It's simply not that hard. In this post we take up the challenge.
We will assume that Kernighan's compiler did not have the type Byte and this may one source of his problem. However, Byte is simply a subrange of the integers (0 .. 255) so this is easily surmounted. We can also safely assume that he had access to the Boolean operators NOT, OR and AND...
Posted on Saturday, January 19, 2008 at 5:42 PM
The next program is one which appeared in the original
Software Tools but not in
Software Tools in Pascal. The program is
Crypt which encrypts and decrypts a text file.
The algorithm for the encryption is what cryptologists call a "one time pad" (google it). When properly used it is theoretically unbreakable. What we are doing here does not include all the steps entailed in properly using the algorithm but it should prevent the casual snoop from decoding your files.
The algorithm consists of merging the input stream of data with a second stream, the key, to produce an output stream of encrypted data. We extract the ascii codes from each char of input and from each char of the key. A bitwise
XOR operation gives us the ascii code for the output which is converted back to a char. Here is the code for
Crypt.
Program Crypt ;
{
Crypt -- encrypt and decrypt
}
var
Key : String ;
KeyLen : Byte ;...