1
我想解密一个在VB.NET中创建的简单程序中的加密字符串,但它看起来像解密部分不能正常工作。VB.NET DES解密出错
这里是我的代码:
Imports System.Security.Cryptography
Module Module1
Dim data As String = "1234567887654321"
Dim key As String = "1111222233334444"
Dim output As String
Dim bData() As Byte
Dim bKey() As Byte
Dim bEncrypted(7) As Byte
Dim bDecrypted(7) As Byte
Dim nullIV(7) As Byte
Dim desprovider As New DESCryptoServiceProvider()
Sub Main()
bData = HexStringToBytes(data)
bKey = HexStringToBytes(key)
Console.WriteLine("Data: " + data)
Console.WriteLine("Key: " + key)
Encrypt()
Console.WriteLine("Encryption Result :" + GetHexString(bEncrypted))
Decrypt()
Console.WriteLine("Decryption Result :" + GetHexString(bDecrypted))
Console.ReadLine()
End Sub
Private Function GetHexString(ByVal bytes() As Byte, Optional ByVal len As Integer = -1, Optional ByVal spaces As Boolean = False) As String
If len = -1 Then len = bytes.Length
Dim i As Integer
Dim s As String = ""
For i = 0 To len - 1
s += bytes(i).ToString("x2")
If spaces Then s += " "
Next
If spaces Then s = s.TrimEnd()
Return s
End Function
Function HexStringToBytes(ByVal hexstring As String) As Byte()
Dim out((hexstring.Length/2) - 1) As Byte
For i = 0 To (hexstring.Length/2) - 1
out(i) = Convert.ToByte(hexstring.Substring(i * 2, 2), 16)
Next
Return out
End Function
Sub Encrypt()
Dim icryptT As ICryptoTransform = desprovider.CreateEncryptor(bKey, nullIV)
icryptT.TransformBlock(bData, 0, bData.Length, bEncrypted, 0)
End Sub
Sub Decrypt()
Dim icryptT As ICryptoTransform = desprovider.CreateDecryptor(bKey, nullIV)
icryptT.TransformBlock(bEncrypted, 0, bEncrypted.Length, bDecrypted, 0)
End Sub
End Module
下面是输出:
数据:1234567887654321
重点:1111222233334444
加密结果:cb8304b91ce6f9a1
解密结果:0000000000000000
正如你在输出中看到的那样,Encrypt()子程序工作得很好,但它在解密部分都出错了。解密应该返回我的原始数据,但它似乎没有发生在程序的Decrypt()子例程中。
你说得对,我主要使用上面的代码进行练习,我知道我不应该使用像DES这样陈旧和不安全的算法。你关于使用TransformFinalBlock的建议奏效。感谢您提供的信息丰富的建议! –