今天写个接口,要求如下,需要对应的AES加密(128位),例子php的
C#实现
/// <summary> /// AES 加密 输出hex格式 /// </summary> /// <param name="str">明文(待加密)</param> /// <param name="key">密文</param> /// <returns></returns> public static string AesEncrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.Zeros //加密什么格式对应改为就行,基本的话应该为PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); //return Convert.ToBase64String(resultArray, 0, resultArray.Length); return ByteArrayToHexString(resultArray); } /// <summary> /// 将一个byte数组转换成一个格式化的16进制字符串 /// </summary> /// <param name="data">byte数组</param> /// <returns>格式化的16进制字符串</returns> public static string ByteArrayToHexString(byte[] data) { StringBuilder sb = new StringBuilder(data.Length * 3); foreach (byte b in data) { //16进制数字 sb.Append(Convert.ToString(b, 16).PadLeft(2, '0')); //16进制数字之间以空格隔开 //sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' ')); } return sb.ToString().ToUpper(); }
/// <summary> /// AES 解密 输出hex格式 /// </summary> /// <param name="str">明文(待解密)</param> /// <param name="key">密文</param> /// <returns></returns> public static string AesDecrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; //Byte[] toEncryptArray = Convert.FromBase64String(str); byte[] toEncryptArray = HexStringToByteArray(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.Zeros }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); } /// <summary> /// 将指定的16进制字符串转换为byte数组 /// </summary> /// <param name="s">16进制字符串(如:“7F 2C 4A”或“7F2C4A”都可以)</param> /// <returns>16进制字符串对应的byte数组</returns> public static byte[] HexStringToByteArray(string s) { s = s.Replace(" ", ""); byte[] buffer = new byte[s.Length / 2]; for (int i = 0; i < s.Length; i += 2) buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16); return buffer; }
输出为Base64将我注释的取消就行,这个是因为需求要的是hex格式