首页 > 学院 > 开发设计 > 正文

vb.net DES加密与解密

2019-11-08 03:10:45
字体:
来源:转载
供稿:网友

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 Function2、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请注意:不同的加密方式,密钥长度有要求;密钥可以写入配置文件中,定期调整;


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表