Útmutató: Sztringek titkosítása és visszafejtése a Visual Basicben

Ez az útmutató bemutatja, hogyan használhatja a TripleDES osztályt karakterláncok titkosítására és visszafejtésére a Triple Data Encryption Standard (3DES) algoritmussal. Az első lépés egy egyszerű burkolóosztály létrehozása, amely beágyazza a 3DES algoritmust, és a titkosított adatokat base-64 kódolású sztringként tárolja. Ezt követően a burkoló használatával biztonságosan tárolhatja a magánfelhasználói adatokat egy nyilvánosan elérhető szövegfájlban.

Titkosítással védheti a felhasználói titkos kódokat (például jelszavakat), és olvashatatlanná teheti a hitelesítő adatokat jogosulatlan felhasználók számára. Ez megvédheti a jogosult felhasználó személyazonosságát az adattolvajoktól, ami védi a felhasználó eszközeit, és biztosítja a visszautasíthatatlanságot. A titkosítás védelmet nyújt a felhasználók adatainak jogosulatlan felhasználók általi elérésétől is.

További információ: Cryptographic Services.

Fontos

A Rijndael (ma Advanced Encryption Standard [AES]) és a Triple Data Encryption Standard (3DES) algoritmusok nagyobb biztonságot nyújtanak, mint a DES, mivel számítási szempontból intenzívebbek. További információ: DES és Rijndael.

A titkosítási burkoló létrehozása

  1. Hozza létre az osztályt a Simple3Des titkosítási és visszafejtési módszerek beágyazásához.

    Public NotInheritable Class Simple3Des
    End Class
    
  2. Adja hozzá a titkosítási névtér importálását az osztályt tartalmazó Simple3Des fájl elejéhez.

    Imports System.Security.Cryptography
    
  3. Simple3Des Az osztályban adjon hozzá privát mezőket a 3DES titkosítási szolgáltató, a megadott kulcs, valamint a formátumverzió, a sóméret és az iteráció számának tárolásához.

    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. Adjon hozzá egy privát metódust, amely egy bájttömböt hoz létre a megadott kulcsból és egy sóból.

    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. Adjon hozzá egy konstruktort, amely a megadott kulcsot tárolja.

    A key paraméter vezérli a EncryptData és a DecryptData metódusokat.

    Sub New(ByVal key As String)
        ' Store the key. The encryption key and IV are created per message.
        Me.Key = key
    End Sub
    
  6. Adjon hozzá egy nyilvános metódust, amely titkosít egy sztringet.

    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. Adjon hozzá egy nyilvános metódust, amely visszafejt egy sztringet.

    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
    

    A burkolóosztály mostantól használható a felhasználói eszközök védelmére. Ebben a példában a magánfelhasználói adatok biztonságos tárolására szolgál egy nyilvánosan elérhető szöveges fájlban.

A titkosítási burkoló tesztelése

  1. Egy külön osztályban adjon hozzá egy metódust, amely a burkoló metódusával EncryptData titkosít egy sztringet, és írja be a felhasználó Dokumentumok mappájába.

    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. Adjon hozzá egy metódust, amely beolvassa a titkosított sztringet a felhasználó Dokumentumok mappájából, és visszafejti a sztringet a burkoló metódusával 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. Adjon hozzá felhasználói felület kódot a TestEncoding és TestDecoding metódusok meghívásához.

  4. Indítsa el az alkalmazást.

    Az alkalmazás tesztelésekor figyelje meg, hogy nem fejti vissza az adatokat, ha helytelen jelszót ad meg.

Lásd még