AES 加密解密 C#和Java 相互兼容解决方案

C# 解密Java的密文报错 Padding is invalid and cannot be removed

Java AES 工具类

/**
 *AES加密解密工具类
 *@author M-Y
 */
public class AESUtil {

      public static String CIPHER_ALGORITHM = "AES"; // optional value AES/DES/DESede


      public static Key getKey(String strKey) {
          try {
              if (strKey == null) {
                  strKey = "";
              }
              KeyGenerator _generator = KeyGenerator.getInstance("AES");
              SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
              secureRandom.setSeed(strKey.getBytes());
              _generator.init(128, secureRandom);
              return _generator.generateKey();
          } catch (Exception e) {
              throw new RuntimeException(" 初始化密钥出现异常 ");
          }
      }

      public static String encrypt(String data, String key) throws Exception {
          SecureRandom sr = new SecureRandom();
          Key secureKey = getKey(key);
          Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
          cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr);
          byte[] bt = cipher.doFinal(data.getBytes());
          String strS = new BASE64Encoder().encode(bt);
          return strS;
      }


      public static String decrypt(String message, String key)  {
    	  try{
	          SecureRandom sr = new SecureRandom();
	          Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
	          Key secureKey = getKey(key);
	          cipher.init(Cipher.DECRYPT_MODE, secureKey, sr);
	          byte[] res = new BASE64Decoder().decodeBuffer(message);
	          res = cipher.doFinal(res);
	          return new String(res);
    	  }catch(Exception e){
    		  e.printStackTrace();
    	  }
    	  	return null;
      }

      public static void main(String[] args) throws Exception {
        
      }
  }

C# AES 工具类

 /// 
    /// AES 加密、解密帮助类
    /// 兼容Java 加密解密
    /// 
    public class AESEncrypt
    {
        private static string key = "123456";


        #region ========加密========
        /// 
        /// 加密
        /// 
        /// 需要加密的内容
        /// 
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, key);
        }


        /// 
        /// AES加密 
        /// 
        /// 加密字符
        /// 加密的密码
        /// 密钥
        /// 
        public static string Encrypt(string text, string password)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode = CipherMode.CBC;

            rijndaelCipher.Padding = PaddingMode.PKCS7;

            rijndaelCipher.KeySize = 128;

            rijndaelCipher.BlockSize = 128;

            //byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
            byte[] pwdBytes = getKey(password);
            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length) len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;
            
            rijndaelCipher.IV = new byte[16];

            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

            byte[] plainText = Encoding.UTF8.GetBytes(text);

            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);

            return Convert.ToBase64String(cipherBytes);

        }

        #endregion

        #region ========解密========


        /// 
        /// 解密
        /// 
        /// 需要解密的内容
        /// 
        public static string Decrypt(string Text)
        {
            if (!string.IsNullOrEmpty(Text))
            {
                return Decrypt(Text, key);
            }
            else
            {
                return "";
            }
        }


        /// 
        /// AES解密
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string Decrypt(string text, string password)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode = CipherMode.CBC;

            rijndaelCipher.Padding = PaddingMode.PKCS7;

            rijndaelCipher.KeySize = 128;

            rijndaelCipher.BlockSize = 128;

            byte[] encryptedData = Convert.FromBase64String(text);
            //byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
            byte[] pwdBytes = getKey(password);

            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length) len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;

            rijndaelCipher.IV = new byte[16];

            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();

            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

            return Encoding.UTF8.GetString(plainText);

        }


        #endregion

        #region 初始化密钥
        /// 
        /// 初始化密钥
        /// 
        /// 
        /// 
        public static byte[] getKey(string secret)
        {

            try
            {
                byte[] seed = Encoding.UTF8.GetBytes(secret);
                using (var st = new SHA1CryptoServiceProvider())
                {
                    //return sha1.ComputeHash(seed);
                    using (var nd = new SHA1CryptoServiceProvider())
                    {
                        var rd = nd.ComputeHash(st.ComputeHash(seed));
                        byte[] keyArray = rd.Take(16).ToArray();
                        return keyArray;
                    }
                }
            }
            catch (Exception)
            {

            }
            throw new Exception("初始化密钥出现异常");
        }

        #endregion

    }

 

你可能感兴趣的:(AES 加密解密 C#和Java 相互兼容解决方案)