Easy object serialization to a file with compression and encryption-VBForums
Results 1 to 3 of 3

Thread: Easy object serialization to a file with compression and encryption

  1. #1

    Thread Starter
    Frenzied Member i00's Avatar
    Join Date
    Mar 2002
    Location
    1/2 way accross the galaxy.. and then some
    Posts
    1,802

    Lightbulb Easy object serialization to a file with compression and encryption

    This set of classes provide an easy way to serialize a (Serializable) object to a file with compression and encryption options!

    Also keep in mind that I wrote this a while ago ... so this may be able to be done better...

    To Implement:
    vb Code:
    1. 'To Serialize with compression:
    2. Serialize.FileSerialize("c:\test.ser", YourObject)
    3.  
    4. 'To Serialize (no compression):
    5. Serialize.FileSerialize("c:\test.ser", YourObject, False)
    6.  
    7. 'To Serialize with encryption:
    8. Serialize.FileSerialize("c:\test.ser", YourObject, False, "EncryptionKey")
    9.  
    10. 'To Serialize with compression and encryption:
    11. Serialize.FileSerialize("c:\test.ser", YourObject, True, "EncryptionKey")
    12.  
    13. 'The folloing DeSerialization functions work for compressed or uncompressed files, this is worked out automatically!
    14.  
    15. 'To DeSerialize a non encrypted file:
    16. YourObject = FileDeserialize("c:\test.ser")
    17.  
    18. 'To DeSerialize an encrypted file:
    19. YourObject = FileDeserialize("c:\test.ser", "EncryptionKey")

    Serialize Class:
    vb Code:
    1. Imports System.IO
    2. Imports System.Runtime.Serialization
    3.  
    4. Public Class Serialize
    5.  
    6. #Region "Serialization classes for save features"
    7.  
    8.     <Serializable()> _
    9.     Private Class CompressedObject
    10.         Public CompressedObject As Byte()
    11.         Public Sub New(ByVal CompressedObject As Byte())
    12.             Me.CompressedObject = CompressedObject
    13.         End Sub
    14.     End Class
    15.  
    16.     <Serializable()> _
    17.     Private Class EncryptedObject
    18.         Public EncryptedObject As Byte()
    19.         Public Sub New(ByVal EncryptedObject As Byte())
    20.             Me.EncryptedObject = EncryptedObject
    21.         End Sub
    22.     End Class
    23.  
    24. #End Region
    25.  
    26.     Private Shared Sub StreamSerialize(ByRef s As Stream, ByVal Obj As Object, Optional ByVal Compress As Boolean = True, Optional ByVal EncryptKey As String = Nothing)
    27.         Dim b As New Formatters.Binary.BinaryFormatter
    28.         If Compress = True Then
    29.             'we want to compress this object to a byte array
    30.             Obj = New CompressedObject(Compression.CompressByte(ByteArrSerialize(Obj)))
    31.         End If
    32.         If EncryptKey <> "" Then
    33.             Obj = New EncryptedObject(Encryption.EncryptByte(ByteArrSerialize(Obj), EncryptKey))
    34.         End If
    35.         b.Serialize(s, Obj)
    36.     End Sub
    37.  
    38.     Public Shared Sub FileSerialize(ByVal File As String, ByVal Obj As Object, Optional ByVal Compress As Boolean = True, Optional ByVal EncryptKey As String = Nothing)
    39.         Using s As New FileStream(File, FileMode.Create, FileAccess.ReadWrite)
    40.             StreamSerialize(s, Obj, Compress, EncryptKey)
    41.             s.Close()
    42.         End Using
    43.     End Sub
    44.  
    45.     Public Shared Function FileDeserialize(ByVal File As String, Optional ByVal DecryptKey As String = Nothing) As Object
    46.         FileDeserialize = Nothing
    47.         Dim theError As Exception = Nothing
    48.         Using s As New FileStream(File, FileMode.Open, FileAccess.Read)
    49.             FileDeserialize = StreamDeserialize(s, DecryptKey)
    50.             s.Close()
    51.         End Using
    52.     End Function
    53.  
    54.     Private Shared Function StreamDeserialize(ByVal s As Stream, Optional ByVal DecryptKey As String = Nothing) As Object
    55.         Dim b As New Formatters.Binary.BinaryFormatter
    56.         StreamDeserialize = b.Deserialize(s)
    57.  
    58. StartFileTypeCheck:
    59.         'lets see if the file was compressed or Encrypted
    60.         If TypeOf StreamDeserialize Is CompressedObject Then
    61.             'we were compressed - so lets decompress
    62.             StreamDeserialize = ByteArrDeserialize(Compression.DecompressByte(CType(StreamDeserialize, CompressedObject).CompressedObject))
    63.             GoTo StartFileTypeCheck
    64.         Else
    65.             'no compression
    66.             'return as is
    67.         End If
    68.  
    69.         If TypeOf StreamDeserialize Is EncryptedObject Then
    70.             'we were compressed - so lets decompress
    71.             StreamDeserialize = ByteArrDeserialize(Encryption.DecryptByte(CType(StreamDeserialize, EncryptedObject).EncryptedObject, DecryptKey))
    72.             GoTo StartFileTypeCheck
    73.         Else
    74.             'no compression
    75.             'return as is
    76.         End If
    77.     End Function
    78.  
    79.     Private Shared Function ByteArrSerialize(ByVal Obj As Object) As Byte()
    80.         Using MS As New MemoryStream
    81.             Dim BF As New Formatters.Binary.BinaryFormatter
    82.             BF.Serialize(MS, Obj)
    83.             ByteArrSerialize = MS.ToArray
    84.             MS.Close()
    85.         End Using
    86.     End Function
    87.  
    88.     Private Shared Function ByteArrDeserialize(ByVal SerializedData() As Byte) As Object
    89.         Using MS As New MemoryStream(SerializedData)
    90.             Dim BF As New Formatters.Binary.BinaryFormatter
    91.             ByteArrDeserialize = BF.Deserialize(MS)
    92.             MS.Close()
    93.         End Using
    94.     End Function
    95.  
    96. End Class

    Compression Class:
    vb Code:
    1. Imports System.IO
    2. Imports System.IO.Compression
    3.  
    4. Public Class Compression
    5.  
    6.     Public Shared Function CompressByte(ByVal byteSource() As Byte) As Byte()
    7.         ' Create a GZipStream object and memory stream object to store compressed stream
    8.         Dim objMemStream As New MemoryStream()
    9.         Dim objGZipStream As New GZipStream(objMemStream, CompressionMode.Compress, True)
    10.         objGZipStream.Write(byteSource, 0, byteSource.Length)
    11.         objGZipStream.Dispose()
    12.         objMemStream.Position = 0
    13.         ' Write compressed memory stream into byte array
    14.         Dim buffer(objMemStream.Length) As Byte
    15.         objMemStream.Read(buffer, 0, buffer.Length)
    16.         objMemStream.Dispose()
    17.         Return buffer
    18.     End Function
    19.  
    20.     Public Shared Function DecompressByte(ByVal byteCompressed() As Byte) As Byte()
    21.  
    22.         Try
    23.             ' Initialize memory stream with byte array.
    24.             Dim objMemStream As New MemoryStream(byteCompressed)
    25.  
    26.             ' Initialize GZipStream object with memory stream.
    27.             Dim objGZipStream As New GZipStream(objMemStream, CompressionMode.Decompress)
    28.  
    29.             ' Define a byte array to store header part from compressed stream.
    30.             Dim sizeBytes(3) As Byte
    31.  
    32.             ' Read the size of compressed stream.
    33.             objMemStream.Position = objMemStream.Length - 5
    34.             objMemStream.Read(sizeBytes, 0, 4)
    35.  
    36.             Dim iOutputSize As Integer = BitConverter.ToInt32(sizeBytes, 0)
    37.  
    38.             ' Posistion the to point at beginning of the memory stream to read
    39.             ' compressed stream for decompression.
    40.             objMemStream.Position = 0
    41.  
    42.             Dim decompressedBytes(iOutputSize - 1) As Byte
    43.  
    44.             ' Read the decompress bytes and write it into result byte array.
    45.             objGZipStream.Read(decompressedBytes, 0, iOutputSize)
    46.  
    47.             objGZipStream.Dispose()
    48.             objMemStream.Dispose()
    49.  
    50.             Return decompressedBytes
    51.  
    52.         Catch ex As Exception
    53.             Return Nothing
    54.         End Try
    55.  
    56.     End Function
    57.  
    58. End Class

    Encryption Class:
    vb Code:
    1. Imports System.Security.Cryptography
    2. Imports System.Text
    3. Imports System.IO
    4.  
    5.     Public Class Encryption
    6.  
    7.     Public Shared Function EncryptByte(ByVal Data As Byte(), ByVal Key As String) As Byte()
    8.         Key = FixKey(Key, 16, 24, 32)
    9.         Dim bytes() As Byte = ASCIIEncoding.ASCII.GetBytes(Key)
    10.         Dim ms As New MemoryStream()
    11.         Dim alg As Rijndael = Rijndael.Create()
    12.         alg.Key = bytes
    13.         alg.IV = New Byte() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
    14.         Dim cs As New CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write)
    15.         cs.Write(Data, 0, Data.Length)
    16.         cs.Close()
    17.         Dim encryptedData As Byte() = ms.ToArray()
    18.         Return encryptedData
    19.     End Function
    20.  
    21.     Private Shared Function FixKey(ByVal Key As String, ByVal ParamArray FixLength() As Integer) As String
    22.         Dim SortedLength = From xItem In FixLength Order By xItem
    23.         For Each item In SortedLength
    24.             If Len(Key) <= item Then
    25.                 If Key Is Nothing Then Key = " "
    26.                 Key = Key.PadRight(item)
    27.                 Exit For
    28.             End If
    29.         Next
    30.         If Key.Length > FixLength(UBound(FixLength)) Then
    31.             Key = Strings.Left(Key, FixLength(UBound(FixLength)))
    32.         End If
    33.         FixKey = Key
    34.     End Function
    35.  
    36.  
    37.     Public Shared Function DecryptByte(ByVal cipherData As Byte(), ByVal Key As String) As Byte()
    38.         Try
    39.             Key = FixKey(Key, 16, 24, 32)
    40.             Dim bytes() As Byte = ASCIIEncoding.ASCII.GetBytes(Key)
    41.             Dim ms As New MemoryStream()
    42.             Dim alg As Rijndael = Rijndael.Create()
    43.             alg.Key = bytes
    44.             alg.IV = New Byte() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
    45.             Dim cs As New CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write)
    46.             cs.Write(cipherData, 0, cipherData.Length)
    47.             cs.Close()
    48.             Dim decryptedData As Byte() = ms.ToArray()
    49.             Return decryptedData
    50.         Catch ex As Exception
    51.             Throw New Exception("Error decrypting - please make sure the key is correct")
    52.         End Try
    53.     End Function
    54.  
    55.  
    56.     End Class

    Hope this helps some people ...
    Also please provide feedback and say thanks if this helped you

    Kris

  2. #2
    New Member
    Join Date
    Mar 2012
    Posts
    2

    Thumbs up Re: Easy object serialization to a file with compression and encryption

    Have implemented this code for the encryption features into a home project with no alterations other than auto correcting a few implicit conversions. Saved me a bit of time and it works almost perfectly.

    FileDeserialize appears to return an empty object if the password is incorrect (rather than a null object as I would have expected), but it has worked so well that I haven't bothered to examine the code too carefully yet.

    Thank you very much.
    Last edited by BumfluffBob; Mar 29th, 2012 at 05:12 PM.

  3. #3
    New Member
    Join Date
    Mar 2012
    Posts
    2

    Re: Easy object serialization to a file with compression and encryption

    Removed Double post
    Last edited by BumfluffBob; Mar 29th, 2012 at 05:12 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.