VB.NET的AES加密

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

考虑到网上的VB.NET实现AES加密基本上找不到参考代码,所以我花了10个小时查阅资料以及测试得到了以下的实用代码


供大家参考,我参考了以下网页:

http://www.cnblogs.com/MythXin/archive/2011/08/03/2126069.html
http://blog.sina.com.cn/s/blog_6570618601012ilz.html
http://bbs.csdn.net/topics/120022863

代码(不含解释,因为有些具体的地方,我自己也不是很清楚):


    Public Class SecurityCenter
        ''' <summary>
        ''' 加密文本为Base64编码
        ''' </summary>
        ''' <param name="Source"></param>
        ''' <param name="Key"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function EncriptStr(ByVal Source As String,ByVal Key As String) As String
            Dim encripter As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create("AES")
            '设置密钥
            Dim keyBytes() As Byte = (New MD5CryptoServiceProvider).ComputeHash(Encoding.Unicode.GetBytes(Key))

            encripter.BlockSize = keyBytes.Length * 8
            encripter.Key = keyBytes
            encripter.IV = keyBytes
            encripter.Mode = CipherMode.CBC
            encripter.Padding = PaddingMode.PKCS7
            Dim cripter As ICryptoTransform = encripter.CreateEncryptor()
            Dim inBuff As Byte() = Encoding.Unicode.GetBytes(Source)
            Return Convert.ToBase64String(cripter.TransformFinalBlock(inBuff,inBuff.Length))
        End Function
        ''' <summary>
        ''' 解密Base64编码的字符串
        ''' </summary>
        ''' <param name="EncodedStr"></param>
        ''' <param name="Key"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function DecriptStr(ByVal EncodedStr As String,ByVal Key As String) As String
            Dim decripter As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create("AES")
            '设置密钥
            Dim keyBytes() As Byte = (New MD5CryptoServiceProvider).ComputeHash(Encoding.Unicode.GetBytes(Key))
            decripter.BlockSize = keyBytes.Length * 8

            decripter.Key = keyBytes
            decripter.IV = keyBytes
            decripter.Mode = CipherMode.CBC
            decripter.Padding = PaddingMode.PKCS7
            Dim cripter As ICryptoTransform = decripter.CreateDecryptor()
            Dim inBuff As Byte() = Convert.FromBase64String(EncodedStr)
            Return Encoding.Unicode.GetString(cripter.TransformFinalBlock(inBuff,inBuff.Length))
        End Function
    End Class

猜你在找的VB相关文章