Walkthrough: Encrypting and Decrypting Strings in Visual Basic
This walkthrough shows you how to use the DESCryptoServiceProvider class to encrypt and decrypt strings using the cryptographic service provider (CSP) version of the Triple Data Encryption Standard (TripleDES) algorithm. The first step is to create a simple wrapper class that encapsulates the 3DES algorithm and stores the encrypted data as a base-64 encoded string. Then, that wrapper is used to securely store private user data in a publicly accessible text file.
You can use encryption to protect user secrets (for example, passwords) and to make credentials unreadable by unauthorized users. This can protect an authorized user's identity from being stolen, which protects the user's assets and provides non-repudiation. Encryption can also protect a user's data from being accessed by unauthorized users.
For more information, see Cryptographic Services.
Important
The Rijndael (now referred to as Advanced Encryption Standard [AES]) and Triple Data Encryption Standard (3DES) algorithms provide greater security than DES because they are more computationally intensive. For more information, see DES and Rijndael.
To create the encryption wrapper
Create the
Simple3Des
class to encapsulate the encryption and decryption methods.Public NotInheritable Class Simple3Des End Class
Add an import of the cryptography namespace to the start of the file that contains the
Simple3Des
class.Imports System.Security.Cryptography
In the
Simple3Des
class, add a private field to store the 3DES cryptographic service provider.Private TripleDes As New TripleDESCryptoServiceProvider
Add a private method that creates a byte array of a specified length from the hash of the specified key.
Private Function TruncateHash( ByVal key As String, ByVal length As Integer) As Byte() Dim sha1 As New SHA1CryptoServiceProvider ' Hash the key. Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key) Dim hash() As Byte = sha1.ComputeHash(keyBytes) ' Truncate or pad the hash. ReDim Preserve hash(length - 1) Return hash End Function
Add a constructor to initialize the 3DES cryptographic service provider.
The
key
parameter controls theEncryptData
andDecryptData
methods.Sub New(ByVal key As String) ' Initialize the crypto provider. TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8) TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8) End Sub
Add a public method that encrypts a string.
Public Function EncryptData( ByVal plaintext As String) As String ' Convert the plaintext string to a byte array. Dim plaintextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the encoder to write to the stream. Dim encStream As New CryptoStream(ms, TripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. encStream.Write(plaintextBytes, 0, plaintextBytes.Length) encStream.FlushFinalBlock() ' Convert the encrypted stream to a printable string. Return Convert.ToBase64String(ms.ToArray) End Function
Add a public method that decrypts a string.
Public Function DecryptData( ByVal encryptedtext As String) As String ' Convert the encrypted text string to a byte array. Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the decoder to write to the stream. Dim decStream As New CryptoStream(ms, TripleDes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. decStream.Write(encryptedBytes, 0, encryptedBytes.Length) decStream.FlushFinalBlock() ' Convert the plaintext stream to a string. Return System.Text.Encoding.Unicode.GetString(ms.ToArray) End Function
The wrapper class can now be used to protect user assets. In this example, it is used to securely store private user data in a publicly accessible text file.
To test the encryption wrapper
In a separate class, add a method that uses the wrapper's
EncryptData
method to encrypt a string and write it to the user's My Documents folder.Sub TestEncoding() Dim plainText As String = InputBox("Enter the plain text:") Dim password As String = InputBox("Enter the password:") Dim wrapper As New Simple3Des(password) Dim cipherText As String = wrapper.EncryptData(plainText) MsgBox("The cipher text is: " & cipherText) My.Computer.FileSystem.WriteAllText( My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\cipherText.txt", cipherText, False) End Sub
Add a method that reads the encrypted string from the user's My Documents folder and decrypts the string with the wrapper's
DecryptData
method.Sub TestDecoding() Dim cipherText As String = My.Computer.FileSystem.ReadAllText( My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\cipherText.txt") Dim password As String = InputBox("Enter the password:") Dim wrapper As New Simple3Des(password) ' DecryptData throws if the wrong password is used. Try Dim plainText As String = wrapper.DecryptData(cipherText) MsgBox("The plain text is: " & plainText) Catch ex As System.Security.Cryptography.CryptographicException MsgBox("The data could not be decrypted with the password.") End Try End Sub
Add user interface code to call the
TestEncoding
andTestDecoding
methods.Run the application.
When you test the application, notice that it will not decrypt the data if you provide the wrong password.