时间:2021-07-01 10:21:17 帮助过:17人阅读
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.IO
Imports System.Xml
Imports System.Text
Imports System.Security.Cryptography
Partial Public Class EncryptToBase64DecryptFromBase64Class EncryptToBase64DecryptFromBase64
Public Shared Function EncryptToBase64String()Function EncryptToBase64String(ByVal stringToEncryptsql As SqlString, ByVal SEncryptionKeysql As SqlString) As SqlString
Dim stringToEncrypt As String = CType(stringToEncryptsql, String)
Dim SEncryptionKey As String = CType(SEncryptionKeysql, String)
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Dim key() As Byte = {}
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))
Dim des As New DESCryptoServiceProvider()
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
Catch e As Exception
Return CType(e.Message, SqlString)
End Try
End Function
Public Shared Function DecryptFromBase64String()Function DecryptFromBase64String(ByVal stringToDecryptsql As SqlString, ByVal sEncryptionKeysql As SqlString) As SqlString
Dim stringToDecrypt As String = CType(stringToDecryptsql, String)
Dim sEncryptionKey As String = CType(sEncryptionKeysql, String)
Dim inputByteArray(stringToDecrypt.Length) As Byte
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Dim key() As Byte = {}
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))
Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(stringToDecrypt)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
Catch e As Exception
Return CType(e.Message, SqlString)
End Try
End Function
End Class
完成之后选择生成,部署即可
至于测试,是否可用,打开查询分析器,执行下面语句,
SELECT dbo.DecryptFromBase64String(dbo.EncryptToBase64String('123456','12345678'),'12345678')
如果出现正确的值:123456,说明成功了