C# 和JAVA AES加密之间的互相兼容,C#版

#region AES



        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        protected virtual string EcryptHexString2String(string content, string password)
        {
            var ecrypt = EcryptAES(content, password);
            var result = Bytes2HexString(ecrypt);
            return result;
        }
        /// <summary>
        /// 得到加密之后的16位进制的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected virtual string Bytes2HexString(string str)
        {
            var bytes = Convert.FromBase64String(str);
            var result = "";
            foreach (var i in bytes)
            {
                result = string.IsNullOrWhiteSpace(result) ? $"{i.ToString("X2")}" : $"{result}{i.ToString("X2")}";
            }

            return result;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        protected virtual string EcryptAES(string content, string password)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged
            {
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7,
                KeySize = 128,
                BlockSize = 128
            };
            byte[] pwdBytes = getKey(password);
            byte[] keyBytes = new byte[16];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
                len = keyBytes.Length;
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
            byte[] plainText = Encoding.UTF8.GetBytes(content);
            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            return Convert.ToBase64String(cipherBytes);
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        protected virtual string DecryptHexString2String(string content, string password)
        {
            if (string.IsNullOrEmpty(content))
                return "";
            var bytes = HexString2Bytes(content);
            var result = DecryptAes(Convert.ToBase64String(bytes), password);
            return result;
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="input"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        protected virtual string DecryptAes(string input, string key)
        {
            var encryptedBytes = Convert.FromBase64String(input);
            byte[] pwdBytes = getKey(key);
            byte[] keyBytes = new byte[16];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length) len = keyBytes.Length;
            Array.Copy(pwdBytes, keyBytes, len);
            RijndaelManaged rijndael = new RijndaelManaged
            {
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7,
                KeySize = 128,
                BlockSize = 128,
                Key = keyBytes
            };
            ICryptoTransform transform = rijndael.CreateDecryptor();
            byte[] plainText = transform.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
            return Encoding.UTF8.GetString(plainText);
        }
        /// <summary>
        /// 得到密钥
        /// </summary>
        /// <param name="secret"></param>
        /// <returns></returns>
        public virtual byte[] getKey(string password)
        {
            try
            {
                byte[] key = Encoding.UTF8.GetBytes(password);
                using (var st = new SHA1CryptoServiceProvider())
                {
                    using (var nd = new SHA1CryptoServiceProvider())
                    {
                        var rd = nd.ComputeHash(st.ComputeHash(key));
                        byte[] keyArray = rd.Take(16).ToArray();
                        return keyArray;
                    }
                }
            }
            catch (Exception)
            {

            }
            throw new Exception("初始化密钥出现异常");
        }
        /// <summary>
        /// 16进制转换2进制
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        protected virtual byte[] HexString2Bytes(string content)
        {
            if (string.IsNullOrEmpty(content))
                return null;

            var len = content.Length / 2;
            var result = new byte[len];
            for (var i = 0; i < len; i++)
            {
                result[i] = Convert.ToByte(content.Substring(i * 2, 2), 16);
            }
            return result;
        }

        #endregion
View Code

我的业务中加了个把加密后的内容进行16进制转换,就不改了吧。

 

参考地址:https://blog.csdn.net/qiandeqiande/article/details/102808581?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-10.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-10.nonecase

posted @ 2020-06-22 18:09  隨興∥隨心  阅读(223)  评论(0编辑  收藏  举报