madCrypt Unit 

Content / madBasic /...
www.madshi.net

One of my customers asked me to add encryption to madExcept, so I looked on the net and found that the blowfish encryption is good, easy, fast and besides also patent free. So here it is. madCrypt is a simple Delphi blowfish implementation. No fancy features, just the basic encryption. I've successfully tested madCrypt against blowfish test vectors, so I can say that everything is in order.

There are two overloaded Encrypt/Decrypt functions, one works with a Delphi string (my favorite), the other one with a dumb pointer. Just use what makes more sense for you.

The string variation automatically adds padding bytes to the end of the data. When decrypting such a string, the padding bytes get deleted again, of course. This logic makes sure that you can encrypt strings of any length.

The pointer variation in contrast does not change the length of the data. Encryption only works in 8 byte chunks, so here odd bytes will remain unencrypted. That means: When using the pointer variation of the "Encrypt" function, please make sure that the data size is a multiple of 8.

If you leave the initialization vector "iv" uninitialized, madCrypt uses the simplest form of encryption ("ECB"). If you specify an initialization vector, madCrypt uses the counter mode ("CTR"), which is another bit safer.

CAUTION: The version 1.1 (or higher) of madCrypt is not compatible with the 1.0 version. If you need to use the old way of encrypting/decrypting, you can use the functions "OldEncrypt" and "OldDecrypt", which are supported for compatability reasons.

procedure Encrypt (var data: string; password: string; iv: int64 = 0); overload;
procedure Decrypt (var data: string; password: string; iv: int64 = 0); overload;

procedure Encrypt (buf: pointer; len: dword; password: string; iv: int64 = 0); overload;
procedure Decrypt (buf: pointer; len: dword; password: string; iv: int64 = 0); overload;

// Example:
strVar := 'Currently this is readable, but not for long...';
Encrypt(strVar, 'D0n''t u5e weak pa55w0rd5!');
Decrypt(strVar, 'D0n''t u5e weak pa55w0rd5!');
ShowMessage(strVar);

Sometimes you will need to store encrypted data as a clear text, e.g. when storing an encrypted password in an ini file. For this purpose madCrypt now also offers base64 encoding/decoding. This is a widely used encoding method which converts binary data to readable text. Because readable text can only consist of a subset of characters, the resulting buffer will always be bigger than the original buffer. Base64 encoding is used for mailing binary attachments, btw.

function Encode (data: string) : string; overload;
function Decode (data: string) : string; overload;

function Encode (data: pchar; len: integer) : string; overload;
function Decode (data: pchar; len: integer) : string; overload;

// Example:
strVar := 'Currently this is readable, but not for long...';
Encrypt(strVar, 'D0n''t u5e weak pa55w0rd5!');
ShowMessage(Encode(strVar));