C#实现Java的AES加密解密算法

前言
  • 由于最近有个项目需要对接一个Java开发的接口数据,拿到后有点懵逼,加密解密代码是Java的,看的有点迷,好在有C#的基础,看起来还是知道个大概,但是还是在这个数据解密问题上花了很多精力,主要卡住我的问题就是输出编码错了,经过多天的努力,找遍各大网站,试了无数种方案,最终综合各个网站代码再结合Java的代码完美解决了。
  • 下面是我对应整理封装了加密解密的一个类。如果你也遇到类似问题可以参考以下类,自行调整模式实现。
  • 有不懂的可以评论留言我。
注意事项
  1. rijndaelCipher.Mode = CipherMode.ECB;
    rijndaelCipher.Padding = PaddingMode.PKCS7;
    rijndaelCipher.KeySize = 128;
    rijndaelCipher.BlockSize = 128;
    此代码表示AES加密模式等,可以根据需要变换对应的值使用。
  2. ECB模式下不需要IV偏移量。
  3. 输出编码hex与base64的相关代码切换,代码中已注释说明。
  4. 在线加密解密工具地址:(自己测试用的) http://tool.chacuo.net/cryptaes 可参考图中在线加密解密自由组合
完整代码
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
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值