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

這個逐步解說會顯示如何使用 DESCryptoServiceProvider 類別,利用三重資料加密標準 (TripleDES) 演算法的密碼編譯服務提供者 (CSP) 版本,進行字串的加密和解密。 第一步是建立簡單的包裝函式類別 (Wrapper Class),封裝 3DES 演算法,並以 Base-64 編碼字串儲存加密的資料。 接著使用該包裝函式,在可公開存取的文字檔中安全地儲存私密的使用者資料。

您可以使用加密保護使用者的機密資訊 (例如密碼),使未經授權的使用者無法讀取認證。 這樣可保護授權使用者的識別 (Identity) 不致遭人盜用,進而保護使用者的資產並提供不可否認性。 加密也可以保護使用者的資料,避免遭到未經授權的使用者加以存取。

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

安全性注意事項安全性注意事項

Rijndael (現為進階加密標準 [AES]) 和三重資料加密標準 (3DES) 演算法使用了更精密的計算方法,所以可提供比 DES 更佳的安全性。 如需詳細資訊,請參閱 DESRijndael

若要建立加密包裝函式

  1. 在檔案開頭加入加密命名空間的匯入。

    Imports System.Security.Cryptography
    
  2. 建立類別,以封裝加密和解密的方法。

    Public NotInheritable Class Simple3Des
    End Class
    
  3. 加入私用 (Private) 欄位,儲存 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. 加入建構函式 (Constructor),初始化 3DES 密碼編譯服務提供者。

    key 參數會控制 EncryptData 和 DecryptData 方法。

    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) 方法。

    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. 加入使用者介面程式碼,呼叫 TestEncoding 和 TestDecoding 方法。

  4. 執行應用程式。

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

請參閱

參考

System.Security.Cryptography

DESCryptoServiceProvider

DES

TripleDES

Rijndael

概念

密碼編譯服務