none
VB.net 的加密函数如何使用 RRS feed

  • 问题

  • 我想对字符串进行加密,而且加密后使用解密函数能够得到原来的字符串。如何实现?

    感谢大家支持

    2011年5月5日 15:06

答案

  • 你好

    或者你可以嘗試使用 TripleDESCryptoServiceProvider Class

    詳情可以參考以下URL

    http://msdn.microsoft.com/zh-cn/library/system.security.cryptography.tripledescryptoserviceprovider.aspx#Y1700

    以下是我測試的Sample Code

    定義 Key 属性和初始化向量 (IV) 

     Private Key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}

        Private IV() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}

     Dim tdesp As New TripleDESCryptoServiceProvider

     

            Dim s As String = "你好嗎,,,... abddd yeah"

            MsgBox(s)

            Dim byteEncrypted() As Byte = EncryptTextToMemory(s, Key, IV)

            Dim enc As New System.Text.UnicodeEncoding()

            Dim EncryptedString As String = enc.GetString(byteEncrypted)

            MessageBox.Show(EncryptedString)

            Dim byteToDecrypt() As Byte = enc.GetBytes(EncryptedString)

            Dim decryptedText As String = DecryptTextFromMemory(byteToDecrypt, Key, IV)

            MsgBox(decryptedText )

        Function EncryptTextToMemory(ByVal Data As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
            Try
                ' Create a MemoryStream.
                Dim mStream As New MemoryStream
                ' Create a CryptoStream using the MemoryStream 
                ' and the passed key and initialization vector (IV).
                Dim cStream As New CryptoStream(mStream, _
                                                New TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV), _
                                                CryptoStreamMode.Write)
                ' Convert the passed string to a byte array.
                Dim toEncrypt As Byte() = New UnicodeEncoding().GetBytes(Data)
                ' Write the byte array to the crypto stream and flush it.
                cStream.Write(toEncrypt, 0, toEncrypt.Length)
                cStream.FlushFinalBlock()
                ' Get an array of bytes from the 
                ' MemoryStream that holds the 
                ' encrypted data.
                Dim ret As Byte() = mStream.ToArray()
                ' Close the streams.
                cStream.Close()
                mStream.Close()
                ' Return the encrypted buffer.
                Return ret
            Catch e As CryptographicException
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
                Return Nothing
            End Try
        End Function
        Function DecryptTextFromMemory(ByVal Data() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
            Try
                ' Create a new MemoryStream using the passed 
                ' array of encrypted data.
                Dim msDecrypt As New MemoryStream(Data)
                ' Create a CryptoStream using the MemoryStream 
                ' and the passed key and initialization vector (IV).
                Dim csDecrypt As New CryptoStream(msDecrypt, _
                                                  New TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), _
                                                  CryptoStreamMode.Read)
                ' Create buffer to hold the decrypted data.
                Dim fromEncrypt(Data.Length) As Byte
                ' Read the decrypted data out of the crypto stream
                ' and place it into the temporary buffer.
                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)
                'Convert the buffer into a string and return it.
                Return New UnicodeEncoding().GetString(fromEncrypt)
            Catch e As CryptographicException
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
                Return Nothing
            End Try
        End Function
    Please correct me if my concept is wrong


    Chi
    2011年5月5日 21:13
    版主
  • 您好

    請參考 DESCryptoServiceProvider 类 : 定义访问数据加密标准 (DES) 算法的加密服务提供程序 (CSP) 版本的包装对象。无法继承此类。

    ' This sample demonstrates using a key based on the cryptographic service provider (CSP) version
    ' of the Data Encryption Standard (DES)algorithm to encrypt a string to a byte array, and then 
    ' to decrypt the byte array back to a string.
    Imports System
    Imports System.IO
    Imports System.Text
    Imports System.Security.Cryptography
    
    
    
    Class CryptoMemoryStream
      
      ' Main method.
      Public Shared Sub Main()
        ' Create a new DES key.
        Dim key As New DESCryptoServiceProvider()
        
        ' Encrypt a string to a byte array.
        Dim buffer As Byte() = Encrypt("This is some plaintext!", key)
        
        ' Decrypt the byte array back to a string.
        Dim plaintext As String = Decrypt(buffer, key)
        
        ' Display the plaintext value to the console.
        Console.WriteLine(plaintext)
      End Sub 'Main
      
      
      ' Encrypt the string.
      Public Shared Function Encrypt(PlainText As String, key As SymmetricAlgorithm) As Byte()
        ' Create a memory stream.
        Dim ms As New MemoryStream()
        
        ' Create a CryptoStream using the memory stream and the 
        ' CSP DES key. 
        Dim encStream As New CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write)
        
        ' Create a StreamWriter to write a string
        ' to the stream.
        Dim sw As New StreamWriter(encStream)
        
        ' Write the plaintext to the stream.
        sw.WriteLine(PlainText)
        
        ' Close the StreamWriter and CryptoStream.
        sw.Close()
        encStream.Close()
        
        ' Get an array of bytes that represents
        ' the memory stream.
        Dim buffer As Byte() = ms.ToArray()
        
        ' Close the memory stream.
        ms.Close()
        
        ' Return the encrypted byte array.
        Return buffer
      End Function 'Encrypt
      
      
      ' Decrypt the byte array.
      Public Shared Function Decrypt(CypherText() As Byte, key As SymmetricAlgorithm) As String
        ' Create a memory stream to the passed buffer.
        Dim ms As New MemoryStream(CypherText)
        
        ' Create a CryptoStream using the memory stream and the 
        ' CSP DES key. 
        Dim encStream As New CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read)
        
        ' Create a StreamReader for reading the stream.
        Dim sr As New StreamReader(encStream)
        
        ' Read the stream as a string.
        Dim val As String = sr.ReadLine()
        
        ' Close the streams.
        sr.Close()
        encStream.Close()
        ms.Close()
        
        Return val
      End Function 'Decrypt
    End Class 'CryptoMemoryStream
    

    歡迎參觀我的Blog.NET菜鳥自救會
    2011年5月6日 1:08

