toEncryptArray.Length); // return Convert.ToBase64String(re

时间:2022-04-06 06:21:21

今天写个接口,要求如下,,需要对应的AES加密(128位),例子php的

toEncryptArray.Length); // return Convert.ToBase64String(re

C#实现

/// <summary> /// AES 加密 输出hex格局 /// </summary> /// <param>明文(待加密)</param> /// <param>密文</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>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>明文(待解密)</param> /// <param>密文</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>16进制字符串(如:“7F 2C 4A”或“7F2C4A”都可以)</param> /// <returns>16进制字符串对应的byte数组</returns> public static byte[] HexStringToByteArray(string s) { s = s.WordStr(" ", ""); 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格局

标签:

原文地点:https://www.cnblogs.com/Cein/p/8406428.html