加密和解密脚本的简单功能

时间:2012-03-25 21:06:59

标签: vb.net encryption

我有两个应该加密和解密字符串的函数,但加密函数每次都为同一文本返回一个不同的加密字符串。我做错了什么?

Public Shared Function Encrypt(ByVal strText As String, ByVal strKey As String) As String
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Try
        Dim bykey() As Byte = System.Text.Encoding.UTF8.GetBytes(Left(strKey, 8))
        Dim InputByteArray() As Byte = System.Text.Encoding.UTF8.GetBytes(strText)
        Dim des As New DESCryptoServiceProvider
        Dim ms As New IO.MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(bykey, IV), CryptoStreamMode.Write)
        cs.Write(InputByteArray, 0, InputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return ex.Message
    Finally
    End Try
End Function

Public Shared Function Decrypt(ByVal strText As String, ByVal strKey As String) As String
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Dim inputByteArray(strText.Length) As Byte
    Try
        Dim byKey() As Byte = System.Text.Encoding.UTF8.GetBytes(Left(strKey, 8))
        Dim des As New DESCryptoServiceProvider
        inputByteArray = Convert.FromBase64String(strText)
        Dim ms As New IO.MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return encoding.GetString(ms.ToArray())
    Catch ex As Exception
        Return ex.Message
    End Try
End Function

1 个答案:

答案 0 :(得分:0)

也许Decrypt需要读取加密的数据,而不是写入。

Public Shared Function Decrypt(ByVal strText As String, ByVal strKey As String) As String 
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} 
    Dim inputByteArray(strText.Length) As Byte 
    string result
    Try 
        Dim byKey() As Byte = System.Text.Encoding.UTF8.GetBytes(Left(strKey, 8)) 
        Using des As New DESCryptoServiceProvider 
            inputByteArray = Convert.FromBase64String(strText) 
            Using ms As New IO.MemoryStream(inputByteArray)
               Using cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Read) 
                   Using srDecrypt As = New StreamReader(cs)
                       result = srDecrypt.ReadToEnd()
                   End Using
               End Using
            End Using
        End Using
        Return result
    Catch ex As Exception 
        Return ex.Message 
    End Try 
End Function 

编辑:现在可以了。添加使用到一次性类