我正在尝试使用我在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()子例程中没有发生任何事情。
答案 0 :(得分:1)
ICryptoTransform
提供了一个单独的函数:TransformFinalBlock
,在加密/解密包含最后一个数据块的缓冲区时应该使用,并确保添加必要的填充。由于您只使用单个块,因此您应该使用此方法而不是TransformBlock
。请注意,返回加密/解密数据,而不是将其放在作为参数传递的缓冲区中。
关于DES的答案是否完整没有提到DES不安全,更一般地说,每次数据加密时你应该使用一个独特的随机IV,但我会假设这个主要用于练习,而不是用于保护任何实际敏感的东西。