演练:在 Visual Basic 中加密和解密字符串

本演练演示如何使用 TripleDES 类通过三重数据加密标准(3DES)算法加密和解密字符串。 第一步是创建一个简单的包装类,该类封装 3DES 算法并将加密数据存储为 base-64 编码字符串。 然后,该包装器用于安全地将专用用户数据存储在可公开访问的文本文件中。

可以使用加密来保护用户机密(例如密码),并使未经授权的用户无法读取凭据。 这可以防止授权用户的标识被盗,从而保护用户的资产并提供不可否认性。 加密还可以保护用户的数据不被未经授权的用户访问。

有关更多信息,请参阅加密服务。

重要

Rijndael(现在称为高级加密标准 [AES])和三重数据加密标准 (3DES) 算法提供比 DES 更高的安全性,因为它们在计算上更密集。 有关详细信息,请参阅 DES 和 Rijndael。

创建加密包装器

  1. Simple3Des创建类以封装加密和解密方法。

    Public NotInheritable Class Simple3Des
    End Class
    
  2. 将加密命名空间的导入添加到包含 Simple3Des 该类的文件的开头。

    Imports System.Security.Cryptography
    
  3. 在 Simple3Des 类中,添加私有字段以存储 3DES 加密服务提供程序、指定的密钥,以及格式版本、盐大小和迭代次数。

    Private TripleDes As TripleDES = TripleDES.Create()
    
    Private Const FormatVersion As Byte = 1
    Private Const SaltSize As Integer = 16
    Private Const Iterations As Integer = 600000
    Private ReadOnly Key As String
    
  4. 添加一个使用指定的键和盐创建字节数组的私有方法。

    Private Function DeriveKey(ByVal salt() As Byte) As Byte()
        ' Derive a key from the specified key and the salt.
        Using kdf As New Rfc2898DeriveBytes(
            Key, salt, Iterations, HashAlgorithmName.SHA256)
    
            Return kdf.GetBytes(TripleDes.KeySize \ 8)
        End Using
    End Function
    
  5. 添加存储指定键的构造函数。

    参数 key 控制 EncryptData 方法和 DecryptData 方法。

    Sub New(ByVal key As String)
        ' Store the key. The encryption key and IV are created per message.
        Me.Key = key
    End Sub
    
  6. 添加加密字符串的公共方法。

    Public Function EncryptData( 
        ByVal plaintext As String) As String
    
        ' Create a new salt and initialization vector for this message.
        Dim salt(SaltSize - 1) As Byte
        Using rng As RandomNumberGenerator = RandomNumberGenerator.Create()
            rng.GetBytes(salt)
        End Using
    
        TripleDes.Key = DeriveKey(salt)
        TripleDes.GenerateIV()
    
        ' 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
        ' Write the format version, salt, and initialization vector in front of
        ' the cipher text. The version identifies the salt length and iteration count.
        ms.WriteByte(FormatVersion)
        ms.Write(salt, 0, salt.Length)
        ms.Write(TripleDes.IV, 0, TripleDes.IV.Length)
    
        ' 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
    
  7. 添加解密字符串的公共方法。

    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)
    
        ' Read the header that precedes the cipher text. Only one format
        ' version exists, so reject anything else.
        Dim ivSize As Integer = TripleDes.BlockSize \ 8
        Dim headerSize As Integer = 1 + SaltSize + ivSize
        If encryptedBytes.Length < headerSize OrElse
            encryptedBytes(0) <> FormatVersion Then
    
            Throw New CryptographicException(
                "The encrypted data is not in the expected format.")
        End If
    
        Dim salt(SaltSize - 1) As Byte
        Dim iv(ivSize - 1) As Byte
        Array.Copy(encryptedBytes, 1, salt, 0, SaltSize)
        Array.Copy(encryptedBytes, 1 + SaltSize, iv, 0, ivSize)
    
        TripleDes.Key = DeriveKey(salt)
        TripleDes.IV = iv
    
        ' 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, headerSize, 
            encryptedBytes.Length - headerSize)
        decStream.FlushFinalBlock()
    
        ' Convert the plaintext stream to a string.
        Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
    End Function
    

    包装类现在可用于保护用户资产。 在此示例中,它用于安全地将专用用户数据存储在可公开访问的文本文件中。

测试加密包装器

  1. 在单独的类中,添加一个方法,该方法使用包装器 EncryptData 的方法加密字符串并将其写入用户的“我的文档”文件夹。

    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
    
  2. 添加从用户的“我的文档”文件夹中读取加密字符串的方法,并使用包装器 DecryptData 的方法解密该字符串。

    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
    
  3. 添加用户界面代码以调用 TestEncoding 和 TestDecoding 方法。

  4. 运行该应用程序。

    测试应用程序时,请注意,如果提供错误的密码,则不会解密数据。

另请参阅