Avatar of rwallacej
rwallacej
 asked on

Encryption/decryption of file

Hi

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..

Thanks
.NET ProgrammingVisual Basic.NETASP.NET

Avatar of undefined
Last Comment
rwallacej

8/22/2022 - Mon
REA_ANDREW

Does this line work?

Me.TextBox_ReadFromFile.Text = fileContents
rwallacej

ASKER
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
ASKER CERTIFIED SOLUTION
VBRocks

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
rwallacej

ASKER
Hi

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 !
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
VBRocks

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

rwallacej

ASKER
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
    'http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_21556745.html?sfQueryTermInfo=1+obscur+xml
    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
        Try
            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

rwallacej

ASKER
the error is
Convert.FromBase64String(encryptedString)
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...
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
rwallacej

ASKER
changing
bytData(intFileLength)
to be
bytData(intFileLength - 1)

fixed this