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

1

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[];
Continuous answered 23/7, 2014 at 6:47 Comment(0)
C
38

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;
}
Curtis answered 23/7, 2014 at 6:53 Comment(4)
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 againContinuous
i catch the exception, its not null key but weak key exception. and i found the solution hereContinuous
What do you test in CanPerformCryptography?Osmium
Not much. return data != null && data.Length > 0Curtis

© 2022 - 2024 — McMap. All rights reserved.