MD5和SHA的加密方式都是单向的,就算是我写的程序用户的密码用这两种方式保存后,我对着看也不知道他们的密码是什么,这用在保存密码上是不错的,但如果是一些需要能将密文还原的应用来说就不合适了,所以接下来就是我们的DES算法上场了。
DES要求两个关健数据 一个是key(密钥)一个是初始化向量(IV)只要这两个数据一致就可以还原出原来的数据,为了方便还是写成函数
TripleDES算法基本上DES是一样的不过加密的强度不同,同SHA1和SHA512区别一样,更高的强度,意味着运算速度的相应下降。
其实用这种方法加密最重要的是保护好KEY和IV。
解密函数
调用
DES要求两个关健数据 一个是key(密钥)一个是初始化向量(IV)只要这两个数据一致就可以还原出原来的数据,为了方便还是写成函数
TripleDES算法基本上DES是一样的不过加密的强度不同,同SHA1和SHA512区别一样,更高的强度,意味着运算速度的相应下降。
其实用这种方法加密最重要的是保护好KEY和IV。
加密函数
Public Function EncryptDes(ByVal SourceStr As String, ByVal myKey As String, ByVal myIV As String) As String '使用的DES对称加密
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()
EncryptDes = Convert.ToBase64String(ms.GetBuffer(), 0, ms.Length)
End Function
解密函数
Public Function DecryptDes(ByVal SourceStr As String, ByVal myKey As String, ByVal myIV As String) As String '使用标准DES对称解密
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()
End Function
调用
Dim mytxt, EDes, msgtxt As String
mytxt = "nyfort的BLOG"
'加密
'注意KEY和IV只能用英文和数字,des是8个字符
EDes = EncryptDes(mytxt, "12345678", "abcdefgh")
msgtxt = "nyfort的BLOG" & vbCrLf & "SHE加密" & vbCrLf & EDes
MessageBox.Show(msgtxt, "SHE加密")
'解密
mytxt = DecryptDes(EDes, "12345678", "abcdefgh")
msgtxt = EDes & vbCrLf & "SHE解密" & vbCrLf & mytxt
MessageBox.Show(msgtxt, "SHE解密")