Cryptography with Oxygene

One of my favorite development topics is Cryptography, and my favorite language is Oxygene. The Oxygene language has some great features that are well suited to advanced programming tasks like cryptography.

For example, it makes it very easy to work with the AesManaged class in the .NET Framework. When you construct an instance of the AesManaged class, it initializes both the Key and the initialization vector (IV) with new random values. Tuples are a great option for returning both of these values from a single method.

classmethod OxygeneCrypto1.GenerateKeys: tuple of(AESBlock, AESKey);beginusing aes := AesFactory doexit(aes.IV, aes.Key);end;

When calling this method, you just use the syntax (IV, Key) := GenerateKeys; and the two local variables receive the values from the Tuple. This is much better than using out functions or creating a custom object just to hold the two values.

Oxygene’s awesomeness doesn’t stop there. Here is a method to encrypt a string with AES and the provided key. It first compresses the string – this strengthens the encryption and reduces the size of the ciphertext. Input parameters are validated with require statements, and ensure statements are used to verify it worked correctly. Nested using statements manage the life-cycle of all the handles. The result is much more concise code that is clearer and easier to maintain than the alternative in other languages.

classmethod OxygeneCrypto1.encrypt(plainText: String; Key: AESKey; IV: AESBlock):arrayof Byte;requireassigned(plainText):'The method encrypt requires the plainText parameter to be defined.'; plainText.Length > 0:'The method encrypt requires the plainText parameter to be defined.';assigned(Key):'The method encrypt requires the Key parameter to be defined.';assigned(IV):'The method encrypt requires the IV parameter to be defined.'; Key.Length= AESKeyLength :'Invalid Key Length when calling encrypt.'; IV.Length= AESBlockLength :'Invalid IV Length when calling encrypt.';beginusing aesAlg := AesFactory(Key, IV)dousing encryptor: ICryptoTransform := aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)dousing output :=new MemoryStream()dousing encStrm :=new CryptoStream(output, encryptor, CryptoStreamMode.Write)dousing gzip :=new DeflateStream(encStrm, CompressionLevel.Fastest)dousing writer :=new StreamWriter(gzip)dobegin writer.Write(plainText);   // Close writer to prepare the output writer.Close();   exit output.ToArray();end;ensureassigned(result):'Undefined result from encrypt.';result.Length > 0:'Undefined result from encrypt.';end;

The decryption method is just as clear and concise. Take a look at the example download to see how it all fits together.

I hope to make this a series of posts on different cryptography solutions with the different platforms each flavor of the Oxygene language supports. So let me know if you find Cryptography as interesting as I do. There are so many other topics to cover, too!