?
Solved

Serialize, encrypt & Deserialize, decrypt

Posted on 2006-06-27
5
Medium Priority
?
851 Views
Last Modified: 2010-05-19
vb2005

i am trying to serialize some data and then encrypt it. The encryption process goes fine i think, no errors there. Its when i decrypt that i get the errors. could somebody help me with the code?

1 form with 2 buttons and some textboxes has to serialize some of the data in the textboxes and store as a file. first button encrypts, second button decrypts.

my code for encrypting goes like this:
            Dim fs As New FileStream(sFile, FileMode.Create) ', FileAccess.Write, FileShare.Write)
            ' Construct a formatter.
            Dim Formatter As New BinaryFormatter
            ' Create the cryptographic object.
            Dim Rijndael As New RijndaelManaged()
            ' Serialize the object to file and encrypt it.
            Dim cs As New CryptoStream(fs, Rijndael.CreateEncryptor(Key, IV), CryptoStreamMode.Write)
            Formatter.Serialize(cs, fd)

my code for decrypting goes like this:
            Dim fs As New FileStream(sFile, FileMode.Create, FileAccess.Read, FileShare.Write)
            ' Construct a formatter.
            Dim Formatter As New BinaryFormatter
            ' Create the cryptographic object.
            Dim Rijndael As New RijndaelManaged()
            ' Deserialize the object to file and decrypt it.
            Dim cs As New CryptoStream(fs, Rijndael.CreateDecryptor(Key, IV), CryptoStreamMode.Read)
            fd = TryCast(Formatter.Deserialize(cs), FormData)

on the line fd = TryCast(Formatter.Deserialize(cs), FormData) i get the following error: Cryptographic exception was unhandled: Padding is invalid and cannot be removed.

any help or link greatly appreciated. thanks
0
Comment
Question by:newyuppie
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 4

Expert Comment

by:sr101880
ID: 16992265
You should cange your Filemode.Create to Filemode.open in your decrypting section.  Let me know if you have any questions.
0
 
LVL 13

Author Comment

by:newyuppie
ID: 16992460
ok did that but keep getting the padding error still.
any ideas?
0
 
LVL 4

Accepted Solution

by:
sr101880 earned 2000 total points
ID: 16992635
Here is a good sample I found on the net that has everything you need.

Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module RijndaelSample

    Sub Main()
        Try
            ' Create a new Rijndael object to generate a key
            ' and initialization vector (IV).
            Dim RijndaelAlg As Rijndael = Rijndael.Create

            ' Create a string to encrypt.
            Dim sData As String = "Here is some data to encrypt."
            Dim FileName As String = "CText.txt"

            ' Encrypt text to a file using the file name, key, and IV.
            EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV)

            ' Decrypt the text from a file using the file name, key, and IV.
            Dim Final As String = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.IV)

            ' Display the decrypted string to the console.
            Console.WriteLine(Final)
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try

        Console.ReadLine()

    End Sub


    Sub EncryptTextToFile(ByVal Data As String, ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte)
        Try
            ' Create or open the specified file.
            Dim fStream As FileStream = File.Open(FileName, 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.CreateEncryptor(Key, IV), _
                                           CryptoStreamMode.Write)

            ' Create a StreamWriter using the CryptoStream.
            Dim sWriter As New StreamWriter(cStream)

            Try

                ' Write the data to the stream
                ' to encrypt it.
                sWriter.WriteLine(Data)
            Catch e As Exception

                Console.WriteLine("An error occurred: {0}", e.Message)

            Finally

                ' Close the streams and
                ' close the file.
                sWriter.Close()
                cStream.Close()
                fStream.Close()

            End Try
        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
        Catch e As UnauthorizedAccessException
            Console.WriteLine("A file error occurred: {0}", e.Message)
        End Try
    End Sub


    Function DecryptTextFromFile(ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte) As String
        Try
            ' Create or open the specified file.
            Dim fStream As FileStream = File.Open(FileName, 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), _
                                            CryptoStreamMode.Read)

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

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

            Try

                val = sReader.ReadLine()

            Catch e As Exception
                Console.WriteLine("An Cerror occurred: {0}", e.Message)
            Finally
                ' Close the streams and
                ' close the file.
                sReader.Close()
                cStream.Close()
                fStream.Close()


            End Try

            ' Return the string.
            Return val

        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Return Nothing
        Catch e As UnauthorizedAccessException
            Console.WriteLine("A file error occurred: {0}", e.Message)
            Return Nothing
        End Try
    End Function
End Module
0
 
LVL 13

Author Comment

by:newyuppie
ID: 16992847
i figured it out, oddly enough just 1 line of code was sufficient to eliminate the padding error:

i added

cs.FlushFinalBlock

after encrypting. seems that gets rid of some remaining block of text which was causing the problems.

anyway i have decided to give the points to sr101880 because the code he provided served me to double check my code and because apparently its the only code i have seen that is not C# and that it has everything that i need. if you have the time please tell me how you googled for that!

thank you very much for this helpful code and probably will serve to others who search for this too.
0
 
LVL 4

Expert Comment

by:sr101880
ID: 16992986
Good work!  I went to google typed in cryptostream and it was the first hit that came up on the screen.  The example is half way down the page.  :-)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question