zoukankan      html  css  js  c++  java
  • 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("
    ", "");
                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");
  • 相关阅读:
    使用Newtonsoft进行JSON序列化时将枚举序列化为字符串的方法
    通过javac导出Jar包
    JAVA中JDBC连接Mysql数据库简单测试
    使用Swashbuckle.AspNetCore生成.NetCore WEBAPI的接口文档
    CentOS7中使用yum安装Nginx的方法
    Dockerfile 指令 ADD 和 COPY介绍
    Azure Web应用中设置静态虚拟目录的方法(比如部署Django需要用到)
    pip常用命令(转载)
    android发布新版忘记keystore(jks)密码终极解决方案
    IntelliJ Idea 常用快捷键列表
  • 原文地址:https://www.cnblogs.com/zoro-zero/p/14897499.html
Copyright © 2011-2022 走看看