ASP.NET加密HEX字符

时间:2011-08-30 16:01:36

标签: asp.net

对于使用HEX而不是ASCII进行加密,可以对此代码执行哪些操作?

加密:

Public Function EncryptAES(ByVal sIn As String, ByVal sKey As String) As String
    Dim AES As New RijndaelManaged
    Dim ahashMD5 As New MD5CryptoServiceProvider()
    AES.Key = ahashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey))
    AES.Mode = CipherMode.ECB
    Dim AESEncrypt As ICryptoTransform = AES.CreateEncryptor()
    Dim aBuffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(sIn)
    Return Convert.ToBase64String(AESEncrypt.TransformFinalBlock(aBuffer, 0, aBuffer.Length))
End Function

解密:

Public Function DecryptAES(ByVal sOut As String, ByVal sKey As String) As String
    Dim dAES As New RijndaelManaged
    Dim dahashMD5 As New MD5CryptoServiceProvider()
    dAES.Key = dahashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey))
    dAES.Mode = CipherMode.ECB
    Dim dAESDecrypt As ICryptoTransform = dAES.CreateDecryptor()
    sOut = Replace(sOut, " ", "+", 1, -1, CompareMethod.Text)
    Dim daBuffer As Byte() = Convert.FromBase64String(sOut)
    Return System.Text.ASCIIEncoding.ASCII.GetString(dAESDecrypt.TransformFinalBlock(daBuffer, 0, daBuffer.Length))
End Function

1 个答案:

答案 0 :(得分:0)

可能有一种不那么冗长的方法,但是下面的内容应该有所帮助:

Dim i = 0
Dim result = String.Empty
Dim bytes = ..a byte array containing the hashed bytes...
For i As Integer = 0 to bytes.Length
    result += String.Format("{0:x2}", bytes(i))
Next

因此,应用此方法并使用Return,而不是在将字节转换为字符串时使用Return result的最后一行。