VB.NET DES解密出错



我试图在VB.NET中创建的一个简单程序中解密加密的字符串,但解密部分似乎无法正常工作。

这是我的代码:

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()子例程中似乎什么都没有发生。

ICryptoTransform提供了一个单独的函数:TransformFinalBlock,在加密/解密包含最后一块数据的缓冲区时应使用该函数,并确保添加必要的填充。由于您只使用单个块,因此应该使用此方法,而不是TransformBlock。请注意,返回加密/解密的数据,而不是将其放在作为参数传递的缓冲区中。

如果不提到DES是不安全的,那么关于DES的答案就不完整了,更普遍地说,每次加密数据时都应该使用唯一的随机IV,但我认为这主要是为了实践,而不是用于保护任何实际敏感的东西。

最新更新