Search code examples
c#aesrijndaelmanaged

AES Encryption using RijndaelManged Class: Baes64 encoding and decoding aes encryption string


So, I am having an issue with decrypting the decoded base64 aes string. Is this possible? I wrote a small console program to work this out but no luck. Here is my example:

enter image description here

As depicted, I have successfully converted the base64 back the aes encrypted string, but when I try to decrypt it I get more junk. If a code snippet is need let me. Thank you all for your help :) UPDATE: Code snippet for decrypting method

static void Main(string[] args)
    {
        string plainText;
        string decrypted;
        string decryptedFromB64EncodedDecoded;
        string fromBase64ToEncryptedText;
        string encryptedText;
        string encryptedTextBase64;
        byte[] encryptedBytes;

        byte[] encryptedBytes2;
        byte[] encryptedBytesBase64;

        RijndaelManaged crypto = new RijndaelManaged();

        UTF8Encoding UTF = new UTF8Encoding();

        Console.WriteLine("Please put in the text to be encrypted.");
        plainText = Console.ReadLine();

        try
        {
            encryptedBytes = encrypt(plainText, crypto.Key, crypto.IV);
            encryptedText = Encoding.ASCII.GetString(encryptedBytes);
            //encryptedBytes2 = Encoding.ASCII.GetBytes(encryptedText);

            encryptedTextBase64 = toBase64String(encryptedText);
            encryptedBytesBase64 = fromBase64String(encryptedTextBase64);

            fromBase64ToEncryptedText = Encoding.ASCII.GetString(encryptedBytesBase64);

            encryptedBytes2 = Encoding.ASCII.GetBytes(fromBase64ToEncryptedText);

            decrypted = decrypt(encryptedBytes, crypto.Key, crypto.IV);
            decryptedFromB64EncodedDecoded = decrypt(encryptedBytes2, crypto.Key, crypto.IV);

            Console.WriteLine("Start: {0}", plainText);
            Console.WriteLine("Encrypted: {0}", encryptedText);
            Console.WriteLine("Encrypted Base64: {0}", encryptedTextBase64);
            Console.WriteLine("From Base64 To AES Encypted Text: {0}", fromBase64ToEncryptedText);
            Console.WriteLine("Decrypted: {0}", decrypted);

            Console.WriteLine("Decrypted From Encode and then Decode Base64 Text: {0}", decryptedFromB64EncodedDecoded);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.Message);
        }

        Console.ReadLine();
    }

public static string decrypt (byte[] textToDecrypt, byte[] key, byte[] IV)
    {
        RijndaelManaged crypto = new RijndaelManaged();
        MemoryStream stream = new MemoryStream(textToDecrypt) ;
        ICryptoTransform decryptor = null;
        CryptoStream cryptoStream = null;
        StreamReader readStream = null;

        string text = string.Empty;

        try
        {
            crypto.Key = key;
            crypto.IV = IV;
            crypto.Padding = PaddingMode.None;

            decryptor = crypto.CreateDecryptor(crypto.Key, crypto.IV);
            cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);
            //cryptoStream.Read(textToDecrypt, 0, textToDecrypt.Length);
            readStream = new StreamReader(cryptoStream);
            text = readStream.ReadToEnd();
            cryptoStream.Close();

            byte[] decodedValue = stream.ToArray();

            return text;
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (crypto != null)
            {
                crypto.Clear();
            }
            stream.Flush();
            stream.Close();
        }
    }

public static byte[] encrypt(string text, byte[] key, byte[] IV)
    {
        RijndaelManaged crypto = null;
        MemoryStream stream = null;

        //ICryptoTransform is used to perform the actual decryption vs encryption, hash function are a version crypto transforms
        ICryptoTransform encryptor = null;
        //CryptoStream allows for encrption in memory
        CryptoStream cryptoStream = null;

        UTF8Encoding byteTransform = new UTF8Encoding();

        byte[] bytes = byteTransform.GetBytes(text);

        try
        {
            crypto = new RijndaelManaged();
            crypto.Key = key;
            crypto.IV = IV;

            stream = new MemoryStream();

            encryptor = crypto.CreateEncryptor(crypto.Key, crypto.IV);
            cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);
            cryptoStream.Write(bytes, 0, bytes.Length);

        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
            if (crypto != null)
            {
                crypto.Clear();
            }
            cryptoStream.Close();
        }

        return stream.ToArray();
    }

 public static string toBase64String(string value)
    {
        UTF8Encoding UTF = new UTF8Encoding();
        byte[] myarray =  UTF.GetBytes(value);
        return Convert.ToBase64String(myarray);
    }

    public static byte[] fromBase64String(string mystring)
    {
        //UTF8Encoding UTF = new UTF8Encoding();
        //byte[] myarray = UTF.GetBytes(value);
        return Convert.FromBase64String(mystring);
    }

Solution

  • I don't know how you're decrypting but before you decrypt, you should convert the base 64 string to a byte array before sending it into the decryption.

    byte[] encryptedStringAsBytes = Convert.FromBase64String(base64EncodedEncryptedValue);
    

    Then with the byte array you can pass to the CryptoStream via a MemoryStream.

    UPDATE

    I believe the issue is how you're setting up your streams

                using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
                {
                    rijndaelManaged.Padding = paddingMode;
                    rijndaelManaged.Key     = key;
                    rijndaelManaged.IV      = initVector;
    
                    MemoryStream memoryStream = null;
                    try
                    {
                        memoryStream = new MemoryStream(valueToDecrypt);
                        using (ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor())
                        {
                            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read))
                            {
                                using (StreamReader streamReader = new StreamReader(cryptoStream))
                                {
                                    return streamReader.ReadToEnd();                       
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (memoryStream != null)
                            memoryStream.Dispose();
                    }
                }    
    

    UPDATE 2

    This is how you should basically perform the steps.

    To encrypt

    1. Encode your plain text string using the Encoding.GetBytes(stringToEncrypt)
    2. pass the byte[] into the crypto API (via memory stream, etc.)
    3. get the bytes from the encrypted stream and encode the results as Base64

    To Decrypt (do the reverse)

    1. Convert the base64 encoded string to bytes using Convert.FromBase64String(base64EncodedEncryptedValue)
    2. pass that byte array into your decryption function above