逐步解說:在 Visual Basic 中為字串加密和解密

本逐步解說會示範如何使用 DESCryptoServiceProvider 類別,透過三重資料加密標準 (TripleDES) 演算法的密碼編譯服務提供者 (CSP) 版本來加密和解密字串。 第一個步驟是建立簡單的包裝函式類別來封裝 3DES 演算法,並將加密的資料儲存為 base-64 編碼的字串。 然後,該包裝函式會用於將私人使用者資料安全地儲存在可公開存取的文字檔中。

您可以使用加密來保護使用者機密 (例如密碼),並讓未經授權的使用者無法讀取認證。 這麼做可保護授權使用者的身分識別免於遭竊,進而保護使用者的資產,並提供不可否認性。 加密也可以保護使用者的資料不受未經授權的使用者存取。

如需詳細資訊,請參閱密碼編譯服務

重要

Rijndael (現在稱為進階加密標準 (AES)) 和三重資料加密標準 (3DES) 演算法提供的安全性比 DES 更高,因為它們的計算強度更大。 如需詳細資訊,請參閱 DESRijndael

若要建立加密包裝函式

  1. 請建立 Simple3Des 類別來封裝加密和解密方法。

    Public NotInheritable Class Simple3Des
    End Class
    
  2. 將加密命名空間的匯入項目新增到包含 Simple3Des 類別的檔案開頭。

    Imports System.Security.Cryptography
    
  3. Simple3Des 類別中新增私人欄位,以便儲存 3DES 密碼編譯服務提供者。

    Private TripleDes As New TripleDESCryptoServiceProvider
    
  4. 新增私人方法,從指定索引鍵的雜湊建立指定長度的位元組陣列。

    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
    
  5. 新增建構函式以初始化 3DES 密碼編譯服務提供者。

    參數 key 會控制 EncryptDataDecryptData 方法。

    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
    
  6. 新增加密字串的公開方法。

    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
    
  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)
    
        ' 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
    

    包裝函式類別至此已可用來保護使用者資產。 在此範例中,它會用來將私人使用者資料安全地儲存在可公開存取的文字檔中。

若要測試加密包裝函式

  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. 新增使用者介面程式碼以呼叫 TestEncodingTestDecoding 方法。

  4. 執行應用程式。

    測試應用程式時,請注意,如果您提供錯誤的密碼,它就不會解密資料。

另請參閱