由於 AES 加解密過程中需要兩個位元組陣列: Key 及 IV 而且必須符合規定的大小
因此這兩個資料,我們可以利用 MD5CryptoServiceProvider 或 Rfc2898DeriveBytes 等方式產生雜湊碼
加密 (C#) :
01 | private string enprypt( string plainText, string key) |
03 | AES = new RijndaelManaged(); |
04 | MD5 = new MD5CryptoServiceProvider(); |
05 | byte [] plainTextData = Encoding.Unicode.GetBytes(plainText); |
06 | byte [] keyData = MD5.ComputeHash( Encoding.Unicode.GetBytes(key)); |
07 | byte [] IVData= MD5.ComputeHash(Encoding.Unicode.GetBytes( "Alex Lee" )); |
08 | ICryptoTransform transform = AES.CreateEncryptor(keyData, IVData); |
09 | byte [] outputData = transform.TransformFinalBlock(plainTextData, 0, plainTextData.Length); |
10 | return Convert.ToBase64String(output); |
加密 (VB) :
01 | Private Function encrypt( ByVal plainText As String , ByVal key As String ) As String |
02 | Dim AES As New RijndaelManaged() |
03 | Dim MD5 As New MD5CryptoServiceProvider() |
04 | Dim plainTextData As Byte () = Encoding. Unicode .GetBytes(plainText) |
05 | Dim keyData As Byte () = MD5.ComputeHash(Encoding. Unicode .GetBytes(key)) |
06 | Dim IVData As Byte () = MD5.ComputeHash(Encoding. Unicode .GetBytes( "Alex Lee" )) |
07 | Dim transform As ICryptoTransform = AES.CreateEncryptor(keyData, IVData) |
08 | Dim outputData As Byte () = transform.TransformFinalBlock(plainTextData, 0, plainTextData.Length) |
09 | encrypt = Convert.ToBase64String(outputData) |
解密(C#):
01 | private string decrypt( byte [] cipherTextData, string key) |
03 | AES = new RijndaelManaged(); |
04 | MD5 = new MD5CryptoServiceProvider(); |
05 | byte [] keyData = MD5.ComputeHash(Encoding.Unicode.GetBytes(key)); |
06 | byte [] IVData = MD5.ComputeHash(Encoding.Unicode.GetBytes( "Alex Lee" )); |
07 | ICryptoTransform transform = AES.CreateDecryptor(keyData, IVData); |
08 | byte [] outputData = transform.TransformFinalBlock(cipherTextData, 0, cipherTextData.Length); |
09 | return Encoding.Unicode.GetString(outputData); |
解密(VB):
1 | Private Function decrypt( ByVal cipherTextData As Byte (), ByVal key As String ) As String |
2 | Dim AES As New RijndaelManaged() |
3 | Dim MD5 As New MD5CryptoServiceProvider() |
4 | Dim keyData As Byte () = MD5.ComputeHash(Encoding. Unicode .GetBytes(key)) |
5 | Dim IVData As Byte () = MD5.ComputeHash(Encoding. Unicode .GetBytes( "Alex Lee" )) |
6 | Dim transform As ICryptoTransform = AES.CreateDecryptor(keyData, IVData) |
7 | Dim outputData As Byte () = transform.TransformFinalBlock(cipherTextData, 0, cipherTextData.Length) |
8 | decrypt = Encoding. Unicode .GetString(outputData) |
C#原始程式檔
VB原始程式檔