Sunday, July 31, 2011

Encrypt & Serialize an object

Serialization can be defined as the process of storing the state of an object instance to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, is converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

But many of the time we need to encrypt the object before saving it in the file, database, etc to protect from misuse. So we have first serialize the object into bytes and then we can encrypt the bytes using Cryptography.

Below is the code snippet to encrypt/decrypt the object in VB.net. Key in the code snippet is like a password which should be same during encryption and decryption.

Encrypt Code

Public Function Encrypt(Of T)(ByVal value As T, ByVal key As String) As Byte()

        Using strm As New MemoryStream
            Dim crypt As New TripleDESCryptoServiceProvider
            Dim slt() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
            Dim pdb As New Rfc2898DeriveBytes(key, slt)
            Dim bytDerivedKey() As Byte = pdb.GetBytes(24)
            crypt.Key = bytDerivedKey
            crypt.IV = pdb.GetBytes(8)

            Using cstream As New CryptoStream(strm, crypt.CreateEncryptor, CryptoStreamMode.Write)
                Dim bFormatter As New BinaryFormatter
                bFormatter.Serialize(cstream, value)
                cstream.Close()
                strm.Close()
            End Using

            Return strm.ToArray
        End Using
    End Function

Decrypt Code

Public Function Decrypt(Of T)(ByVal bytes() As Byte, ByVal key As String) As T
        Dim value As T

        Using strm As New MemoryStream(bytes)
            Dim crypt As New TripleDESCryptoServiceProvider
            Dim slt() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
            Dim pdb As New Rfc2898DeriveBytes(key, slt)
            Dim bytDerivedKey() As Byte = pdb.GetBytes(24)
            crypt.Key = bytDerivedKey
            crypt.IV = pdb.GetBytes(8)

            Using cstream As New CryptoStream(strm, crypt.CreateDecryptor, CryptoStreamMode.Read)
                Dim bFormatter As New BinaryFormatter
                value = bFormatter.Deserialize(cstream)
                cstream.Close()
                strm.Close()
            End Using
        End Using
        Return value
    End Function

Example to use above functions

<Serializable()>
    Public ClassCustomer
      
Public PropertyCustomerID As Integer
        Public Property
CustomerName As String
    End Class

    Private Sub
SaveCustomer()
        Dim d As New Customer
       
d.CustomerID = 1
d.CustomerName = "GAURAV"
       
Dim bytes() As Byte = Encrypt(Of Customer)(d, "54321")
        My.Computer.FileSystem.WriteAllBytes("E:\Test.dat", bytes, False)
    End Sub

    Private Sub
LoadCustomer()
        Dim bytes() As Byte = My.Computer.FileSystem.ReadAllBytes("E:\Test.dat")
        Dim objCustomer As Customer = Decrypt(Of Customer)(bytes, "54321")
    End Sub