18

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[];
SharpC
  • 6,974
  • 4
  • 45
  • 40

1 Answers1

37

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;
}
Tomtom
  • 9,087
  • 7
  • 52
  • 95
  • hello Tomtom, i use try catch to do PerformCryptography, if the _key using 8 byte of 0 (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) it return catch. i think the decryptor found that the key are null (in this case not null but 8 byte of 0x00). how to make it right? thx again – Abraham Putra Prakasa Jul 23 '14 at 08:38
  • 1
    i catch the exception, its not null key but weak key exception. and i found the solution [here](http://social.msdn.microsoft.com/Forums/en-US/8fdfcce7-3a8a-4271-8557-3df715c80df8/weak-key-cryptographic-exception) – Abraham Putra Prakasa Jul 24 '14 at 03:25
  • What do you test in CanPerformCryptography? – Maulik Modi Jan 20 '22 at 10:12
  • Not much. `return data != null && data.Length > 0` – Tomtom Jan 21 '22 at 13:52