title: System.Security.Cryptography.CryptographicException: Bad Data
body: <p>I am having this bad data problem when I tried to open it. Any idea how to solve it? When I debug it shows that <code>CryptoStream.FlushFinalBlock()</code> is having a problem. See codes below.</p>
  
  <pre><code>Public Class Encryption
    Public Function Encrypt(ByVal plainText As String) As Byte()
  
      Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
      Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
  
  
      Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
  
      ' The ICryptTransform interface uses the TripleDES 
      ' crypt provider along with encryption key and init vector 
      ' information 
      Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
  
  
      Dim encryptedStream As MemoryStream = New MemoryStream()
      Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
  
  
      cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
      cryptStream.FlushFinalBlock()
      encryptedStream.Position = 0
  
      Dim result(encryptedStream.Length - 1) As Byte
      encryptedStream.Read(result, 0, encryptedStream.Length)
      cryptStream.Close()
      Return result
    End Function
  
    Public Function Decrypt(ByVal inputInBytes() As Byte) As String 
      ' UTFEncoding is used to transform the decrypted Byte Array 
      ' information back into a string. 
      Dim utf8encoder As UTF8Encoding = New UTF8Encoding() 
      Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
  
      ' As before we must provide the encryption/decryption key along with 
      ' the init vector. 
      Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateDecryptor(Me.key, Me.iv)
  
      ' Provide a memory stream to decrypt information into 
      Dim decryptedStream As MemoryStream = New MemoryStream()
      Dim cryptStream As CryptoStream = New CryptoStream(decryptedStream, cryptoTransform, CryptoStreamMode.Write)
      cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
      cryptStream.FlushFinalBlock()
      decryptedStream.Position = 0
  
      ' Read the memory stream and convert it back into a string 
      Dim result(decryptedStream.Length - 1) As Byte
      decryptedStream.Read(result, 0, decryptedStream.Length)
      cryptStream.Close()
      Dim myutf As UTF8Encoding = New UTF8Encoding()
      Return myutf.GetString(result)
    End Function
  End Class
  </code></pre>