System.Security.Cryptography.CryptographicException:"要解密的数据长度无效。字符串双倍空格



我已经实现了这个答案中的方法来加密解密字符串

AES 加密 VB.NET 字符串

对于大多数字符串,这似乎是加密和解密良好的,直到字符串有两个或更多空格。

  • "嗡嗡声" - 加密/解密精细(缓冲区/长度 = 16(
  • "Buzz Aldrin" - 加密/解密精细(缓冲区/长度 = 16(
  • "巴兹奥尔德林宇航员" - 加密精细/解密错误(缓冲区/长度 = 31(

System.Security.Cryptography.CryptographicException:"要解密的数据长度无效。

Public Shared Function AES_Decrypt(ByVal ciphertext As String, ByVal key As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim SHA256 As New System.Security.Cryptography.SHA256Cng
Dim plaintext As String = ""
Dim iv As String = ""
Try
Dim ivct = ciphertext.Split(CChar("="))
iv = ivct(0) & "=="
ciphertext = ivct(2) & "=="
AES.Key = SHA256.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))
AES.IV = Convert.FromBase64String(iv)
AES.Mode = Security.Cryptography.CipherMode.CBC
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(ciphertext)
Exception  ---->   plaintext = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return plaintext
Catch ex As system.Exception
Return ex.Message
End Try
End Function

知道我做错了什么或如何纠正它吗?

示例更新

Try
Dim s1, s2, s3 As String
s1 = Crypto.AES_Encrypt("Buzz", "Password")
s2 = Crypto.AES_Encrypt("Buzz Aldrin", "Password")
s3 = Crypto.AES_Encrypt("Buzz Aldrin Astronaut", "Password")
Debug.Print("Buzz : " & s1 & " : " & Crypto.AES_Decrypt(s1, "Password"))
Debug.Print("Buzz Aldrin : " & s2 & " : " & Crypto.AES_Decrypt(s2, "Password"))
Debug.Print("Buzz Aldrin Astronaut : " & s3 & " : " & Crypto.AES_Decrypt(s3, "Password"))
Catch ex As System.Exception
Debug.Print(ex.Message.ToString())
End Try

Debug.Print Output
Buzz : aTBh1U0OFqW7+266LiC7Vg==GC6bUY5pK10L2KgQzpAtgg== : Buzz Buzz Aldrin : 80fmD0z57R8jmmCkKhCsXg==dixi7bqheBzKhXcT1UEpWQ== : Buzz
Aldrin
在 mscorlib 中抛出的异常: 'System.Security.Cryptography.CryptographicException' .dll
要解密的数据长度无效。

巴兹奥尔德林宇航员 :/1RInYgi/XPCpKYKxCCQLg==NgtahaolZmtyRKqG5d3XdWbnTP3o782hoyg7jp6VVAA=

这就是我运行您的示例的内容。

您的最后String仅以一个=结尾,因此此行不正确并生成此错误

ciphertext = ivct(2) & "=="

替换以下行

Dim ivct = ciphertext.Split(CChar("="))
iv = ivct(0) & "=="
ciphertext = ivct(2) & "=="

通过此代码

Dim ivct = ciphertext.Split({"=="}, StringSplitOptions.None)
iv = ivct(0) & "=="
ciphertext = If(ivct.Length = 3, ivct(1) & "==", ivct(1))

这应该运行良好。

希望这有帮助。

用于拆分 IV 和密文的代码实际上通过始终附加==来破坏密文。这会导致 Base64 编码损坏,由于某种原因 VB.Net 没有问题。

ciphertext = ciphertext.Substring(0, ciphertext.Length - ciphertext.Length Mod 4)

ciphertext = ivct(2) & "=="

此行修复了 Base64 编码。

您还可以更改我的实现,以便加密算法将 IV 与密文连接起来,中间有一个 # 字符,解密将从那里拆分它并删除 #。它应该对每个人都更方便。很抱歉给您带来最初的不便。

最新更新