C#實現Java的AES加密解密算法

 前言

  由於最近有個項目需要對接一個Java開發的接口數據,拿到後有點懵逼,加密解密代碼是Java的,看的有點迷,好在有C#的基礎,看起來還是知道個大概,但是還是在這個數據解密問題上花了很多精力,主要卡住我的問題就是輸出編碼錯了,經過多天的努力,找遍各大網站,試了無數種方案,最終綜合各個網站代碼再結合Java的代碼完美解決了。
下面是我對應整理封裝了加密解密的一個類。如果你也遇到類似問題可以參考以下類,自行調整模式實現。
有不懂的可以評論留言我。

注意事項


  rijndaelCipher.Mode = CipherMode.ECB;
  rijndaelCipher.Padding = PaddingMode.PKCS7;
  rijndaelCipher.KeySize = 128;
  rijndaelCipher.BlockSize = 128;


此代碼表示AES加密模式等,可以根據需要變換對應的值使用。

using System;
using System.Security.Cryptography;
using System.Text;

namespace MyDemo
{
    #region 字符串加密解密
    public class AESEncryption
    {
        #region AES加密
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="text">明文</param>
        /// <param name="key">密鑰,長度爲16的字符串</param>
        /// <param name="iv">偏移量,長度爲16的字符串</param>
        /// <returns>密文</returns>
        public static string AESEncode(string text, string key)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Mode = CipherMode.ECB;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            rijndaelCipher.KeySize = 128;
            rijndaelCipher.BlockSize = 128;
            byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
            byte[] keyBytes = new byte[16];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
                len = keyBytes.Length;
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            //byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
            //rijndaelCipher.IV = ivBytes;//需要IV的啓用這兩句
            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
            byte[] plainText = Encoding.UTF8.GetBytes(text);
            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            //return Convert.ToBase64String(cipherBytes);//輸出爲Base64即啓用此句,註釋下一句
            return ToHex(cipherBytes);//輸出爲hex即啓用此句,註釋上一句
        }
        #endregion

        #region AES解密
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="text">密文</param>
        /// <param name="key">密鑰,長度爲16的字符串</param>
        /// <param name="iv">偏移量,長度爲16的字符串</param>
        /// <returns>明文</returns>
        public static string AESDecode(string text, string key)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Mode = CipherMode.ECB;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            rijndaelCipher.KeySize = 128;
            rijndaelCipher.BlockSize = 128;
            //byte[] encryptedData = Convert.FromBase64String(text);//輸出爲Base64即啓用此句,註釋下一句
            byte[] encryptedData = UnHex(text);//輸出爲hex即啓用此句,註釋上一句
            byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
            byte[] keyBytes = new byte[16];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
                len = keyBytes.Length;
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            //byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
            //rijndaelCipher.IV = ivBytes;//需要IV的啓用這兩句
            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            return Encoding.UTF8.GetString(plainText);
        }
        #endregion

        #region Hex與byte轉碼
        /// <summary>
        /// 從字符串轉換到16進製表示的字符串
        /// </summary>
        /// <param name="bytes">需要轉碼的byte</param>
        /// <returns>返回結果</returns>
        private static string ToHex(byte[] bytes)
        {
            string str = string.Empty;
            if (bytes != null || bytes.Length > 0)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    str += string.Format("{0:X2}", bytes[i]);
                }
            }
            return str.ToLower();
        }

        /// <summary>
        /// 從16進制轉換成utf編碼的字符串
        /// </summary>
        /// <param name="hex">需要轉碼的hex</param>
        /// <returns></returns>
        public static byte[] UnHex(string hex)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
                throw new ArgumentException("hex is not a valid number!", "hex");
            }
            // 需要將 hex 轉換成 byte 數組。
            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每兩個字符是一個 byte。
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message.
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            return bytes;
        }
        #endregion
    }
    #endregion
}

C# 解密java 的AES加密算法:

string temp = AESHelper.AESDecode(data.msg, "20210610abc2f5d3");

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章