3DES
The DES algorithm has been around for a long time, and the 56-bit version is now easily crackable (in less than a day on fairly most equipment). An enhancement, and one which is still fairly compatible with DES, is the 3-DES algorithm. It has three phases, and splits the key into two. Overall the key size is typically 112 bits (with a combination of the three keys - of which two of the keys are the same). The algorithm is EncryptK3( DecryptK2( EncryptK1(message), where K1 and K3 are typically the same (to keep compatibility).
Encrypted stream:
and to test, the decrypted text is:
In this case, if we try "test" as the key we get:
"Specified key is a known weak key for 'TripleDES' and cannot be used." and it will not encrypt.
As a test: "Hello how are you?" with a stronger key of "m65hhhgfd" which should give:
B8841E83139EDF87AE0D033162CFE174A968ED820FA86C01
The code is:
TripleDES threedes = new TripleDESCryptoServiceProvider();
try
{
threedes.Key = StringToByte(this.tbKey.Text, 24); // convert to 24 characters - 192 bits
threedes.IV = StringToByte(" ");
byte[] key = threedes.Key;
byte[] IV = threedes.IV;
ICryptoTransform encryptor = threedes.CreateEncryptor(key, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
// Write all data to the crypto stream and flush it.
csEncrypt.Write(StringToByte(this.tbMessage.Text), 0, StringToByte(this.tbMessage.Text).Length);
csEncrypt.FlushFinalBlock();
// Get the encrypted array of bytes.
byte[] encrypted = msEncrypt.ToArray();
this.tbEncrypt.Text = ByteToString(encrypted);
ICryptoTransform decryptor = threedes.CreateDecryptor(key, IV);
// Now decrypt the previously encrypted message using the decryptor
MemoryStream msDecrypt = new MemoryStream(encrypted);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
this.tbDecrypt.Text = ByteToString(csDecrypt);
}
catch (Exception ex)
{
this.tbEncrypt.Text = ex.Message.ToString();
}
|