C#实现的AES加密解密完整实例
本文实例讲述了C#实现的AES加密解密。分享给大家供大家参考,具体如下:
/******************************************************************
*创建人:HTL
*说明:C#AES加密解密
*******************************************************************/
usingSystem;
usingSystem.Security.Cryptography;
usingSystem.Text;
usingSystem.IO;
publicclassTest
{
publicstaticvoidMain()
{
//密码
stringpassword="1234567890123456";
//加密初始化向量
stringiv="";
stringmessage=AESEncrypt("abcdefghigklmnopqrstuvwxyz0123456789",password,iv);
Console.WriteLine(message);
message=AESDecrypt("8Z3dZzqn05FmiuBLowExK0CAbs4TY2GorC2dDPVlsn/tP+VuJGePqIMv1uSaVErr",password,iv);
Console.WriteLine(message);
}
///<summary>
///AES加密
///</summary>
///<paramname="text">加密字符</param>
///<paramname="password">加密的密码</param>
///<paramname="iv">密钥</param>
///<returns></returns>
publicstaticstringAESEncrypt(stringtext,stringpassword,stringiv)
{
RijndaelManagedrijndaelCipher=newRijndaelManaged();
rijndaelCipher.Mode=CipherMode.CBC;
rijndaelCipher.Padding=PaddingMode.PKCS7;
rijndaelCipher.KeySize=128;
rijndaelCipher.BlockSize=128;
byte[]pwdBytes=System.Text.Encoding.UTF8.GetBytes(password);
byte[]keyBytes=newbyte[16];
intlen=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=newbyte[16];
ICryptoTransformtransform=rijndaelCipher.CreateEncryptor();
byte[]plainText=Encoding.UTF8.GetBytes(text);
byte[]cipherBytes=transform.TransformFinalBlock(plainText,0,plainText.Length);
returnConvert.ToBase64String(cipherBytes);
}
///<summary>
///AES解密
///</summary>
///<paramname="text"></param>
///<paramname="password"></param>
///<paramname="iv"></param>
///<returns></returns>
publicstaticstringAESDecrypt(stringtext,stringpassword,stringiv)
{
RijndaelManagedrijndaelCipher=newRijndaelManaged();
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=newbyte[16];
intlen=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;
ICryptoTransformtransform=rijndaelCipher.CreateDecryptor();
byte[]plainText=transform.TransformFinalBlock(encryptedData,0,encryptedData.Length);
returnEncoding.UTF8.GetString(plainText);
}
}
PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:
密码安全性在线检测:
tools.jb51.net/password/my_password_safe
高强度密码生成器:
tools.jb51.net/password/CreateStrongPassword
MD5在线加密工具:
tools.jb51.net/password/CreateMD5Password
迅雷、快车、旋风URL加密/解密工具:
tools.jb51.net/password/urlrethunder
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下