2017-08-22 54 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

您也可以更改我的實現,以便加密算法將密文與密文之間用#字符連接,解密將從那裏拆分並刪除#。對每個人都應該更方便。對不起,最初的不便。

相關問題