全部回复

  • 你好

    或者你可以嘗試使用 TripleDESCryptoServiceProvider Class

    詳情可以參考以下URL

    http://msdn.microsoft.com/zh-cn/library/system.security.cryptography.tripledescryptoserviceprovider.aspx#Y1700

    以下是我測試的Sample Code

    定義 Key 属性和初始化向量 (IV) 

     Private Key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}

        Private IV() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}

     Dim tdesp As New TripleDESCryptoServiceProvider

     

            Dim s As String = "你好嗎,,,... abddd yeah"

            MsgBox(s)

            Dim byteEncrypted() As Byte = EncryptTextToMemory(s, Key, IV)

            Dim enc As New System.Text.UnicodeEncoding()

            Dim EncryptedString As String = enc.GetString(byteEncrypted)

            MessageBox.Show(EncryptedString)

            Dim byteToDecrypt() As Byte = enc.GetBytes(EncryptedString)

            Dim decryptedText As String = DecryptTextFromMemory(byteToDecrypt, Key, IV)

            MsgBox(decryptedText )

        Function EncryptTextToMemory(ByVal Data As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
            Try
                ' Create a MemoryStream.
                Dim mStream As New MemoryStream
                ' Create a CryptoStream using the MemoryStream 
                ' and the passed key and initialization vector (IV).
                Dim cStream As New CryptoStream(mStream, _
                                                New TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV), _
                                                CryptoStreamMode.Write)
                ' Convert the passed string to a byte array.
                Dim toEncrypt As Byte() = New UnicodeEncoding().GetBytes(Data)
                ' Write the byte array to the crypto stream and flush it.
                cStream.Write(toEncrypt, 0, toEncrypt.Length)
                cStream.FlushFinalBlock()
                ' Get an array of bytes from the 
                ' MemoryStream that holds the 
                ' encrypted data.
                Dim ret As Byte() = mStream.ToArray()
                ' Close the streams.
                cStream.Close()
                mStream.Close()
                ' Return the encrypted buffer.
                Return ret
            Catch e As CryptographicException
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
                Return Nothing
            End Try
        End Function
        Function DecryptTextFromMemory(ByVal Data() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
            Try
                ' Create a new MemoryStream using the passed 
                ' array of encrypted data.
                Dim msDecrypt As New MemoryStream(Data)
                ' Create a CryptoStream using the MemoryStream 
                ' and the passed key and initialization vector (IV).
                Dim csDecrypt As New CryptoStream(msDecrypt, _
                                                  New TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), _
                                                  CryptoStreamMode.Read)
                ' Create buffer to hold the decrypted data.
                Dim fromEncrypt(Data.Length) As Byte
                ' Read the decrypted data out of the crypto stream
                ' and place it into the temporary buffer.
                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)
                'Convert the buffer into a string and return it.
                Return New UnicodeEncoding().GetString(fromEncrypt)
            Catch e As CryptographicException
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
                Return Nothing
            End Try
        End Function
    Please correct me if my concept is wrong


    Chi
    2011年5月5日 21:13
    版主
  • 您好

    請參考 DESCryptoServiceProvider 类 : 定义访问数据加密标准 (DES) 算法的加密服务提供程序 (CSP) 版本的包装对象。无法继承此类。

    ' This sample demonstrates using a key based on the cryptographic service provider (CSP) version
    ' of the Data Encryption Standard (DES)algorithm to encrypt a string to a byte array, and then 
    ' to decrypt the byte array back to a string.
    Imports System
    Imports System.IO
    Imports System.Text
    Imports System.Security.Cryptography
    
    
    
    Class CryptoMemoryStream
      
      ' Main method.
      Public Shared Sub Main()
        ' Create a new DES key.
        Dim key As New DESCryptoServiceProvider()
        
        ' Encrypt a string to a byte array.
        Dim buffer As Byte() = Encrypt("This is some plaintext!", key)
        
        ' Decrypt the byte array back to a string.
        Dim plaintext As String = Decrypt(buffer, key)
        
        ' Display the plaintext value to the console.
        Console.WriteLine(plaintext)
      End Sub 'Main
      
      
      ' Encrypt the string.
      Public Shared Function Encrypt(PlainText As String, key As SymmetricAlgorithm) As Byte()
        ' Create a memory stream.
        Dim ms As New MemoryStream()
        
        ' Create a CryptoStream using the memory stream and the 
        ' CSP DES key. 
        Dim encStream As New CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write)
        
        ' Create a StreamWriter to write a string
        ' to the stream.
        Dim sw As New StreamWriter(encStream)
        
        ' Write the plaintext to the stream.
        sw.WriteLine(PlainText)
        
        ' Close the StreamWriter and CryptoStream.
        sw.Close()
        encStream.Close()
        
        ' Get an array of bytes that represents
        ' the memory stream.
        Dim buffer As Byte() = ms.ToArray()
        
        ' Close the memory stream.
        ms.Close()
        
        ' Return the encrypted byte array.
        Return buffer
      End Function 'Encrypt
      
      
      ' Decrypt the byte array.
      Public Shared Function Decrypt(CypherText() As Byte, key As SymmetricAlgorithm) As String
        ' Create a memory stream to the passed buffer.
        Dim ms As New MemoryStream(CypherText)
        
        ' Create a CryptoStream using the memory stream and the 
        ' CSP DES key. 
        Dim encStream As New CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read)
        
        ' Create a StreamReader for reading the stream.
        Dim sr As New StreamReader(encStream)
        
        ' Read the stream as a string.
        Dim val As String = sr.ReadLine()
        
        ' Close the streams.
        sr.Close()
        encStream.Close()
        ms.Close()
        
        Return val
      End Function 'Decrypt
    End Class 'CryptoMemoryStream
    

    歡迎參觀我的Blog.NET菜鳥自救會
    2011年5月6日 1:08