Click here to Skip to main content
       

Visual Basic

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionRijndael encryption not workingmembermaskrtnik0114 Nov '12 - 2:20 
Hi,
 
I am working on program to be used to process confidential data. That data must be well-encrypted. I have built method, that exports data from memory to XML, encrypts XMl document and saves it to file. But, what seems strange to me is, that encryption method doesn’t work. After its execution, file, which may contain encrypted data is created, but remains empty. I don’ t see any bug in the code. Could you help me to get it working, please?
 
Here is code used to encrypt and save XML.
Public Sub Save(ByVal carrier As DataCarrier, ByVal password As String, ByVal filename As String)
            Try
                Using sha As New SHA512Managed
                    Dim salt As Byte() = sha.ComputeHash(Encoding.Default.GetBytes(password))
                    Using pdb As New Rfc2898DeriveBytes(password, salt), aes As New RijndaelManaged, filestr As New FileStream(filename, FileMode.Create, FileAccess.Write)
                        Using cryptostr As New CryptoStream(filestr, aes.CreateEncryptor(pdb.GetBytes(32), pdb.GetBytes(16)), CryptoStreamMode.Write)
                            ExportData(carrier).Save(cryptostr)
                        End Using
                    End Using
                End Using
            Catch ex As Exception
                Logging.Instance.WriteException(ex, TraceEventType.Error)
                MessageBox.Show(String.Format(My.Resources.UnhandledExceptionExString, ex.Message, ex.ToString), My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub
 
Also, is that encryption algorithm OK, or there is some way to break it? I must be sure that there is no way to break encryption, that is used.
Stanislav Husár

AnswerRe: Rijndael encryption not workingmentorKeith Barrow14 Nov '12 - 2:52 
Have you tried putting a breakpoint to see if an Exception is thrown?
 
After a brief glance, the code itself looks fine AFAICT, though the problem could be in the ExportData method, is there a reason you aren't calling the cryptostream's Write directly?
 
My knowledge about this is four years out of date, but Rijndael was considered secure. I vaguely recall reading they'd found a way to crack it in theory, but applying the crack it in practise hasn't happened yet and isn't likely to be feasible soon.

GeneralRe: Rijndael encryption not workingmembermaskrtnik0114 Nov '12 - 3:08 
It does not throw any exception.
 
ExportData method only creates XML document with data to be encrypted. I have checked, that result of ExportData contains, what it should cotain.
 
I have also tried following, again, empty file is generated.
Public Sub Save(ByVal carrier As DataCarrier, ByVal password As String, ByVal filename As String)
            Try
                Using sha As New SHA512Managed
                    Dim salt As Byte() = sha.ComputeHash(Encoding.Default.GetBytes(password))
                    Using pdb As New Rfc2898DeriveBytes(password, salt), aes As New RijndaelManaged, filestr As New FileStream(filename, FileMode.Create, FileAccess.Write)
                        Using cryptostr As New CryptoStream(filestr, aes.CreateEncryptor(pdb.GetBytes(32), pdb.GetBytes(16)), CryptoStreamMode.Write)
                            Dim str = ExportData(carrier).ToString()
                            Using w As New StreamWriter(cryptostr)
                                w.Write(str)
                            End Using
                        End Using
                    End Using
                End Using
            Catch ex As Exception
                Logging.Instance.WriteException(ex, TraceEventType.Error)
                MessageBox.Show(String.Format(My.Resources.UnhandledExceptionExString, ex.Message, ex.ToString), My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub
 
Moreover, I have tried simply writing string literal to CryptoStream, this approach generates empty file too.
 
Strange is, that when I run this version:
 Public Sub Save(ByVal carrier As DataCarrier, ByVal password As String, ByVal filename As String)
            Try
                Using sha As New SHA512Managed
                    Dim salt As Byte() = sha.ComputeHash(Encoding.Default.GetBytes(password))
                    Using pdb As New Rfc2898DeriveBytes(password, salt), aes As New RijndaelManaged, filestr As New MemoryStream() 'filestr As New FileStream(filename, FileMode.Create, FileAccess.Write)
                        Using cryptostr As New CryptoStream(filestr, aes.CreateEncryptor(pdb.GetBytes(32), pdb.GetBytes(16)), CryptoStreamMode.Write)
                            ExportData(carrier).Save(cryptostr)
                            Dim str = New String(Encoding.Default.GetChars(filestr.ToArray()))
                            Debugger.Break()
                        End Using
                    End Using
                End Using
            Catch ex As Exception
                Logging.Instance.WriteException(ex, TraceEventType.Error)
                MessageBox.Show(String.Format(My.Resources.UnhandledExceptionExString, ex.Message, ex.ToString), My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub
Then at Debugger.Break statement str variable cotains data, which should be in the file.
 
While this and simmilar solutions generate empty file.
Public Sub Save(ByVal carrier As DataCarrier, ByVal password As String, ByVal filename As String)
            Try
                Using sha As New SHA512Managed
                    Dim salt As Byte() = sha.ComputeHash(Encoding.Default.GetBytes(password))
                    Using pdb As New Rfc2898DeriveBytes(password, salt), aes As New RijndaelManaged, filestr As New MemoryStream() 'filestr As New FileStream(filename, FileMode.Create, FileAccess.Write)
                        Using cryptostr As New CryptoStream(filestr, aes.CreateEncryptor(pdb.GetBytes(32), pdb.GetBytes(16)), CryptoStreamMode.Write)
                            ExportData(carrier).Save(cryptostr)
                            File.WriteAllBytes(filename, filestr.ToArray())
                            Debugger.Break()
                        End Using
                    End Using
                End Using
            Catch ex As Exception
                Logging.Instance.WriteException(ex, TraceEventType.Error)
                MessageBox.Show(String.Format(My.Resources.UnhandledExceptionExString, ex.Message, ex.ToString), My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub
 
I am really confused on what it does.
GeneralRe: Rijndael encryption not workingmentorKeith Barrow14 Nov '12 - 3:26 
I'm not surprised at your confusion. The only thing I can suggest is to simplify as far as possible and re-factor back to what you want.
  1. Comment out the export line and perform the crypto-stream write directly.
  2. Create two byte arrays for the key and IV and make sure pdb is creating a sensible key & IV, I would have thought that the if these were incorrect the encryption algorithm would throw. I've not used the derived bytes thing, so it is new to me
  3. If the above isn't working, hard-code the key and IV byte arrays
 
If all else fails, you could go back to square one, and write a console app that uses hard-coded byte arrays.

GeneralRe: Rijndael encryption not workingmentorKeith Barrow14 Nov '12 - 3:35 
I think I may have figured it out!
 

The cryptostream writes to a filestream. The XML can't write to the same stream, and if you use a different stream you'll either overwrite (this is probably your situation) or it'll append the XML after the encrypted information. The other option is the XML is written first, then appended or overwitten with the encrypted information, neith seems to apply in your case.
 
In your position I'd replace the file stream with a memory stream for the cryptography stuff. I'd perform the write immediately, reset the position to 0 and pass the memory stream into the Export method. Then all the XML writer has to do is to read the Memory stream into the file stream when you've reached the correct point in the file (or set a property to its contents).
 
The other problem you might face is that you need to encode the encrypted bytes (e.g. into Hex characters), otherwise you'll get non-printing characters in the XML document, fouling it up.

GeneralRe: Rijndael encryption not workingmembermaskrtnik0114 Nov '12 - 3:48 
Hmm, now it works, even with using the same code as the one that didn´t work.I di d nothing more, than copying binaries from bin/Debug/ and running them on another computer. I can´t understand this behaviour.
GeneralRe: Rijndael encryption not workingmentorKeith Barrow14 Nov '12 - 4:05 
I think that is properly called a heisenbug[^].
 
That is odd behaviour. Something to do with a 64/32 bit compilation on a 32/64 bit machine Unsure | :~ (I mean really unsure)! The only other things that spring to mind immediately is the framework version or that restarting your machine might be a good idea, in case VS has screwed up. Hope you get it stable.

QuestionRe: Rijndael encryption not working [modified]membermaskrtnik0115 Nov '12 - 19:40 
Maybe it is stable now. But there is new problem. I have tried decrypting encrypted file, but it fails to decrypt, decrypted data absolutely do not match data which was encrypted. I am using this code:
	Public Sub Save(ByVal carrier As DataCarrier, ByVal password As String, ByVal filename As String)
            Try
                Using sha As New SHA512Managed
                    Dim hash = sha.ComputeHash(Encoding.Default.GetBytes(password))
                    Dim key As Byte() = New Byte(31) {}
                    Dim iv As Byte() = New Byte(15) {}
                    Array.Copy(hash, 0, key, 0, 32)
                    Array.Copy(hash, 32, iv, 0, 16)
                    Using aes As New RijndaelManaged, filestr As New FileStream(filename, FileMode.Create, FileAccess.Write)
                        Using cryptostr As New CryptoStream(filestr, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write)
                            ExportData(carrier).Save(cryptostr)
                        End Using
                    End Using
                End Using
            Catch ex As Exception
                Logging.Instance.WriteException(ex, TraceEventType.Error)
                MessageBox.Show(String.Format(My.Resources.UnhandledExceptionExString, ex.Message, ex.ToString), My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub
        Public Function Load(ByVal password As String, ByVal filename As String) As XDocument
            Dim sha As SHA512Managed
            Dim aes As RijndaelManaged
            Dim trans As ICryptoTransform
            Dim cryptostr As CryptoStream
            Dim filestr As FileStream
            Try
                sha = New SHA512Managed()
                Dim hash = sha.ComputeHash(Encoding.Default.GetBytes(password))
                aes = New RijndaelManaged()
                Dim key As Byte() = New Byte(31) {}
                Dim iv As Byte() = New Byte(15) {}
                Array.Copy(hash, 0, key, 0, 32)
                Array.Copy(hash, 32, iv, 0, 16)
                trans = aes.CreateEncryptor(key, iv)
                filestr = New FileStream(filename, FileMode.Open)
                cryptostr = New CryptoStream(filestr, trans, CryptoStreamMode.Read)
                Return XDocument.Load(cryptostr)
            Catch ex As Exception
                Logging.Instance.WriteException(ex, TraceEventType.Error)
                MessageBox.Show(String.Format(My.Resources.UnhandledExceptionExString, ex.Message, ex.ToString), My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Finally
                If cryptostr IsNot Nothing Then cryptostr.Dispose()
                If filestr IsNot Nothing Then filestr.Dispose()
                If trans IsNot Nothing Then trans.Dispose()
                If aes IsNot Nothing Then aes.Dispose()
                If sha IsNot Nothing Then sha.Dispose()
            End Try
        End Function


modified 17 Nov '12 - 11:23.

GeneralRe: Rijndael encryption not workingmemberDisIsHoody14 Nov '12 - 9:34 
Can you post the code for the Export.Save method so we can see how you are using the cryptostream?
GeneralRe: Rijndael encryption not workingmembermaskrtnik0114 Nov '12 - 18:21 
Do you mean ExportData(carrier).Save(cryptostr) ? That is System.Xml.Linq.Save method.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   


Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 21 May 2013
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid