我已经尝试过TripleDESCryptoServiceProvider()。 我稍微更改了加密/解密密钥,想知道为什么不同的密钥可以成功解密加密文本。
(我也试过有或没有指定不同的IV,相同的结果)
密钥的差异在TestKey1(5) = 4, TestKey2(5) = 5
Imports System.Net
Imports System.IO
Imports System.Security.Cryptography
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim tDESalg As New TripleDESCryptoServiceProvider()
Dim Testkey1 As Byte() = UTF8Encoding.UTF8.GetBytes("Z4xC#49S3$3!A470&i0O51@5")
' Create a string to encrypt.
Dim sData As String = "Here is some data to encrypt."
' Encrypt the string to an in-memory buffer.
Dim Data As Byte() = TrippleDESCSPSample.EncryptTextToMemory(sData, Testkey1, tDESalg.IV)
Dim Testkey2 As Byte() = UTF8Encoding.UTF8.GetBytes("Z4xC#59S3$3!A470&i0O51@5")
Debug.Print(Testkey1.Equals(Testkey2))
' Decrypt the buffer back to a string.
Dim Final As String = TrippleDESCSPSample.DecryptTextFromMemory(Data, Testkey2, tDESalg.IV)
' Display the decrypted string to the console.
Response.Write(Final)
End Sub
End Class
Class TrippleDESCSPSample
Public Shared Function EncryptTextToMemory(Data As String, Key As Byte(), 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 ASCIIEncoding().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
Public Shared Function DecryptTextFromMemory(Data As Byte(), Key As Byte(), 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 As Byte() = New Byte(Data.Length - 1) {}
' 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 ASCIIEncoding().GetString(fromEncrypt)
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Return Nothing
End Try
End Function
End Class