使用方式  自定 8 個字元長度的字串  或由 Generatekey 得到一個 8字元長度的字串

Dim Des as new CDES

Dim Key as string = Des.GenerateKey

Dim str as string = "I Love Taiwan"

'取得 加密後的字串

Dim EnStr as string = Des.EncryptString(str,Key)

 

'將加密後的字串反解

Dim EnStr as string = Des.DecryptString(EStr,Key)


Public Class cDES

    Public Function GenerateKey() As String
        Dim desCrypto As DESCryptoServiceProvider = CType(DESCryptoServiceProvider.Create(), DESCryptoServiceProvider)
        'File.WriteAllText("HSREDES.des", ASCIIEncoding.ASCII.GetString(desCrypto.Key))
        Return ASCIIEncoding.ASCII.GetString(desCrypto.Key)
    End Function

    ''' <summary>
    ''' 加密字串
    ''' </summary>
    ''' <param name="sInputString"></param>
    ''' <param name="sKey"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function EncryptString(ByVal sInputString As String, ByVal sKey As String) As String

        Dim data As Byte() = Encoding.UTF8.GetBytes(sInputString)
        Dim DES As DESCryptoServiceProvider = New DESCryptoServiceProvider
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
        Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
        Dim result() As Byte = desencrypt.TransformFinalBlock(data, 0, data.Length)
        Return BitConverter.ToString(result)

    End Function

    ''' <summary>
    ''' 解密字符串
    ''' </summary>
    ''' <param name="sInputString"></param>
    ''' <param name="sKey"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function DecryptString(ByVal sInputString As String, ByVal sKey As String) As String
        Dim sInput() As String = sInputString.Split("-".ToCharArray())
        Dim data() As Byte = New Byte(sInput.Length) {}
        For i As Integer = 0 To sInput.Length - 1
            data(i) = Byte.Parse(sInput(i), NumberStyles.HexNumber)
        Next
        Dim DES As DESCryptoServiceProvider = New DESCryptoServiceProvider
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
        Dim desencrypt As ICryptoTransform = DES.CreateDecryptor()
        Dim result() As Byte = desencrypt.TransformFinalBlock(data, 0, data.Length - 1)
        Return Encoding.UTF8.GetString(result)
    End Function

End Class

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Rh 的頭像
    Rh

    程式狂想曲

    Rh 發表在 痞客邦 留言(0) 人氣()