• netcore对接java ase加密


    参考:https://www.cnblogs.com/aishangyipiyema/p/9948011.html

    参考:https://www.shuzhiduo.com/A/GBJrE78Wz0/

    JAVA代码

    package kevin.demo;
    
    
    import com.sun.org.apache.xpath.internal.objects.XString;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    
    
    public class Hello {
    
    
    
            //算法名称/加密模式/数据填充方式
            private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
            /**
             * 加密
             * @param content    加密的字符串
             * @param encryptKey key值
             * @return String 密文
             * @throws Exception
             */
            public static String encrypt(String content, String encryptKey){
                try {
                    final BASE64Encoder encoder = new BASE64Encoder();
    
                    KeyGenerator kGen = KeyGenerator.getInstance("AES");
                    kGen.init(128);
                    Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
                    //根据加密规则拆分成字节,并加密
                    SecretKeySpec ss=new SecretKeySpec(encryptKey.getBytes(), "AES");
                    String wxd=parseByte2HexStr(ss.getEncoded());
                    cipher.init(Cipher.ENCRYPT_MODE, ss);
                    //密文utf8转码后存在字节数组中
                    byte[] b = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
                    //采用base64算法进行转码
                    return  encoder.encode(b);
                } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) {
                    return null;
                }
            }
        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();
        }
    
            /**
             * 解密
             *
             * @param encryptStr 解密的字符串
             * @param decryptKey 解密的key值
             * @return String 明文
             * @throws Exception
             */
            public static String decrypt(String encryptStr, String decryptKey)  {
                final BASE64Decoder decoder = new BASE64Decoder();
                try {
                    KeyGenerator kGen = KeyGenerator.getInstance("AES");//根据AES生成密钥
                    kGen.init(128);
                    Cipher cipher = Cipher.getInstance(ALGORITHMSTR);//加密规则
                    //根据加密规则拆分成字节,并解密,获取解密方案
                    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
                    //采用base64算法进行转码
                    byte[] encryptBytes = new byte[0];
                    try {
                        encryptBytes = decoder.decodeBuffer(encryptStr);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    byte[] decryptBytes = cipher.doFinal(encryptBytes);
                    return new String(decryptBytes, StandardCharsets.UTF_8);
                } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) {
    
                    return null;
                }
            }
    
    
    
        public static void main(String[] args) {
            String dd=encrypt("wxd5617","1234560123456789");
            String dd2=decrypt(dd,"1234560123456789");
            System.out.println(dd);
    
            System.out.println(dd2);
            }
        }

    NetCore代码

    using System;
    using System.Security.Cryptography;
    using System.Text;
    
    namespace JAVAAESForCshap
    {
    
        public static class EncryptDecryptTool
        {
            /// <summary>
            /// 这个key来自java代码的wxd
            /// </summary>
            private const string key = "31323334353630313233343536373839";
    
            /// <summary>
            /// MD5哈希计算
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            //public static byte[] ConvertStringToMD52(string key)
            //{
    
            //    //byte[] ByteData = Encoding.UTF8.GetBytes(key);
            //    //MD5 oMd5 = MD5.Create();
            //    //byte[] HashData = oMd5.ComputeHash(ByteData);
    
            //    return Convert.ToString(key, 2); 
            //}
    
    
            private static byte[] ConvertStringToMD5(string hexString)
            {
                hexString = hexString.Replace(" ", "");
                if ((hexString.Length % 2) != 0)
                    hexString += " ";
                byte[] returnBytes = new byte[hexString.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                return returnBytes;
            }
    
            /// <summary>
            /// AES加密 
            /// </summary>
            /// <param name="toEncrypt"></param>
            /// <returns></returns>
            public static string Encrypt(string toEncrypt)
            {
                byte[] keyArray = ConvertStringToMD5(key);
                byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);
    
                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;
    
                ICryptoTransform cTransform = rDel.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
    
                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
    
            /// <summary>
            /// AES解密
            /// </summary>
            /// <param name="toDecrypt"></param>
            /// <returns></returns>
            public static string Decrypt(string toDecrypt)
            {
                byte[] keyArray = ConvertStringToMD5(key);
                byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
    
                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;
    
                ICryptoTransform cTransform = rDel.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
    
                return Encoding.UTF8.GetString(resultArray);
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                /*
                 OoU0cxhvu/kgut0FAJ0IWg==
                wxd5617
                 */
                //var dd = AesEncrypt("wxd5617", "1234560123456789");
                //Console.WriteLine(dd);
                //var dd2= AesDecrypt(dd, "1234560123456789");
                //Console.WriteLine(dd2);
                var dd = EncryptDecryptTool.Encrypt("wxd5617");
                Console.WriteLine(dd);
                if (dd == "OoU0cxhvu/kgut0FAJ0IWg==")
                {
                    Console.WriteLine("加密一致");
                }
    
            }
        }
    }

    参考链接1,是java对key有进行特殊处理,而这个特殊处理辨识md5哈希加密。

    而实际场景中,java代码,key直接转为数组进行加密的,因java和c#数组排列不同——具体参考文章2.所以进行16进制转换。通信~~~~

  • 相关阅读:
    操作系统简介
    计算机基础
    Django之form
    CMDB资产采集
    Git
    User model
    多级评论
    个人主页
    media路径设置
    Web框架
  • 原文地址:https://www.cnblogs.com/blogs2014/p/15252858.html
Copyright © 2020-2023  润新知