[C#][VB.Net] AES 加解密

  • 30617
  • 0
  • C#
  • 2011-06-28

摘要:[C#][VB.Net] AES 加解密

由於 AES 加解密過程中需要兩個位元組陣列: KeyIV 而且必須符合規定的大小

因此這兩個資料,我們可以利用 MD5CryptoServiceProviderRfc2898DeriveBytes 等方式產生雜湊碼

加密 (C#) :


        private string enprypt(string plainText, string key)
        {
            AES = new RijndaelManaged();
            MD5 = new MD5CryptoServiceProvider();
            byte[] plainTextData = Encoding.Unicode.GetBytes(plainText);
            byte[] keyData = MD5.ComputeHash( Encoding.Unicode.GetBytes(key));
            byte[] IVData= MD5.ComputeHash(Encoding.Unicode.GetBytes("Alex Lee"));
            ICryptoTransform transform = AES.CreateEncryptor(keyData, IVData);
            byte[] outputData = transform.TransformFinalBlock(plainTextData, 0, plainTextData.Length);
            return Convert.ToBase64String(output);
        }

 

 

加密 (VB) :


    Private Function encrypt(ByVal plainText As String, ByVal key As String) As String
        Dim AES As New RijndaelManaged()
        Dim MD5 As New MD5CryptoServiceProvider()
        Dim plainTextData As Byte() = Encoding.Unicode.GetBytes(plainText)
        Dim keyData As Byte() = MD5.ComputeHash(Encoding.Unicode.GetBytes(key))
        Dim IVData As Byte() = MD5.ComputeHash(Encoding.Unicode.GetBytes("Alex Lee"))
        Dim transform As ICryptoTransform = AES.CreateEncryptor(keyData, IVData)
        Dim outputData As Byte() = transform.TransformFinalBlock(plainTextData, 0, plainTextData.Length)
        encrypt = Convert.ToBase64String(outputData)
    End Function

 

解密(C#):


        private string decrypt(byte[] cipherTextData, string key)
        {
            AES = new RijndaelManaged();
            MD5 = new MD5CryptoServiceProvider();
            byte[] keyData = MD5.ComputeHash(Encoding.Unicode.GetBytes(key));
            byte[] IVData = MD5.ComputeHash(Encoding.Unicode.GetBytes("Alex Lee"));
            ICryptoTransform transform = AES.CreateDecryptor(keyData, IVData);
            byte[] outputData = transform.TransformFinalBlock(cipherTextData, 0, cipherTextData.Length);
            return Encoding.Unicode.GetString(outputData);
        }

解密(VB):


    Private Function decrypt(ByVal cipherTextData As Byte(), ByVal key As String) As String
        Dim AES As New RijndaelManaged()
        Dim MD5 As New MD5CryptoServiceProvider()
        Dim keyData As Byte() = MD5.ComputeHash(Encoding.Unicode.GetBytes(key))
        Dim IVData As Byte() = MD5.ComputeHash(Encoding.Unicode.GetBytes("Alex Lee"))
        Dim transform As ICryptoTransform = AES.CreateDecryptor(keyData, IVData)
        Dim outputData As Byte() = transform.TransformFinalBlock(cipherTextData, 0, cipherTextData.Length)
        decrypt = Encoding.Unicode.GetString(outputData)
    End Function

 

C#原始程式檔
VB原始程式檔