C#AES128 加解密
AesUtil.Encrypt(textBox1.Text.ToString(), “12345678”); //加密调用
AesUtil.Decrypt(textBox2.Text.ToString(), “12345678”); //解密调用
///
/// AES加密字符串
///
///
///
///
///
public static string Encrypt(string data, string key, string iv = “”)
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
byte[] result = Encrypt(new AesModel
{
Data = bytes,
Key = key,
IV = iv,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
});
if (result == null)
{
return “”;
}
return Convert.ToBase64String(result);
}
///
/// AES解密字符串
///
///
///
///
///
public static string Decrypt(string data, string key, string iv = “”)
{
byte[] bytes = Convert.FromBase64String(data);
byte[] result = Decrypt(new AesModel
{
Data = bytes,
Key = key,
IV = iv,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
});
if (result == null)
{
return “”;
}
return Encoding.UTF8.GetString(result);
}
public class AesModel
{
///
/// 需要加密/解密的数据
///
public byte[] Data { get; set; }
/// <summary>
/// 密钥
/// </summary>
public string Key { get; set; }
/// <summary>
/// 向量
/// </summary>
public string IV { get; set; }
/// <summary>
/// 加密模式
/// </summary>
public CipherMode Mode { get; set; }
/// <summary>
/// 填充模式
/// </summary>
public PaddingMode Padding { get; set; }
}
}