Sdílet prostřednictvím


Návod: Šifrování a dešifrování řetězců v jazyce Visual Basic

V tomto názorném postupu se dozvíte, jak pomocí DESCryptoServiceProvider třídy šifrovat a dešifrovat řetězce pomocí verze poskytovatele kryptografických služeb (CSP) algoritmu Standard (TripleDESTriple Data Encryption Standard). Prvním krokem je vytvoření jednoduché třídy obálky, která zapouzdřuje algoritmus 3DES a ukládá šifrovaná data jako řetězec kódovaný v base-64. Tento obálka se pak použije k bezpečnému ukládání soukromých uživatelských dat do veřejně přístupného textového souboru.

Šifrování můžete použít k ochraně tajných kódů uživatelů (například hesel) a k tomu, aby byly přihlašovací údaje nečitelné neoprávněnými uživateli. To může chránit identitu autorizovaného uživatele před odcizením, která chrání prostředky uživatele a poskytuje neodvrácení. Šifrování může také chránit data uživatele před přístupem neoprávněných uživatelů.

Další informace naleznete v tématu Kryptografické služby.

Důležité

Algoritmy Rijndael (nyní označované jako Advanced Encryption Standard [AES]) a Triple Data Encryption Standard (3DES) poskytují větší zabezpečení než DES, protože jsou výpočetně náročné. Další informace najdete v tématech DES a Rijndael.

Vytvoření obálky šifrování

  1. Simple3Des Vytvořte třídu pro zapouzdření metod šifrování a dešifrování.

    Public NotInheritable Class Simple3Des
    End Class
    
  2. Na začátek souboru, který obsahuje Simple3Des třídu, přidejte import kryptografického oboru názvů.

    Imports System.Security.Cryptography
    
  3. Simple3Des Do třídy přidejte soukromé pole pro uložení zprostředkovatele kryptografických služeb 3DES.

    Private TripleDes As New TripleDESCryptoServiceProvider
    
  4. Přidejte privátní metodu, která vytvoří bajtové pole zadané délky z hodnoty hash zadaného klíče.

    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. Přidejte konstruktor pro inicializaci zprostředkovatele kryptografických služeb 3DES.

    Parametr key řídí metody EncryptData a DecryptData metody.

    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. Přidejte veřejnou metodu, která šifruje řetězec.

    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. Přidejte veřejnou metodu, která dešifruje řetězec.

    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
    

    Třída obálky se teď dá použít k ochraně uživatelských prostředků. V tomto příkladu se používá k bezpečnému ukládání soukromých dat uživatelů do veřejně přístupného textového souboru.

Otestování obálky šifrování

  1. Do samostatné třídy přidejte metodu, která používá metodu obálky EncryptData k zašifrování řetězce a zápisu do složky Dokumenty uživatele.

    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. Přidejte metodu, která čte šifrovaný řetězec ze složky Dokumenty uživatele a dešifruje řetězec metodou obálky 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. Přidejte kód uživatelského rozhraní pro volání TestEncoding metod a TestDecoding metod.

  4. Aplikaci spusťte.

    Když aplikaci otestujete, všimněte si, že pokud zadáte nesprávné heslo, data nešifruje.

Viz také