AES Encrypt String in VB.NET

J'ai un programme basé sur Visual Basic 2010.

je veux utiliser un mot-clé personnalisé et le cryptage AES pour générer des clés d'enregistrement sur notre site web d'entreprise, qui déverrouillera le logiciel, indépendamment du fait que le logiciel est connecté ou non à l'internet.

pour ce faire, je veux crypter certaines informations utilisateur (et un code de validation) dans une chaîne cryptée AES en utilisant un utilitaire que je construirai sur mon site web. Ensuite, je veux que mon programme déchiffre la chaîne en l'information utilisateur et le code de validation, puis utiliser cette information pour valider la clé d'enregistrement.

ce qui m'amène à la question - comment chiffrer et déchiffrer une chaîne dans AES programatically? Est-il un modèle de code que je peux utiliser quelque part, ou une méthode intégrée?

16
demandé sur CodeMouse92 2011-05-13 08:19:40

3 réponses

une recherche rapide sur Google amène les fonctions suivantes: je n'ai pas testé si la sortie qu'ils produisent est correcte, cependant ils semblent compiler correctement.

Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
        Dim AES As New System.Security.Cryptography.RijndaelManaged
        Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
        Dim encrypted As String = ""
        Try
            Dim hash(31) As Byte
            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
            Array.Copy(temp, 0, hash, 0, 16)
            Array.Copy(temp, 0, hash, 15, 16)
            AES.Key = hash
            AES.Mode = Security.Cryptography.CipherMode.ECB
            Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
            Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
            encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
            Return encrypted
        Catch ex As Exception
        End Try
    End Function

Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
        Dim AES As New System.Security.Cryptography.RijndaelManaged
        Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
        Dim decrypted As String = ""
        Try
            Dim hash(31) As Byte
            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
            Array.Copy(temp, 0, hash, 0, 16)
            Array.Copy(temp, 0, hash, 15, 16)
            AES.Key = hash
            AES.Mode = Security.Cryptography.CipherMode.ECB
            Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
            Dim Buffer As Byte() = Convert.FromBase64String(input)
            decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
            Return decrypted
        Catch ex As Exception
        End Try
    End Function
4-->http://www.l33thackers.com/Thread-VB-NET-AES-Encryption

28
répondu Shane Gowland 2011-05-13 11:40:21

Edit: Merci à Artjom B. pour m'avoir avisé d'une erreur de décryptage de AES-CBC qui s'est produite à cause de ma fausse hypothèse que les chaînes IV se terminent toujours par == (en Base64) ce qui est faux. Grâce à Kanky pour avoir abordé ce sujet et merci à Misère pour offrir une solution dans ce lien. Notez que je n'ai pas vérifier son corrigé moi-même, mais j'espère que c'est correct.

voici deux solutions pour cryptage des chaînes avec AES. Le premier utilise le mode CBC avec un IV généré automatiquement et est plus sûr. L'utilisation de IV avec le mode CBC garantit que même les mêmes paires de clés en clair donnent lieu à des textes chiffrés distincts, ce qui le rend plus sûr. Le second utilise ECB plus et ne devrait pas être utilisé pour le chiffrement répétitif en clair. AES.La clé est générée en hachant la chaîne de la clé d'entrée avec SHA256; donc vous n'avez pas à vous soucier de la pseudorandomness de votre clé.

celui-ci est AES-CBC. IV est généré automatiquement par la fonction intégrée et concaténé avec le cryptogramme et retourné comme la sortie de l'algorithme de cryptage. L'algorithme de déchiffrement divise ce texte concaténé pour récupérer L'IV et le cryptogramme réel.

Private Function AESE(ByVal plaintext As String, ByVal key As String) As String
    Dim AES As New System.Security.Cryptography.RijndaelManaged
    Dim SHA256 As New System.Security.Cryptography.SHA256Cng
    Dim ciphertext As String = ""
    Try
        AES.GenerateIV()
        AES.Key = SHA256.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))

        AES.Mode = Security.Cryptography.CipherMode.CBC
        Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
        Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(plaintext)
        ciphertext = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))

       Return Convert.ToBase64String(AES.IV) & Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))

    Catch ex As Exception
        Return ex.Message
    End Try
End Function

Private Function AESD(ByVal ciphertext As String, ByVal key As String) As String
    Dim AES As New System.Security.Cryptography.RijndaelManaged
    Dim SHA256 As New System.Security.Cryptography.SHA256Cng
    Dim plaintext As String = ""
    Dim iv As String = ""
    Try
        Dim ivct = ciphertext.Split({"=="}, StringSplitOptions.None)
        iv = ivct(0) & "=="
        ciphertext = If(ivct.Length = 3, ivct(1) & "==", ivct(1))

        AES.Key = SHA256.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))
        AES.IV = Convert.FromBase64String(iv)
        AES.Mode = Security.Cryptography.CipherMode.CBC
        Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
        Dim Buffer As Byte() = Convert.FromBase64String(ciphertext)
        plaintext = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
        Return plaintext
    Catch ex As Exception
        Return ex.Message
    End Try
End Function

celui ci-dessous est en mode AES-ECB. Il n'utilise pas de perf. Les mêmes textes simples donnent toujours les mêmes textes chiffrés (sous la même clé bien sûr) et vice versa.

Private Function AESE(ByVal input As Byte(), ByVal key As String) As Byte()
    Dim AES As New System.Security.Cryptography.RijndaelManaged
    Dim SHA256 As New System.Security.Cryptography.SHA256Cng
    Dim ciphertext As String = ""
    Try
        AES.Key = SHA256.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))
        AES.Mode = Security.Cryptography.CipherMode.ECB
        Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
        Dim Buffer As Byte() = input
        Return DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)
    Catch ex As Exception
    End Try
End Function

Private Function AESD(ByVal input As Byte(), ByVal key As String) As Byte()
    Dim AES As New System.Security.Cryptography.RijndaelManaged
    Dim SHA256 As New System.Security.Cryptography.SHA256Cng
    Try
        AES.Key = SHA256.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))
        AES.Mode = Security.Cryptography.CipherMode.ECB
        Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
        Dim Buffer As Byte() = input
        Return DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)
    Catch ex As Exception
    End Try
End Function
6
répondu Merison Miryza 2017-08-23 11:56:07

vous pouvez utiliser le mode CBC pour crypter les fichiers avec une relative facilité. Utilisez uuencode/uudecode pour convertir un fichier binaire en une représentation de texte et de retour. Voir par rapport info ici: http://www.nullskull.com/a/237/uuencode-and-uudecode-in-vbnet-and-c.aspx et ici: https://social.msdn.microsoft.com/Forums/vstudio/en-US/5d4eaed8-1984-4639-aebb-bb2afddbfb8a/how-to-uuencodeuudecode-file-in-vbnet?forum=vbgeneral

0
répondu Will Pepponi 2016-12-10 23:05:38