General String Encryption in .NET

Posted by cryptospin on Stack Overflow See other posts from Stack Overflow or by cryptospin
Published on 2009-05-23T01:16:33Z Indexed on 2010/03/18 3:21 UTC
Read the original article Hit count: 285

Filed under:
|

I am looking for a general string encryption class in .NET. (Not to be confused with the 'SecureString' class.)

I have started to come up with my own class, but thought there must be a .NET class that already allows you to encrypt/decrypt strings of any encoding with any Cryptographic Service Provider.

Public Class SecureString

        Private key() As Byte
        Private iv() As Byte
        Private m_SecureString As String

        Public ReadOnly Property Encrypted() As String
            Get
                Return m_SecureString
            End Get
        End Property

        Public ReadOnly Property Decrypted() As String
            Get
                Return Decrypt(m_SecureString)
            End Get
        End Property

        Public Sub New(ByVal StringToSecure As String)
            If StringToSecure Is Nothing Then StringToSecure = ""
            m_SecureString = Encrypt(StringToSecure)
        End Sub

        Private Function Encrypt(ByVal StringToEncrypt As String) As String

            Dim result As String = ""
            Dim bytes() As Byte = Text.Encoding.UTF8.GetBytes(StringToEncrypt)

            Using provider As New AesCryptoServiceProvider()

                With provider
                    .Mode = CipherMode.CBC                  
                    .GenerateKey()
                    .GenerateIV()
                    key = .Key
                    iv = .IV
                End With

                Using ms As New IO.MemoryStream
                    Using cs As New CryptoStream(ms, provider.CreateEncryptor(), CryptoStreamMode.Write)
                        cs.Write(bytes, 0, bytes.Length)
                        cs.FlushFinalBlock()
                    End Using
                    result = Convert.ToBase64String(ms.ToArray())
                End Using

            End Using

            Return result

        End Function

        Private Function Decrypt(ByVal StringToDecrypt As String) As String

            Dim result As String = ""
            Dim bytes() As Byte = Convert.FromBase64String(StringToDecrypt)

            Using provider As New AesCryptoServiceProvider()

                Using ms As New IO.MemoryStream
                    Using cs As New CryptoStream(ms, provider.CreateDecryptor(key, iv), CryptoStreamMode.Write)
                        cs.Write(bytes, 0, bytes.Length)
                        cs.FlushFinalBlock()
                    End Using
                    result = Text.Encoding.UTF8.GetString(ms.ToArray())
                End Using

            End Using

            Return result

        End Function

    End Class

© Stack Overflow or respective owner

Related posts about .NET

Related posts about cryptography