文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>用C#实现AES加密和解密

用C#实现AES加密和解密

时间:2011-02-20  来源:linzheng

需要加入引用   using System.Security.Cryptography;

 /// <summary>
/// 有密码的AES加密
/// </summary>
/// <param name="text">加密字符</param>
/// <param name="password">加密的密码</param>
/// <param name="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 = System.Text.Encoding.UTF8.GetBytes(password);

byte[] keyBytes = new byte[16];

int len = pwdBytes.Length;

if (len > keyBytes.Length) len = keyBytes.Length;

System.Array.Copy(pwdBytes, keyBytes, len);

rijndaelCipher.Key
= keyBytes;


byte[] ivBytes = System.Text.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);

}

/// <summary>
/// 随机生成密钥
/// </summary>
/// <returns></returns>
public static string GetIv(int n)
{
char[] arrChar = new char[]{
'a','b','d','c','e','f','g','h','i','j','k','l','m','n','p','r','q','s','t','u','v','w','z','y','x',
'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','Q','P','R','T','S','V','U','W','X','Y','Z'
};

StringBuilder num
= new StringBuilder();

Random rnd
= new Random(DateTime.Now.Millisecond);
for (int i = 0; i < n; i++)
{
num.Append(arrChar[rnd.Next(
0, arrChar.Length)].ToString());

}

return num.ToString();
}

/// <summary>
/// AES解密
/// </summary>
/// <param name="text"></param>
/// <param name="password"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string AESDecrypt(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[] encryptedData = Convert.FromBase64String(text);

byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);

byte[] keyBytes = new byte[16];

int len = pwdBytes.Length;

if (len > keyBytes.Length) len = keyBytes.Length;

System.Array.Copy(pwdBytes, keyBytes, len);

rijndaelCipher.Key
= keyBytes;

byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
rijndaelCipher.IV
= ivBytes;

ICryptoTransform transform
= rijndaelCipher.CreateDecryptor();

byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

return Encoding.UTF8.GetString(plainText);

}
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载