close
using System.Security.Cryptography;
using System.Text;
AES解密 :
*注意編碼為utf-8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// AES解密 | |
/// </summary> | |
/// <param name="text">要解密的字串</param> | |
/// <param name="password">KEY值</param> | |
/// <param name="iv">IV值</param> | |
/// <returns>解密後的字串</returns> | |
public static string AESDecrypt(string text, string password, string iv) | |
{ | |
RijndaelManaged rijndaelCipher = new RijndaelManaged(); | |
rijndaelCipher.Mode = CipherMode.CBC; //設定Mode | |
rijndaelCipher.Padding = PaddingMode.PKCS7; //設定Padding | |
rijndaelCipher.KeySize = 128; | |
rijndaelCipher.BlockSize = 128; | |
byte[] encryptedData = Convert.FromBase64String(Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(text))); | |
byte[] pwdBytes = Encoding.UTF8.GetBytes(password); | |
byte[] keyBytes = new byte[16]; | |
int len = pwdBytes.Length; | |
if (len > keyBytes.Length) | |
len = keyBytes.Length; | |
Array.Copy(pwdBytes, keyBytes, len); | |
rijndaelCipher.Key = keyBytes; | |
byte[] ivBytes = Encoding.UTF8.GetBytes(iv); | |
rijndaelCipher.IV = ivBytes; | |
ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); | |
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); | |
return Encoding.UTF8.GetString(plainText); | |
} |
AES加密 :
*注意編碼為utf-8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// AES加密 | |
/// </summary> | |
/// <param name="text">要加密的字串</param> | |
/// <param name="password">KEY值</param> | |
/// <param name="iv">IV值</param> | |
/// <returns></returns> | |
public static string AESEncrypt(string text, string password, string iv) | |
{ | |
RijndaelManaged rijndaelCipher = new RijndaelManaged(); | |
rijndaelCipher.Mode = CipherMode.CBC; | |
rijndaelCipher.Padding = PaddingMode.PKCS7; | |
rijndaelCipher.KeySize = 128; | |
rijndaelCipher.BlockSize = 128; | |
byte[] pwdBytes = Encoding.UTF8.GetBytes(password); | |
byte[] keyBytes = new byte[16]; | |
int len = pwdBytes.Length; | |
if (len > keyBytes.Length) | |
len = keyBytes.Length; | |
Array.Copy(pwdBytes, keyBytes, len); | |
rijndaelCipher.Key = keyBytes; | |
byte[] ivBytes = Encoding.UTF8.GetBytes(iv); | |
rijndaelCipher.IV = ivBytes; | |
ICryptoTransform transform = rijndaelCipher.CreateEncryptor(); | |
byte[] plainText = Encoding.UTF8.GetBytes(text); | |
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length); | |
return Convert.ToBase64String(cipherBytes); | |
} |
全站熱搜