如何加密和解密字符串到base64?

时间:2016-04-19 09:04:09

标签: vb.net encryption

大家好日子,我是vb.net编程的新手。我想加密和解密用户密码,我想出了下面的代码。

 Imports System.Security.Cryptography
 Imports System.Text

 Public Class UPdatePass

   Dim DES As New TripleDESCryptoServiceProvider
   Dim MD5 As New MD5CryptoServiceProvider

 Function Encrypt(StringInput As String, Key As String) As String
    DES.Key = MD5Hash(Key)
    DES.Mode = CipherMode.ECB
    Dim buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(StringInput)
    Return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length))
End Function

 Function Decrypt(EncryptedString As String, Key As String) As String
    DES.Key = MD5Hash(Key)
    DES.Mode = CipherMode.ECB
    Dim Buffer As Byte() = Convert.FromBase64String(EncryptedString)
    Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function

Function MD5Hash(value As String) As Byte()
    Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
End Function

End Class

当我执行代码并解密时,我收到此错误消息。

mscorlib.dll中发生未处理的“System.Security.Cryptography.CryptographicException”类型异常 附加信息:要解密的数据长度无效。

我希望有人能帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

您的代码适用于我。检查您输入的用于加密的密钥是否与解密相同