vb.net DES加密与解密

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/baronyang/article/details/55517816

1、DES加密

Public Function EncryptDes(ByVal SourceStr As String, Optional ByVal myKey As String = "", Optional ByVal myIV As String = "") As String '使用的DES对称加密
        If String.IsNullOrEmpty(myKey) Then
            myKey = Me.JMKey
        End If
        If String.IsNullOrEmpty(myIV) Then
            myIV = Me.JMIv
        End If
        Dim des As New System.Security.Cryptography.DESCryptoServiceProvider 'DES算法
        'Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider'TripleDES算法
        Dim inputByteArray As Byte()
        inputByteArray = System.Text.Encoding.Default.GetBytes(SourceStr)
        des.Key = System.Text.Encoding.UTF8.GetBytes(myKey) 'myKey DES用8个字符,TripleDES要24个字符
        des.IV = System.Text.Encoding.UTF8.GetBytes(myIV) 'myIV DES用8个字符,TripleDES要24个字符
        Dim ms As New System.IO.MemoryStream
        Dim cs As New System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
        Dim sw As New System.IO.StreamWriter(cs)
        sw.Write(SourceStr)
        sw.Flush()
        cs.FlushFinalBlock()
        ms.Flush()
        Return Convert.ToBase64String(ms.GetBuffer(), 0, ms.Length)
    End Function
2、DES解密

Public Function DecryptDes(ByVal SourceStr As String, Optional ByVal myKey As String = "", Optional ByVal myIV As String = "") As String    '使用标准DES对称解密
        If String.IsNullOrEmpty(SourceStr) Then
            Return SourceStr
        End If
        If SourceStr = "" Then
            Return SourceStr
        End If
        If String.IsNullOrEmpty(myKey) Then
            myKey = Me.JMKey
        End If
        If String.IsNullOrEmpty(myIV) Then
            myIV = Me.JMIv
        End If
        Dim des As New System.Security.Cryptography.DESCryptoServiceProvider 'DES算法
        'Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider'TripleDES算法
        des.Key = System.Text.Encoding.UTF8.GetBytes(myKey) 'myKey DES用8个字符,TripleDES要24个字符
        des.IV = System.Text.Encoding.UTF8.GetBytes(myIV) 'myIV DES用8个字符,TripleDES要24个字符
        Dim buffer As Byte() = Convert.FromBase64String(SourceStr)
        Dim ms As New System.IO.MemoryStream(buffer)
        Dim cs As New System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read)
        Dim sr As New System.IO.StreamReader(cs)
        DecryptDes = sr.ReadToEnd()
        Return DecryptDes
    End Function

请注意:不同的加密方式,密钥长度有要求;密钥可以写入配置文件中,定期调整;

展开阅读全文

没有更多推荐了,返回首页