using System.Collections.Generic;
using System.Security.Cryptography;
public static void Main()
Console.WriteLine("Exptected: 0EAF22D998F401867172198A4533E158F4CE6B4718B5625616A65B161F7B592F");
Console.WriteLine("Actual : "+ Encrypt("5555555555554444", "96f164eea32184f544e5c2458bc287f82ce91ac2b539730e", "cf90e23dbdd145a08591f2dcc9399d1220240724191335"));
public const string KEY_ALGORITHM = "AES";
public const string CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS7";
public static string Encrypt(string str, string key, string iv)
if (!string.IsNullOrWhiteSpace(str))
byte[] ivBytes = GetIV(iv);
byte[] keyBytes = HexStrToBytes(key);
using (var aes = Aes.Create())
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
using (var ms = new System.IO.MemoryStream())
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
byte[] inputBytes = Encoding.UTF8.GetBytes(str);
cs.Write(inputBytes, 0, inputBytes.Length);
return BytesToHexStr(result);
throw new ArgumentException("AesAlgorithm.encrypt error", ex);
public static string Decrypt(string str, string key, string iv)
if (!string.IsNullOrWhiteSpace(str))
byte[] ivBytes = GetIV(iv);
byte[] keyBytes = HexStrToBytes(key);
using (var aes = Aes.Create())
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
using (var ms = new System.IO.MemoryStream(HexStrToBytes(str)))
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (var reader = new System.IO.StreamReader(cs))
return reader.ReadToEnd();
throw new ArgumentException("AesAlgorithm.decrypt error", ex);
public static byte[] GetIV(string iv)
byte[] iv1 = Encoding.UTF8.GetBytes(iv);
byte[] iv2 = new byte[16];
System.Array.Copy(iv1, 0, iv2, 0, (iv1.Length > iv2.Length ? iv2.Length : iv1.Length));
public static string BytesToHexStr(byte[] bytes)
if (bytes != null && bytes.Length > 0)
StringBuilder stringBuilder = new StringBuilder();
foreach (byte b in bytes)
stringBuilder.Append(b.ToString("X2"));
return stringBuilder.ToString();
public static byte[] HexStrToBytes(string str)
char[] hex = str.ToCharArray();
int length = hex.Length / 2;
byte[] rawData = new byte[length];
for (int i = 0; i < length; i++)
int high = Convert.ToInt32(hex[i * 2].ToString(), 16);
int low = Convert.ToInt32(hex[i * 2 + 1].ToString(), 16);
int value = (high << 4) | low;
rawData[i] = (byte)value;