We help IT Professionals succeed at work.

Encryption/decryption of file

Last Modified: 2013-11-07

This question follows on from 21556745.

I used the example question 21556745 in a desktop form fine and it works. However if I use the DLL in a web application I get problems with

       A first chance exception of type 'System.FormatException' occurred

The aspx page loads an encrypted textfile then tries to decrypt it to a string.

Here's my code to load a file and then try to decrypt it to a string...

        If FileUpload1.HasFile Then
            Dim intFileLength As Integer, bytData() As Byte
            Dim objStream As System.IO.Stream

            intFileLength = FileUpload1.PostedFile.ContentLength
            ReDim bytData(intFileLength)
            objStream = FileUpload1.PostedFile.InputStream
            objStream.Read(bytData, 0, intFileLength)

            Dim fileContents As String = Encoding.ASCII.GetString(bytData)
            'this displays the file contents
            Me.TextBox_ReadFromFile.Text = fileContents    
            'attempt to decrypt the string            
            Dim decrypted As String = Crypto.Decrypt(fileContents, "theKeyHEre")

           'ERROR Happens here...
            Me.DecryptedFromFile.Text = fileContents
   End If

so....text loads fine but decrypt doesn't work.

However, if I have the following code in design mode
  fileContents = "a long string with exactly the same as is in the file being uploaded"
  decrypted = Crypto.Decrypt(fileContents, "theKeyHEre")
there is no error and the text decrypts fine.

Why would this be happening?  Text loaded from a file doesn't decrypted, the same text hard coded into class does - what's the solution? This is a strange one..

Watch Question

Does this line work?

Me.TextBox_ReadFromFile.Text = fileContents


yes it does work however displays blank
its the line
Dim decrypted As String = Crypto.Decrypt(fileContents, "theKeyHEre")

that throws exception in the Decrypt method
and returns a blank string/nother
Top Expert 2007
This one is on us!
(Get your first solution completely free - no credit card required)



Thanks for the feedback;

I don't really have a chance to change the encryption method used. The project I am on is the transfer of a desktop application to a web application, The desktop application has used the above encryption method to save files and users would like files created on the desktop version to open in the new web version

Maybe there's an answer out there !
Top Expert 2007

Oh, gotcha.  Well, it was worth a shot.  Good luck!


I've copied the class Crypto.vb across (opposed to using the DLL, there is only one class  - see below)
Copying across leads me to the error line:
Dim Buffer As Byte() = Convert.FromBase64String(encryptedString) causes the exception
"A first chance exception of type 'System.FormatException' occurred "

Does this help ?
Imports System
Imports System.IO
Imports System.Xml
Imports System.Text
Imports System.Security.Cryptography
Imports System.Windows.Forms
Public Class Crypto
    Private Shared DES As New TripleDESCryptoServiceProvider
    Private Shared MD5 As New MD5CryptoServiceProvider
    Public Shared Function Encrypt(ByVal stringToEncrypt As String, ByVal key As String) As String
        DES.Key = MD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))
        DES.Mode = CipherMode.ECB
        Dim DESEncrypt As ICryptoTransform = DES.CreateEncryptor()
        Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(stringToEncrypt)
        Return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length))
    End Function
    Public Shared Function Decrypt(ByVal encryptedString As String, ByVal key As String, Optional ByVal displayError As Boolean = True) As String
            DES.Key = MD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))
            DES.Mode = CipherMode.ECB
            Dim DESDecrypt As Security.Cryptography.ICryptoTransform = DES.CreateDecryptor()
            Dim Buffer As Byte() = Convert.FromBase64String(encryptedString)
            Return System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length))
        Catch ex As Exception
            If displayError Then
                MessageBox.Show("Invalid Key", "Decryption Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
            System.Diagnostics.Debug.Print("Invalid Key" & vbCrLf & ex.StackTrace)
            Return Nothing
        End Try
    End Function
    End Class

Open in new window


the error is
Return System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypt.Transf      Run-time exception thrown : System.FormatException - Invalid length for a Base-64 char array.      
...I'd have thought passing in the same string would be ok...


to be
bytData(intFileLength - 1)

fixed this

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.