vb.net DES加密与解密

前端之家收集整理的这篇文章主要介绍了vb.net DES加密与解密前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、DES加密

  1. Public Function EncryptDes(ByVal SourceStr As String,Optional ByVal myKey As String = "",Optional ByVal myIV As String = "") As String '使用的DES对称加密
  2. If String.IsNullOrEmpty(myKey) Then
  3. myKey = Me.JMKey
  4. End If
  5. If String.IsNullOrEmpty(myIV) Then
  6. myIV = Me.JMIv
  7. End If
  8. Dim des As New System.Security.Cryptography.DESCryptoServiceProvider 'DES算法
  9. 'Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider'TripleDES算法
  10. Dim inputByteArray As Byte()
  11. inputByteArray = System.Text.Encoding.Default.GetBytes(SourceStr)
  12. des.Key = System.Text.Encoding.UTF8.GetBytes(myKey) 'myKey DES用8个字符,TripleDES要24个字符
  13. des.IV = System.Text.Encoding.UTF8.GetBytes(myIV) 'myIV DES8个字符,TripleDES24个字符
  14. Dim ms As New System.IO.MemoryStream
  15. Dim cs As New System.Security.Cryptography.CryptoStream(ms,des.CreateEncryptor(),System.Security.Cryptography.CryptoStreamMode.Write)
  16. Dim sw As New System.IO.StreamWriter(cs)
  17. sw.Write(SourceStr)
  18. sw.Flush()
  19. cs.FlushFinalBlock()
  20. ms.Flush()
  21. Return Convert.ToBase64String(ms.GetBuffer(),ms.Length)
  22. End Function
2、DES解密

  1. Public Function DecryptDes(ByVal SourceStr As String,Optional ByVal myIV As String = "") As String '使用标准DES对称解密
  2. If String.IsNullOrEmpty(SourceStr) Then
  3. Return SourceStr
  4. End If
  5. If SourceStr = "" Then
  6. Return SourceStr
  7. End If
  8. If String.IsNullOrEmpty(myKey) Then
  9. myKey = Me.JMKey
  10. End If
  11. If String.IsNullOrEmpty(myIV) Then
  12. myIV = Me.JMIv
  13. End If
  14. Dim des As New System.Security.Cryptography.DESCryptoServiceProvider 'DES算法
  15. 'Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider'TripleDES算法
  16. des.Key = System.Text.Encoding.UTF8.GetBytes(myKey) 'myKey DES用8个字符,TripleDES要24个字符
  17. des.IV = System.Text.Encoding.UTF8.GetBytes(myIV) 'myIV DES8个字符,TripleDES24个字符
  18. Dim buffer As Byte() = Convert.FromBase64String(SourceStr)
  19. Dim ms As New System.IO.MemoryStream(buffer)
  20. Dim cs As New System.Security.Cryptography.CryptoStream(ms,des.CreateDecryptor(),System.Security.Cryptography.CryptoStreamMode.Read)
  21. Dim sr As New System.IO.StreamReader(cs)
  22. DecryptDes = sr.ReadToEnd()
  23. Return DecryptDes
  24. End Function

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

猜你在找的VB相关文章