2017-08-22 58 views
0

我已经实现了在这个答案的方法加密解密字符串System.Security.Cryptography.CryptographicException:'要解密的数据的长度无效。'字符串双空格

AES Encrypt String in VB.NET

这似乎是加密和解密对大多数串直到字符串中有两个或两个以上空间。

I.e.

  • '巴兹' - 加密/解密细(缓冲液/长度= 16)
  • '奥尔德林' - 加密/解密细(缓冲液/长度= 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输出
巴兹:aTBh1U0OFqW7 + 266LiC7Vg == GC6bUY5pK10L2KgQzpAtgg ==:巴兹
奥尔德林:80fmD0z57R8jmmCkKhCsXg == dixi7bqheBzKhXcT1UEpWQ ==:巴斯Aldrin
抛出的异常:mscorlib.dll中的'System.Security.Cryptography.CryptographicException'
要解密的数据的长度无效。

+0

我已经添加了一个示例 – Kanky

+0

请注意,密码应该是散列,*不*加密 – Plutonix

+0

对不起,我的坏^ _ ^我对Base64没有太多了解 –

回答

1

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

这是我所得到的运行您的例子。

你最后String最终只有一个=所以这条线是不正确的,并生成该错误

ciphertext = ivct(2) & "==" 

这段代码

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

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

,这应该运行得很好。

希望这会有所帮助。

0

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

添加

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

ciphertext = ivct(2) & "==" 

此行修复Base64编码。

0

您也可以更改我的实现,以便加密算法将密文与密文之间用#字符连接,解密将从那里拆分并删除#。对每个人都应该更方便。对不起,最初的不便。

相关问题