Procedura dettagliata: crittografia e decrittografia di stringhe in Visual Basic

Questa procedura dettagliata illustra come usare la classe DESCryptoServiceProvider per crittografare e decrittografare le stringhe usando la versione del provider del servizio di crittografia dell'algoritmo Triple Data Encryption Standard (TripleDES). Il primo passaggio consiste nel creare una classe wrapper semplice che incapsula l'algoritmo 3DES e archivia i dati crittografati come stringa con codifica Base 64. Il wrapper viene quindi usato per archiviare in modo sicuro i dati utente privati in un file di testo accessibile pubblicamente.

È possibile usare la crittografia per proteggere i segreti utente (ad esempio, le password) e rendere le credenziali illeggibili da parte di utenti non autorizzati. Questo consente di proteggere l'identità di un utente autorizzato da possibili furti e gli asset dell'utente e fornisce funzionalità di non ripudio. La crittografia può anche proteggere i dati di un utente dall'accesso da parte di utenti non autorizzati.

Per altre informazioni, vedere Servizi di crittografia.

Importante

Gli algoritmi Rijndael (ora definiti Advanced Encryption Standard [AES]) e Triple Data Encryption Standard (3DES) offrono maggiore sicurezza rispetto a DES perché richiedono un elevato utilizzo di calcolo. Per altre informazioni, vedere DES e Rijndael.

Per creare il wrapper di crittografia

  1. Creare la classe Simple3Des per incapsulare i metodi di crittografia e decrittografia.

    Public NotInheritable Class Simple3Des
    End Class
    
  2. Aggiungere un'importazione dello spazio dei nomi di crittografia all'inizio del file contenente la classe Simple3Des.

    Imports System.Security.Cryptography
    
  3. Nella classe Simple3Des aggiungere un campo privato per archiviare il provider di servizi di crittografia 3DES.

    Private TripleDes As New TripleDESCryptoServiceProvider
    
  4. Aggiungere un metodo privato che crea una matrice di byte della lunghezza specificata dall'hash della chiave specificata.

    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. Aggiungere un costruttore per inizializzare il provider di servizi di crittografia 3DES.

    Il parametro key controlla i metodi EncryptData e 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. Aggiungere un metodo pubblico che crittografa una stringa.

    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. Aggiungere un metodo pubblico che decrittografa una stringa.

    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
    

    La classe wrapper può ora essere usata per proteggere gli asset utente. In questo esempio, viene usata per archiviare in modo sicuro i dati utente privati in un file di testo accessibile pubblicamente.

Per testare il wrapper di crittografia

  1. In una classe separata aggiungere un metodo che usa il metodo EncryptData del wrapper per crittografare una stringa e scriverla nella cartella Documenti dell'utente.

    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. Aggiungere un metodo che legge la stringa crittografata dalla cartella Documenti dell'utente e decrittografa la stringa con il metodo DecryptData del wrapper.

    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. Aggiungere il codice dell'interfaccia utente per chiamare i metodi TestEncoding e TestDecoding.

  4. Eseguire l'applicazione.

    Quando si testa l'applicazione, si noti che non decrittograferà i dati se si specifica una password non corretta.

Vedi anche