Rijndael Algorithm + Padding error...


  • Hi all

    I am trying to encrypt and decrypt data using the Rijndael alogrithm.  I have been successfull in encrypting and decrypting the data in one go.  However problems arise when I attempt to save the key and the IV value and return at a later time to decrypt the data,

    The error I am getting is as follows: "System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed."


    Here is the code that I am using to encrypt and decrypt the data:

    Imports System.web


    imports system.web.service.protocols

    imports system

    imports system.text



    Dim  RijndaelAlg as Rijndael = Rijndael.Create

    <webmethod()> _

    Private Sub EncryptTextToFile(ByVal data As String, ByVal filename As String, ByVal key() As Byte, ByVal IV() As Byte)
            Dim fStream As FileStream = File.Open(filename, FileMode.OpenOrCreate)

            Dim RijndaelAlg As Rijndael = Rijndael.Create
            Dim cStream As New CryptoStream(fStream, RijndaelAlg.CreateEncryptor(key, IV), CryptoStreamMode.Write)

            Dim sWriter As New StreamWriter(cStream)


            Catch ex As Exception
            End Try
        End Sub

    I use the following two functions to extract the key and the IV

    <webmethod()> _

    Public Function getKey() As String
            'Return convertToString(RijndaelAlg.Key)
            Return Convert.ToBase64String(RijndaelAlg.Key)
        End Function

        <WebMethod()> _
        Public Function getIV() As String
            'Return convertToString(RijndaelAlg.IV)
            Return Convert.ToBase64String(RijndaelAlg.IV)
        End Function

    Here is the method that should decrypt the data:

    <WebMethod()> _
            Public Function DecryptTextFromFile2(ByVal filename As String, ByVal key As String, ByVal iv As String) As String
            DecryptTextFromFile2 = Nothing
            Dim fstream As FileStream = File.Open(filename, FileMode.OpenOrCreate)

            Dim rijndaelalg As Rijndael = Rijndael.Create
            Dim cStream As New CryptoStream(fstream, rijndaelalg.CreateDecryptor(Convert.FromBase64String(key), Convert.FromBase64String(iv)), CryptoStreamMode.Read)
            Dim sreader As New StreamReader(cStream)

            Dim val As String = Nothing
                val = sreader.ReadLine
                Return val
            Catch ex As Exception
            End Try
        End Function


    The error occurs at the val = sreader.ReadLine line. 




    Tuesday, January 31, 2006 2:51 PM


All replies

  • Hello,

    I'm going to move your question to the Common Language Runtime where people should have more expertise on the Security related namespaces.  This forum is really only for ASP.NET Web Services specific questions.


    Daniel Roth

    Wednesday, February 01, 2006 12:22 AM
  • Hi Mike,

    I suggest that you read Ivan Medvedev's article on usign the crypto streams:  He gives a sample of how to do this properly with Rinjdael -- the tricky bit is making sure that the stream gets closed at the right time so that your padding is written properly.


    Tuesday, February 07, 2006 5:15 PM
  • I had the same problem, but when I added

    rijndael.Padding = PaddingMode.None;

    when crypting and decrypting I never saw this error again.
    Hope it will help you.
    Saturday, March 18, 2006 8:09 PM
  • If you will see the same error after this, try to change PaddingMode.
    Use for example ISO10126, but as far as I understood, you should than remove padding data after decryption.
    Sunday, March 19, 2006 10:10 AM
  • This error was occuring for me while reading from and decrypting a file. Strangely enough, I found that the error only occured for me when I didn't read to the end of the file. As long as I read until there was no data left in the file before trying to close it, the CrytpoStream's close function wouldn't throw an error.
    Friday, April 07, 2006 2:04 AM
  • I get the same problem.

    If i take the byte array I can decrypt it, but if I save that array as a string or whatever and then try to decrypt it I get the padding error.



    Thursday, April 20, 2006 9:06 PM
  • The Encoding class is not meant to round trip arbitrary data, and is likely mangling your ciphertext.  Check out for more information.


    Thursday, April 20, 2006 9:11 PM
  • I am using the code below right out of MSDN


    I have 2 programs/2005 VS projects: EncryptR and DecryptR. I put the statement in both projects .cs files


              rijndael.Padding = PaddingMode.None;   didn't work


         I use xmlDoc.Save and xmlDoc.Load so I cannot apply flush!


    I even tried PKCS7: Next I'll try removing : xmlDoc.PreserveWhitespace = true;


    // Create a new Rijndael key.

    key = new RijndaelManaged();

    key.Padding = PaddingMode.PKCS7;

    // Load an XML document.

    XmlDocument xmlDoc = new XmlDocument();

    xmlDoc.PreserveWhitespace = true;


    // Encrypt the "passWord" element.

    Encrypt(xmlDoc, "passWord", key);


    Console.WriteLine("The element was encrypted");


    //Decrypt(xmlDoc, key);


    //Console.WriteLine("The element was decrypted");


    Tuesday, February 06, 2007 1:38 AM
  • Hi Shawn,


    Thanks a lot for sharing this code.  It works just right!





    Wednesday, March 14, 2007 5:22 PM
  • I have this error when I try to dectypt a file.
    please help me if you can.
    the code is:

     Sub DecryptTextFromFile(ByVal Key() As Byte, ByVal IV() As Byte)
            Dim var As String = My.Application.Info.DirectoryPath + "\text.txt"

                ' Create or open the specified file.
                Dim fStream As FileStream = File.Open(var, FileMode.OpenOrCreate)

                ' Create a new Rijndael object.
                Dim RijndaelAlg As Rijndael = Rijndael.Create

                ' Create a CryptoStream using the FileStream
                ' and the passed key and initialization vector (IV).
                Dim cStream As New CryptoStream(fStream, _
                                                RijndaelAlg.CreateDecryptor(Key, IV), _

                'RijndaelAlg.Padding = PaddingMode.PKCS7

                ' Create a StreamReader using the CryptoStream.
                Dim sReader As StreamReader = New StreamReader(cStream)

                Dim var23 As String = sReader.ReadLine()

                'Read the data from the stream
                'to decrypt it.
                Dim val As String = ""

                    val = sReader.ReadLine()

                Catch e As Exception
                    MessageBox.Show("An error occurred: {0}", e.Message)
                    ' Close the streams and
                    ' close the file.

                End Try

                TextBox3.Text = val

            Catch e As CryptographicException
                MessageBox.Show("A Cryptographic error occurred: {0}", e.Message)
                'Return Nothing
            Catch e As UnauthorizedAccessException
                MessageBox.Show("A file error occurred: {0}", e.Message)
                'Return Nothing
            End Try

        End Sub

    Thursday, August 16, 2007 10:06 AM
  • You get this problem when the KEY, the IV and the ENCRYPTED DATA are not all of the correct block sizes and 'scheme'. The only way to avoid this problem is to use the IV and KEY generated by the algorithm. You can use GenerateIV to get the algorithm to generate you an IV. Store this away somewhere safe as you will need it. Then simply call the encrypt method and pass in the data. The algorithm will then encrypt the data and set the Key property to the newly generated key. Store this with your encrypted data. That's all there is to it.



    Monday, April 14, 2008 4:34 PM