Programmer's Highway

VB.NET Tips and simple code

I'm very sorry for machine translation in English.

VB.NET AES Encryption

.NET Framework provides class encryption standard because it is easy, it is possible to perform encryption and decryption easier.
The sample code performs encryption and decryption using a fixed encryption key.

Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
    ' 128bit(16byte)IV and Key
    Private Const AesIV As String = "!QAZ2WSX#EDC4RFV"
    Private Const AesKey As String = "5TGB&YHN7UJM(IK<"
    
    ''' <summary>
    ''' AES Encryption
    ''' </summary>
    Private Function Encrypt(text As StringAs String
        ' AesCryptoServiceProvider
        Dim aes As New AesCryptoServiceProvider()
        aes.BlockSize = 128
        aes.KeySize = 128
        aes.IV = Encoding.UTF8.GetBytes(AesIV)
        aes.Key = Encoding.UTF8.GetBytes(AesKey)
        aes.Mode = CipherMode.CBC
        aes.Padding = PaddingMode.PKCS7
    
        ' Convert string to byte array
        Dim src As Byte() = Encoding.Unicode.GetBytes(text)
    
        ' encryption
        Using enc As ICryptoTransform = aes.CreateEncryptor()
            Dim dest As Byte() = enc.TransformFinalBlock(src, 0, src.Length)
    
            ' Convert byte array to Base64 strings
            Return Convert.ToBase64String(dest)
        End Using
    End Function
    
    ''' <summary>
    ''' AES decryption
    ''' </summary>
    Private Function Decrypt(text As StringAs String
        ' AesCryptoServiceProvider
        Dim aes As New AesCryptoServiceProvider()
        aes.BlockSize = 128
        aes.KeySize = 128
        aes.IV = Encoding.UTF8.GetBytes(AesIV)
        aes.Key = Encoding.UTF8.GetBytes(AesKey)
        aes.Mode = CipherMode.CBC
        aes.Padding = PaddingMode.PKCS7
    
        ' Convert Base64 strings to byte array
        Dim src As Byte() = System.Convert.FromBase64String(text)
    
        ' decryption
        Using dec As ICryptoTransform = aes.CreateDecryptor()
            Dim dest As Byte() = dec.TransformFinalBlock(src, 0, src.Length)
            Return Encoding.Unicode.GetString(dest)
        End Using
    End Function

The sample has been fixed string Key and IV, with respect to IV will automatically generate program, I may be added to the beginning of the encrypted string.

Encrypted data is a byte array, has been converted to a string of Base64 format so cumbersome as it is.

Visual Studio 2010 .NET Framework 4