博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AES加密 对应的 C#/JAVA 方法
阅读量:6927 次
发布时间:2019-06-27

本文共 11632 字,大约阅读时间需要 38 分钟。

由于最近在项目中用到,之前在网上找了好多,来来回回,终于整出来了。 贴出来以后用起来方便C# [csharp] view plaincopyprint? #region AES加解密          ///           ///AES加密(加密步骤)          ///1,加密字符串得到2进制数组;          ///2,将2禁止数组转为16进制;          ///3,进行base64编码          ///           /// 要加密的字符串          /// 密钥          public String Encrypt(String toEncrypt, String key)          {             Byte[] _Key = Encoding.ASCII.GetBytes(key);             Byte[] _Source = Encoding.UTF8.GetBytes(toEncrypt);               Aes aes = Aes.Create("AES");             aes.Mode = CipherMode.ECB;             aes.Padding = PaddingMode.PKCS7;             aes.Key = _Key;             ICryptoTransform cTransform = aes.CreateEncryptor();             Byte[] cryptData = cTransform.TransformFinalBlock(_Source, 0, _Source.Length);             String HexCryptString = Hex_2To16(cryptData);             Byte[] HexCryptData = Encoding.UTF8.GetBytes(HexCryptString);             String CryptString =Convert.ToBase64String(HexCryptData);             return CryptString;         }           ///           /// AES解密(解密步骤)          /// 1,将BASE64字符串转为16进制数组          /// 2,将16进制数组转为字符串          /// 3,将字符串转为2进制数据          /// 4,用AES解密数据          ///           /// 已加密的内容          /// 密钥          public String Decrypt(string encryptedSource, string key)         {             Byte[] _Key = Encoding.ASCII.GetBytes(key);             Aes aes = Aes.Create("AES");             aes.Mode = CipherMode.ECB;             aes.Padding = PaddingMode.PKCS7;             aes.Key = _Key;             ICryptoTransform cTransform = aes.CreateDecryptor();               Byte[] encryptedData = Convert.FromBase64String(encryptedSource);             String encryptedString = Encoding.UTF8.GetString(encryptedData);             Byte[] _Source = Hex_16To2(encryptedString);             Byte[] originalSrouceData = cTransform.TransformFinalBlock(_Source, 0, _Source.Length);             String originalString = Encoding.UTF8.GetString(originalSrouceData);             return originalString;         }           ///           /// 2进制转16进制          ///           String Hex_2To16(Byte[] bytes)         {             String hexString = String.Empty;             Int32 iLength = 65535;             if (bytes != null)             {                 StringBuilder strB = new StringBuilder();                   if (bytes.Length < iLength)                 {                     iLength = bytes.Length;                 }                   for (int i = 0; i < iLength; i++)                 {                     strB.Append(bytes[i].ToString("X2"));                 }                 hexString = strB.ToString();             }             return hexString;         }           ///           /// 16进制转2进制          ///           Byte[] Hex_16To2(String hexString)         {             if ((hexString.Length % 2) != 0)             {                 hexString += " ";             }             Byte[] returnBytes = new Byte[hexString.Length / 2];             for (Int32 i = 0; i < returnBytes.Length; i++)             {                 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);             }             return returnBytes;         }         #endregion #region AES加解密       ///         ///AES加密(加密步骤)       ///1,加密字符串得到2进制数组;       ///2,将2禁止数组转为16进制;       ///3,进行base64编码       ///         /// 要加密的字符串        /// 密钥        public String Encrypt(String toEncrypt, String key)        {            Byte[] _Key = Encoding.ASCII.GetBytes(key);            Byte[] _Source = Encoding.UTF8.GetBytes(toEncrypt);           Aes aes = Aes.Create("AES");            aes.Mode = CipherMode.ECB;            aes.Padding = PaddingMode.PKCS7;            aes.Key = _Key;            ICryptoTransform cTransform = aes.CreateEncryptor();            Byte[] cryptData = cTransform.TransformFinalBlock(_Source, 0, _Source.Length);            String HexCryptString = Hex_2To16(cryptData);            Byte[] HexCryptData = Encoding.UTF8.GetBytes(HexCryptString);            String CryptString =Convert.ToBase64String(HexCryptData);            return CryptString;        }       ///         /// AES解密(解密步骤)       /// 1,将BASE64字符串转为16进制数组       /// 2,将16进制数组转为字符串       /// 3,将字符串转为2进制数据       /// 4,用AES解密数据       ///         /// 已加密的内容        /// 密钥        public String Decrypt(string encryptedSource, string key)        {            Byte[] _Key = Encoding.ASCII.GetBytes(key);            Aes aes = Aes.Create("AES");            aes.Mode = CipherMode.ECB;            aes.Padding = PaddingMode.PKCS7;            aes.Key = _Key;            ICryptoTransform cTransform = aes.CreateDecryptor();           Byte[] encryptedData = Convert.FromBase64String(encryptedSource);            String encryptedString = Encoding.UTF8.GetString(encryptedData);            Byte[] _Source = Hex_16To2(encryptedString);            Byte[] originalSrouceData = cTransform.TransformFinalBlock(_Source, 0, _Source.Length);            String originalString = Encoding.UTF8.GetString(originalSrouceData);            return originalString;        }       ///         /// 2进制转16进制       ///         String Hex_2To16(Byte[] bytes)        {            String hexString = String.Empty;            Int32 iLength = 65535;            if (bytes != null)            {                StringBuilder strB = new StringBuilder();               if (bytes.Length < iLength)                {                    iLength = bytes.Length;                }               for (int i = 0; i < iLength; i++)                {                    strB.Append(bytes[i].ToString("X2"));                }                hexString = strB.ToString();            }            return hexString;        }       ///         /// 16进制转2进制       ///         Byte[] Hex_16To2(String hexString)        {            if ((hexString.Length % 2) != 0)            {                hexString += " ";            }            Byte[] returnBytes = new Byte[hexString.Length / 2];            for (Int32 i = 0; i < returnBytes.Length; i++)            {                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);            }            return returnBytes;        }        #endregion JAVA: [java] view plaincopyprint? /**      * 加密--把加密后的byte数组先进行二进制转16进制在进行base64编码     * @param sSrc      * @param sKey      * @return      * @throws Exception      */      public static String encrypt(String sSrc, String sKey) throws Exception {          if (sKey == null) {              throw new IllegalArgumentException("Argument sKey is null.");          }          if (sKey.length() != 16) {              throw new IllegalArgumentException(                      "Argument sKey'length is not 16.");          }          byte[] raw = sKey.getBytes("ASCII");          SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");            Cipher cipher = Cipher.getInstance("AES");          cipher.init(Cipher.ENCRYPT_MODE, skeySpec);            byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));          String tempStr = parseByte2HexStr(encrypted);            Base64Encoder encoder = new Base64Encoder();          return encoder.encode(tempStr.getBytes("UTF-8"));      }        /**      *解密--先 进行base64解码,在进行16进制转为2进制然后再解码     * @param sSrc      * @param sKey      * @return      * @throws Exception      */      public static String decrypt(String sSrc, String sKey) throws Exception {            if (sKey == null) {              throw new IllegalArgumentException("499");          }          if (sKey.length() != 16) {              throw new IllegalArgumentException("498");          }            byte[] raw = sKey.getBytes("ASCII");          SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");            Cipher cipher = Cipher.getInstance("AES");          cipher.init(Cipher.DECRYPT_MODE, skeySpec);            Base64Encoder encoder = new Base64Encoder();          byte[] encrypted1 = encoder.decode(sSrc);            String tempStr = new String(encrypted1, "utf-8");          encrypted1 = parseHexStr2Byte(tempStr);          byte[] original = cipher.doFinal(encrypted1);          String originalString = new String(original, "utf-8");          return originalString;      }        /**      * 将二进制转换成16进制     *       * @param buf      * @return      */      public static String parseByte2HexStr(byte buf[]) {          StringBuffer sb = new StringBuffer();          for (int i = 0; i < buf.length; i++) {              String hex = Integer.toHexString(buf[i] & 0xFF);              if (hex.length() == 1) {                  hex = '0' + hex;              }              sb.append(hex.toUpperCase());          }          return sb.toString();      }        /**      * 将16进制转换为二进制     *       * @param hexStr      * @return      */      public static byte[] parseHexStr2Byte(String hexStr) {          if (hexStr.length() < 1)              return null;          byte[] result = new byte[hexStr.length() / 2];          for (int i = 0; i < hexStr.length() / 2; i++) {              int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);              int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),                      16);              result[i] = (byte) (high * 16 + low);          }          return result;      } /**   * 加密--把加密后的byte数组先进行二进制转16进制在进行base64编码  * @param sSrc   * @param sKey   * @return   * @throws Exception   */  public static String encrypt(String sSrc, String sKey) throws Exception {   if (sKey == null) {    throw new IllegalArgumentException("Argument sKey is null.");   }   if (sKey.length() != 16) {    throw new IllegalArgumentException(      "Argument sKey'length is not 16.");   }   byte[] raw = sKey.getBytes("ASCII");   SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  Cipher cipher = Cipher.getInstance("AES");   cipher.init(Cipher.ENCRYPT_MODE, skeySpec);  byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));   String tempStr = parseByte2HexStr(encrypted);  Base64Encoder encoder = new Base64Encoder();   return encoder.encode(tempStr.getBytes("UTF-8"));  } /**   *解密--先 进行base64解码,在进行16进制转为2进制然后再解码  * @param sSrc   * @param sKey   * @return   * @throws Exception   */  public static String decrypt(String sSrc, String sKey) throws Exception {  if (sKey == null) {    throw new IllegalArgumentException("499");   }   if (sKey.length() != 16) {    throw new IllegalArgumentException("498");   }  byte[] raw = sKey.getBytes("ASCII");   SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  Cipher cipher = Cipher.getInstance("AES");   cipher.init(Cipher.DECRYPT_MODE, skeySpec);  Base64Encoder encoder = new Base64Encoder();   byte[] encrypted1 = encoder.decode(sSrc);  String tempStr = new String(encrypted1, "utf-8");   encrypted1 = parseHexStr2Byte(tempStr);   byte[] original = cipher.doFinal(encrypted1);   String originalString = new String(original, "utf-8");   return originalString;  } /**   * 将二进制转换成16进制  *   * @param buf   * @return   */  public static String parseByte2HexStr(byte buf[]) {   StringBuffer sb = new StringBuffer();   for (int i = 0; i < buf.length; i++) {    String hex = Integer.toHexString(buf[i] & 0xFF);    if (hex.length() == 1) {     hex = '0' + hex;    }    sb.append(hex.toUpperCase());   }   return sb.toString();  } /**   * 将16进制转换为二进制  *   * @param hexStr   * @return   */  public static byte[] parseHexStr2Byte(String hexStr) {   if (hexStr.length() < 1)    return null;   byte[] result = new byte[hexStr.length() / 2];   for (int i = 0; i < hexStr.length() / 2; i++) {    int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);    int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),      16);    result[i] = (byte) (high * 16 + low);   }   return result;  }

 

转载地址:http://dzkjl.baihongyu.com/

你可能感兴趣的文章
Linux Nano命令
查看>>
线程高级应用-心得4-java5线程并发库介绍,及新技术案例分析
查看>>
linux 弹出光驱失败
查看>>
grep用法详解:grep与正则表达式【转】
查看>>
Python中执行系统命令常见的几种方法--转载
查看>>
spring整合springmvc
查看>>
【译】Kafka学习之路
查看>>
(转) 深度强化学习综述:从AlphaGo背后的力量到学习资源分享(附论文)
查看>>
有关HTTP的粗读
查看>>
在线支付系统功能
查看>>
如果有个库函数接受的是无参数的回调函数怎么办?
查看>>
Asp.Net Core Authentication Middleware And Generate Token
查看>>
[C++]简单的udp通信
查看>>
Recovery模式【转】
查看>>
SQL数据分析概览——Hive、Impala、Spark SQL、Drill、HAWQ 以及Presto+druid
查看>>
mongodb备份与恢复
查看>>
iOS 11确认将完全停止支持 32 位应用
查看>>
hdu 4857 逃生 (拓扑排序+保证最小在前面)
查看>>
shell 编程笔记
查看>>
1215 迷宫
查看>>