Triple DES Encryption in Xamarin.Forms using Bouncy Castle

The System.Net.Cryptography library is not available in a PCL and one has to revert to 3rd party libraries in order to carry out crytography tasks.

Not all 3rd party libraries implement Triple DES Encryption, mainly because it is not as secure as other algorithms such as AES and can be broken in a faster than brute force time.

It is advisable to use other algorithms such as AES, Blowfish, Twofish if you are not constrained by the encryption algorithm to implement.

If you however have to implement Triple DES, the bouncy castle PCL nuget package provides a library for it.
Bouncy castle also have a standard library package that can be used in your standard library project.

Add the bouncy castle library to your project: Install-Package Portable.BouncyCastle

You can then use the method below to carry out the encryption:

public static string TripleDESEncrypt(string toEncrypt, string key, bool useHashing = true)
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

    //If hashing, get MD5 hashcode regards to your key
    if (useHashing)
	    //initialize MD5
	    MD5Digest dig = new MD5Digest();

	    //get byte array of key to use
	    byte[] msgBytes = Encoding.UTF8.GetBytes(key);
	    dig.BlockUpdate(msgBytes, 0, msgBytes.Length);
	    //initialize the key array's size
	    keyArray = new byte[dig.GetDigestSize()];
	    //complete the hashing
	    dig.DoFinal(keyArray, 0);
        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    //create Triple DES encryption engine
    DesEdeEngine desedeEngine = new DesEdeEngine();

    //create a padded block cipher using the default PKCS7/PKCS5 padding
    BufferedBlockCipher bufferedCipher = new PaddedBufferedBlockCipher(desedeEngine);

    // Create the KeyParameter for the DES3 key generated. 
    KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DESEDE", keyArray);

    //initialize the output array
    byte[] output = new byte[bufferedCipher.GetOutputSize(toEncryptArray.Length)];
    bufferedCipher.Init(true, keyparam);

    //carry out the encryption
    output = bufferedCipher.DoFinal(toEncryptArray);

    //Return the encrypted data into unreadable string format
    return Convert.ToBase64String(output, 0, output.Length);

Here, the key is hashed using MD5 if hashing is required before the string toEncrypt is encrypted using Triple DES with PKCS7/PKCS5 padding.

The full specification of the BouncyCastle library can be found here.