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 工具类

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


        #region ========加密========
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text">需要加密的内容</param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, key);
        }


        /// <summary>
        /// AES加密 
        /// </summary>
        /// <param name="text">加密字符</param>
        /// <param name="password">加密的密码</param>
        /// <param name="iv">密钥</param>
        /// <returns></returns>
        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 ========解密========


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text">需要解密的内容</param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            if (!string.IsNullOrEmpty(Text))
            {
                return Decrypt(Text, key);
            }
            else
            {
                return "";
            }
        }


        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="password"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        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 初始化密钥
        /// <summary>
        /// 初始化密钥
        /// </summary>
        /// <param name="secret"></param>
        /// <returns></returns>
        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

    }

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#Java 都支持 AES 加密算法,因此可以在两种语言中进行加密解密。下面是一个示例代码,演示了 C#Java 中如何使用 AES 加密解密数据。 首先是 Java 中的代码,用于加密数据: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AesEncryption { private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String KEY = "0123456789abcdef"; // 16-byte key private static final String IV = "0123456789abcdef"; // 16-byte initialization vector public static String encrypt(String data) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "AES"); IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] encrypted = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encrypted); } } ``` 这个代码使用了 AES/CBC/PKCS5Padding 加密算法,采用了 16 字节的密钥和初始化向量。`encrypt()` 方法接受一个字符串参数,并返回加密后的字符串。 接下来是 C# 中的代码,用于解密数据: ```csharp using System; using System.Security.Cryptography; using System.Text; public class AesDecryption { private static readonly byte[] Key = Encoding.UTF8.GetBytes("0123456789abcdef"); // 16-byte key private static readonly byte[] Iv = Encoding.UTF8.GetBytes("0123456789abcdef"); // 16-byte initialization vector public static string Decrypt(string data) { byte[] encryptedData = Convert.FromBase64String(data); using (Aes aes = Aes.Create()) { aes.Key = Key; aes.IV = Iv; aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length); return Encoding.UTF8.GetString(decrypted); } } } ``` 这个代码使用了相同的 AES/CBC/PKCS5Padding 加密算法和 16 字节的密钥和初始化向量。`Decrypt()` 方法接受一个加密的字符串参数,并返回解密后的字符串。 使用这两个类,可以在 C#Java 中进行 AES 加密解密操作。注意,密钥和初始化向量需要在两种语言中保持一致。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值