2014-04-16 63 views
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()子例程中。

回答

1

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

没有回答关于DES的问题,完全没有提到DES是不安全的,更一般地说,每次数据加密时应该使用独特的随机IV,但我会认为这主要是为了练习,而不是用于保护任何实际上敏感的东西。

+0

你说得对,我主要使用上面的代码进行练习,我知道我不应该使用像DES这样陈旧和不安全的算法。你关于使用TransformFinalBlock的建议奏效。感谢您提供的信息丰富的建议! –