How to return byte[] when decrypt using CryptoStream (DESCryptoServiceProvider)

Abraham Putra Prakasa picture Abraham Putra Prakasa · Jul 23, 2014 · Viewed 16.3k times · Source

This is a beginner question,

Every time I search on the internet, decrypt with DESCryptoServiceProvider function always returning a string.

How can we get byte[] for the return?

This is the code. Thank you for any help.

DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
cryptoProvider.Padding = PaddingMode.None;
cryptoProvider.Mode = CipherMode.CBC;

MemoryStream memoryStream = new MemoryStream(value);
CryptoStream cryptoStream = new CryptoStream(memoryStream, 
cryptoProvider.CreateDecryptor(password, initVector), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryptoStream);

return reader.ReadToEnd();            
//how to return byte[];

Answer

Tomtom picture Tomtom · Jul 23, 2014

I had this problem too, and I created a class with some functions to help me with this issues.

The function to perform the cryptography is:

private byte[] PerformCryptography(ICryptoTransform cryptoTransform, byte[] data)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(data, 0, data.Length);
                    cryptoStream.FlushFinalBlock();
                    return memoryStream.ToArray();
                }
            }
        }

The ICryptoTransform is either a spezific encryptor or decryptor.

This Method works for symmetric altorithm's

Just for example, the methods for encryption and decryption look like:

public byte[] Encrypt(byte[] data)
{
    if (CanPerformCryptography(data))
    {
        using (var encryptor = _algorithm.CreateEncryptor(_key, _iv))
        {
            return PerformCryptography(encryptor, data);
        }
    }
    return data;
}

public byte[] Decrypt(byte[] data)
{
    if (CanPerformCryptography(data))
    {
        using (var decryptor = _algorithm.CreateDecryptor(_key, _iv))
        {
            return PerformCryptography(decryptor, data);
        }
    }
    return data;
}