【发布时间】:2017-08-28 09:06:42
【问题描述】:
我找到了这篇文章:link to msdn
我正在尝试做的事情:加密 Byte() 数组,然后解密它。 它可以工作,但解密的结果不等于原始数组。 我的代码:
Dim RMCrypto As New RijndaelManaged()
RMCrypto.Key = Key
RMCrypto.IV = IV
RMCrypto.Padding = PaddingMode.Zeros
Dim dataToDecrypt As Byte() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
Dim encrypted As Byte() = Encrypt(dataToDecrypt, RMCrypto)
Dim roundtrip As Byte() = Decrypt(encrypted, RMCrypto)
在哪里
Private Function Encrypt(ByVal plainText As Byte(), RMCrypto As RijndaelManaged) As Byte()
Dim encrypted() As Byte
Using RMCrypto
' Create a decrytor to perform the stream transform.
Dim encryptor As ICryptoTransform = RMCrypto.CreateEncryptor(RMCrypto.Key, RMCrypto.IV)
' Create the streams used for encryption.
Using msEncrypt As New MemoryStream()
Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
Using swEncrypt As New StreamWriter(csEncrypt)
'Write all data to the stream.
swEncrypt.Write(plainText)
End Using
encrypted = msEncrypt.ToArray()
End Using
End Using
End Using
' Return the encrypted bytes from the memory stream.
Return encrypted
End Function 'Encrypt
和
Private Function Decrypt(ByVal cipherText() As Byte, RMCrypto As RijndaelManaged) As Byte()
Dim plaintext As Byte()
Using RMCrypto
' Create a decrytor to perform the stream transform.
Dim decryptor As ICryptoTransform = RMCrypto.CreateDecryptor(RMCrypto.Key, RMCrypto.IV)
' Create the streams used for decryption.
Using msDecrypt As New MemoryStream(cipherText)
Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
Using srDecrypt As New StreamReader(csDecrypt)
' Read the decrypted bytes from the decrypting stream
' and place them in a string.
plaintext = Encoding.UTF8.GetBytes(srDecrypt.ReadToEnd())
End Using
End Using
End Using
End Using
Return plaintext
End Function 'Decrypt
它是如何工作的:
Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
encrypted: 221 54 108 65 95 233 31 124 101 181 205 176 13 233 85 252
decrypted: 15 45 15 239 191 189 239 191 189 14 58 239 191 189 9 118 37 239 191 189 212 149 239 191 189 58
如我们所见,看起来加密是对的,但解密是完全错误的——它甚至还有更多的成员!
附:可能是由于Decrypt 函数中从字符串到 Byte() 的错误转换吗?
更有趣的时刻:decrypted改变它的大小,每次都给出一个新的答案!
【问题讨论】:
-
Rijndael 是一种分组密码,在默认 (CBC) 模式下,它以 128 位 = 16 字节的块生成/预期密文。您的
dataToDecrypt仅 11 个字节长,因此不是一个完整的块,因此无法解密。 -
@Iridium 你是对的!我将它的大小更改为 16 字节并得到另一个错误。你能看看这个吗?
-
尝试更改
rijAlg.Padding的不同值,它可以解决Iridium描述的问题。 -
在从内存流中读取内容之前,需要让 CryptoStream 的使用结束。
-
encrypted = msEncrypt.ToArray()在加密期间应该在CryptoStream的End Using后面。解密期间的读取可能没问题。但是不要在那里转换为 UTF-8,你只需要返回字节。
标签: .net vb.net encryption stream cryptography