I’ve been trying to find out the correct way to encrypt a byte[16] variable using DES algorithm. Here’s the scenario:
- The data should be encrypted in 8-byte parts. the key for encryption is:
byte[] {11, 11, 11, 11, 11, 11, 11, 11} - First 8 bytes is encrypted using
Instance Vector = new byte[8](8 bytes with 0 value). - the encrypted result will be the IV for the next 8 bytes. (is this CBC?)
- that last 8 byte is the result I should send.
With this information, I have implemented the Encrypt method as follows:
public static byte[] Encrypt(byte[] data)
{
var dataChunk = new byte[8];
var IV = new byte[8];
var result = new byte[8];
var key = new byte[] { 11, 11, 11, 11, 11, 11, 11, 11 };
for (int counter = 0; counter < data.Length / 8; counter++)
{
// Copy the next 8-byte chunk.
Array.Copy(data, counter * 8, dataChunk, 0, 8);
var des = System.Security.Cryptography.DES.Create();
des.Key = key;
des.IV = IV;
des.Padding = PaddingMode.None;
ICryptoTransform cryptoTransform = des.CreateEncryptor(key, IV);
// Encrypt the datra chunk.
cryptoTransform.TransformBlock(dataChunk, 0, 8, result, 0);
// Set the new IV.
Array.Copy(result, IV, 8);
}
return result;
}
Is this the correct way of encrypting data using DES cryptography?
You don’t need to create an encryptor for each block. The encryptor itself implements the operation modes (CBC, …) and padding.
So you need something like this:
I’m omitting the warning of using DES here. You might also want to take a look at CryptoStream afterwards for an even easier en- and decryption …