vb.net 加密函数模块,主要用于校验密钥生成。

vb.net 加密函数模块,主要用于校验密钥生成。

以下代码需要引用

Imports System.Security.Cryptography
 

Function MD5(str As String, Optional algorithm As String = "md5", Optional GEncoding As String = "utf-8", Optional Key As String = "", Optional Sign As String = "") As String
    Dim bt As Byte() = Encoding.GetEncoding(GEncoding).GetBytes(str)
    Select Case algorithm.ToLower
      Case "md5"
        Dim Hash As New MD5CryptoServiceProvider
        MD5 = Convert.ToBase64String(Hash.ComputeHash(bt))
        Return MD5.Substring(0, MD5.Length - 2)
      Case "md5sign"
        Dim Hash As New MD5CryptoServiceProvider(), mysign As String = "", t As Byte() = Hash.ComputeHash(bt)
        For Each h As String In t
          If Hex(h).Length = 1 Then mysign &= "0" & Hex(h) Else mysign &= Hex(h)
        Next
        Return mysign.ToLower
      Case "sha1"
        Dim Hash As New SHA1CryptoServiceProvider
        MD5 = Convert.ToBase64String(Hash.ComputeHash(bt))
        Return MD5.Substring(0, MD5.Length - 2)
      Case "sha1sign"
        Dim Hash As New SHA1CryptoServiceProvider, mysign As String = "", t As Byte() = Hash.ComputeHash(bt)
        For Each h As String In t
          If Hex(h).Length = 1 Then mysign &= "0" & Hex(h) Else mysign &= Hex(h)
        Next
        Return mysign.ToLower
      Case "sha384"
        Dim Hash As New SHA384Managed
        MD5 = Convert.ToBase64String(Hash.ComputeHash(bt))
        Return MD5.Substring(0, MD5.Length - 2)
      Case "sha256"
        Dim Hash As New SHA256Managed(), mysign As String = "", t As Byte() = Hash.ComputeHash(bt)
        For Each h As String In t
          If Hex(h).Length = 1 Then mysign &= "0" & Hex(h) Else mysign &= Hex(h)
        Next
        Return mysign.ToLower
      Case "rsa2"
        Dim Hash = New SHA256CryptoServiceProvider(), Provider As New RSACryptoServiceProvider(), Params As RSAParameters = RSAPrivate(Key)
        If Params.ToString Is Nothing Then Return ""
        Provider.ImportParameters(Params)
        Dim formatter As New RSAPKCS1SignatureFormatter(Provider)
        formatter.SetHashAlgorithm("SHA256")
        Return Convert.ToBase64String(formatter.CreateSignature(Hash.ComputeHash(bt)))
      Case "rsa2verify"
        Dim Hash = New SHA256CryptoServiceProvider(), Provider As New RSACryptoServiceProvider(), Params As RSAParameters = RSAPublic(Key)
        If Params.ToString Is Nothing Then Return ""
        Provider.ImportParameters(Params)
        Return Provider.VerifyData(bt, "SHA256", Convert.FromBase64String(Sign))
      Case Else
        Return str
    End Select
  End Function

上一篇:从Excel到Access再到VB.NET学习过程小结


下一篇:回顾2017系列篇(四):永不过时的设计资源