.NET加密实例AES128
一般在多方业务交互时会对消息体使用秘钥进行加密,生成密文后进行传输,对方接收后再进行解密,最终拿到传递过来的消息实体,本文给出的是.NET AES128加密实例,希望能帮助到需要的朋友。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1.Model //命名空间需要更改
{
public class AES128
{
/// <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>
/// 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);
}
}
}
版权声明:
作者:兴兴
文章:.NET加密实例AES128
链接:https://www.networkcabin.com/original/1381
文章版权归本站所有,未经授权请勿转载。
作者:兴兴
文章:.NET加密实例AES128
链接:https://www.networkcabin.com/original/1381
文章版权归本站所有,未经授权请勿转载。
THE END