Criptare e decriptare file in VB.NET

Mattepuffo's logo
Criptare e decriptare file in VB.NET

Criptare e decriptare file in VB.NET

Oggi vediamo come criptare e decriptare file usando VB.NET.

Come algoritmo useremo Aes.

La chiave di cifratura sarà, ovviamente, la stessa.

Useremo la crittografia simmetrica, e non installeremo librerie esterne.

Con la funzione crypt inseriremo del testo nel file e lo cripteremo.

Con la funzione decrypt leggeremo il file e visualizzeremo il testo in console.

Ecco il codice:

Imports System
Imports System.IO
Imports System.Security.Cryptography

Module Module1

    Sub Main(ByVal args As String())
        Dim strFile = "test.txt"
        Dim key As Byte() = {&H1, &H2, &H3, &H4, &H5, &H6, &H7, &H8, &H9, &H10, &H11, &H12, &H13, &H14, &H15, &H16}
        crypt(strFile, key)
        Console.WriteLine("---")
        decrypt(strFile, key)
    End Sub

    Private Sub crypt(ByVal file As String, ByVal key As Byte())
        Using fs As FileStream = New FileStream(file, FileMode.OpenOrCreate)
            Using aes As Aes = Aes.Create()
                aes.Key = key
                Dim iv As Byte() = aes.IV
                fs.Write(iv, 0, iv.Length)

                Using cryptStream As CryptoStream = New CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Write)

                    Using sWriter As StreamWriter = New StreamWriter(cryptStream)
                        sWriter.WriteLine("Ciao!!")
                        Console.WriteLine("File criptato")
                    End Using
                End Using
            End Using
        End Using
    End Sub

    Private Sub decrypt(ByVal file As String, ByVal key As Byte())
        Using fs As FileStream = New FileStream(file, FileMode.OpenOrCreate)
            Using aes As Aes = Aes.Create()
                Dim iv As Byte() = New Byte(aes.IV.Length - 1) {}
                fs.Read(iv, 0, iv.Length)

                Using cryptStream As CryptoStream = New CryptoStream(fs, aes.CreateDecryptor(key, iv), CryptoStreamMode.Read)

                    Using sReader As StreamReader = New StreamReader(cryptStream)
                        Console.WriteLine("Contenuto del file: {0}", sReader.ReadToEnd())
                    End Using
                End Using
            End Using
        End Using
    End Sub

End Module

Non ho impostato eccezioni su eventuali errori; ovviamente fatelo se ne avete bisogno.

Enjoy!


Condividi su Facebook

Commentami!