String encryptor and decryptor

StewartBW 1,145 Reputation points
2024-03-27T20:43:46.3666667+00:00

Hey

I need a simple safe method to save passwords on the local user registry and found this:

https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aescryptoserviceprovider?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aescryptoserviceprovider.createdecryptor?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aescryptoserviceprovider.createencryptor?view=netframework-4.8

They key/iv should be constant which is hardcoded in the app, by the way, modified the above samples and have 2 questions:

  1. Am I using it correctly?
  2. Inside the Encrypt/Decrypt functions, may I replace Dim encryptor As ICryptoTransform with Using encryptor As ICryptoTransform ? Thank you
    Private Function _HexStringToByteArray(ByVal Value As String) As Byte()
        Dim Ret(Convert.ToInt32((Value.Length / 2) - 1)) As Byte
        Try
            For MyLoop As Integer = 0 To Ret.Length - 1
                Ret(MyLoop) = Byte.Parse(Value.Substring(MyLoop * 2, 2), NumberStyles.HexNumber)
            Next
        Catch Exception As Exception
            Exit Try
        End Try
        Return Ret
    End Function
    Private Function _ByteArrayToHexString(ByVal Value() As Byte) As String
        Dim Ret As New StringBuilder
        Try
            For Each MyByte As Byte In Value
                Ret.Append(MyByte.ToString("x2"))
            Next
        Catch Exception As Exception
            Exit Try
        End Try
        Return Ret.ToString
    End Function
    Friend Function EncryptStringToBytes_Aes(ByVal plainText As String) As Byte()
        If plainText Is Nothing OrElse plainText.Length <= 0 Then
            Throw New ArgumentNullException("plainText")
        End If
        ' Create an AesCryptoServiceProvider object
        ' with the specified key and IV.
        Using aesAlg As New AesCryptoServiceProvider()
            aesAlg.Key = _HexStringToByteArray("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
            aesAlg.IV = _HexStringToByteArray("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
            ' Create an encryptor to perform the stream transform.
            Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
            ' Create the streams used for encryption.
            Dim msEncrypt As New MemoryStream()
            Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
                Using swEncrypt As New StreamWriter(csEncrypt)
                    'Write all data to the stream.
                    swEncrypt.Write(plainText)
                End Using
                ' Return the encrypted bytes from the memory stream.
                Return msEncrypt.ToArray()
            End Using
        End Using
    End Function 'EncryptStringToBytes_Aes
    Friend Function DecryptStringFromBytes_Aes(ByVal cipherText() As Byte) As String
        ' Check arguments.
        If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
            Throw New ArgumentNullException("cipherText")
        End If
      
        ' Create an AesCryptoServiceProvider object
        ' with the specified key and IV.
        Using aesAlg As New AesCryptoServiceProvider()
            aesAlg.Key = _HexStringToByteArray("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
            aesAlg.IV = _HexStringToByteArray("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
            ' Create a decryptor to perform the stream transform.
            Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)
            ' Create the streams used for decryption.
            Using msDecrypt As New MemoryStream(cipherText)
                Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
                    Using srDecrypt As New StreamReader(csDecrypt)
                        ' Read the decrypted bytes from the decrypting stream
                        Return srDecrypt.ReadToEnd()
                    End Using
                End Using
            End Using
        End Using
    End Function 'DecryptStringFromBytes_Aes 
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,727 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 31,331 Reputation points Microsoft Vendor
    2024-03-28T08:01:39.0933333+00:00

    Hi @StewartBW ,

    1. Some points you need to be aware of: When converting between strings and byte arrays, it's important to specify the encoding to ensure consistency. In your code, you're using the default encoding, which might not be the most suitable in all cases. You could explicitly specify UTF-8 encoding for consistency. By default, AES encryption in .NET uses PKCS7 padding. You may want to explicitly specify the padding mode to ensure consistency, especially if interoperability with other systems is a concern.
    2. You can use the Using statement for ICryptoTransform to ensure proper disposal of resources.

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.