標籤:例子 style 指定 image 字串轉換 end alt 進位 解密
今天寫個介面,要求如下,需要對應的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格式
C#AES加密