Search code examples
c#cryptographyencryption-symmetric

Empty or null array using System.Security.Cryptography


I'm trying to use the AES encryption method in C# using this code:

public static byte[] encryptData(string plaintext)
    {
        Aes myAes = Aes.Create();
        byte[] encrypted = EncryptStringToBytes_Aes(plaintext,myAes.Key, myAes.IV);
        return encrypted;
    }

static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;
        Aes aesAlg = Aes.Create();
        aesAlg.Key = Key;
        aesAlg.Key = IV;
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
        MemoryStream msEncrypt = new MemoryStream();
        CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
        StreamWriter swEncrypt = new StreamWriter(csEncrypt);
        swEncrypt.Write(plainText);
        encrypted = msEncrypt.ToArray();
        return encrypted;
    }

And calling the functions like this:

byte[] encrypt = Security.encryptData("Hi, how are you?");

But the returned byte array is always empty.

I'm trying to use this to encrypt values like passwords on my app.config file.


Solution

  • Put you streams in using or use Close method to Dispose of them.

    static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        // your code
        byte[]  plainBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] encrypted;
        Aes aesAlg = Aes.Create();
        aesAlg.Key = Key;
        aesAlg.Key = IV;
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
        using(MemoryStream ms = new MemoryStream())
        {
            using(CryptoStream csEncrypt = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                csEncrypt.Write(plainBytes,0, plainBytes.Length );
                csEncrypt.FlushFinalBlock();
                return msEncrypt.ToArray();
            }
        }
    }