C#与Java互通AES算法加密解密

利用AES加密算法对报文进行加密解密,实现C#与Java互通,网上查了一堆也许是因为版本的原因都用不了,于是还是静心下来自己写个:


直接上代码:

C# 需要引用System.Security.Cryptography命名空间

[csharp]  view plain copy print ?
  1. /// <summary>AES加密</summary>  
  2. /// <param name="text">明文</param>  
  3. /// <param name="key">密钥,长度为16的字符串</param>  
  4. /// <param name="iv">偏移量,长度为16的字符串</param>  
  5. /// <returns>密文</returns>  
  6. public static string EncodeAES(string text, string key,string iv)  
  7. {  
  8.     RijndaelManaged rijndaelCipher = new RijndaelManaged();  
  9.     rijndaelCipher.Mode = CipherMode.CBC;  
  10.     rijndaelCipher.Padding = PaddingMode.Zeros;  
  11.     rijndaelCipher.KeySize = 128;  
  12.     rijndaelCipher.BlockSize = 128;  
  13.     byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);  
  14.     byte[] keyBytes = new byte[16];  
  15.     int len = pwdBytes.Length;  
  16.     if (len > keyBytes.Length)  
  17.         len = keyBytes.Length;  
  18.     System.Array.Copy(pwdBytes, keyBytes, len);  
  19.     rijndaelCipher.Key = keyBytes;  
  20.     rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);  
  21.     ICryptoTransform transform = rijndaelCipher.CreateEncryptor();  
  22.     byte[] plainText = Encoding.UTF8.GetBytes(text);  
  23.     byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);  
  24.     return Convert.ToBase64String(cipherBytes);  
  25. }  
  26.   
  27. /// <summary>AES解密</summary>  
  28. /// <param name="text">密文</param>  
  29. /// <param name="key">密钥,长度为16的字符串</param>  
  30. /// <param name="iv">偏移量,长度为16的字符串</param>  
  31. /// <returns>明文</returns>  
  32. public static string DecodeAES(string text, string key,string iv)  
  33. {  
  34.     RijndaelManaged rijndaelCipher = new RijndaelManaged();  
  35.     rijndaelCipher.Mode = CipherMode.CBC;  
  36.     rijndaelCipher.Padding = PaddingMode.Zeros;  
  37.     rijndaelCipher.KeySize = 128;  
  38.     rijndaelCipher.BlockSize = 128;  
  39.     byte[] encryptedData = Convert.FromBase64String(text);  
  40.     byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);  
  41.     byte[] keyBytes = new byte[16];  
  42.     int len = pwdBytes.Length;  
  43.     if (len > keyBytes.Length)  
  44.         len = keyBytes.Length;  
  45.     System.Array.Copy(pwdBytes, keyBytes, len);  
  46.     rijndaelCipher.Key = keyBytes;  
  47.     rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);  
  48.     ICryptoTransform transform = rijndaelCipher.CreateDecryptor();  
  49.     byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);  
  50.     return Encoding.UTF8.GetString(plainText);  
  51. }  

Java,需要以下引用:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

另外需要对String和byte[]相互转换的类,我自己写的Base64Helper


[java]  view plain copy print ?
  1. /** 
  2.  * @author miracle.qu 
  3.  * @see AES算法加密明文 
  4.  * @param data 明文 
  5.  * @param key 密钥,长度16 
  6.  * @param iv 偏移量,长度16 
  7.  * @return 密文 
  8.  */  
  9.   public static String encryptAES(String data,String key,String iv) throws Exception {  
  10.         try {  
  11.             Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");  
  12.             int blockSize = cipher.getBlockSize();  
  13.             byte[] dataBytes = data.getBytes();  
  14.             int plaintextLength = dataBytes.length;  
  15.               
  16.             if (plaintextLength % blockSize != 0) {  
  17.                 plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));  
  18.             }  
  19.   
  20.             byte[] plaintext = new byte[plaintextLength];  
  21.             System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);  
  22.                
  23.             SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");  
  24.             IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());  
  25.   
  26.             cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);  
  27.             byte[] encrypted = cipher.doFinal(plaintext);  
  28.   
  29.             return Base64Helper.encode(encrypted).trim();  
  30.   
  31.         } catch (Exception e) {  
  32.             e.printStackTrace();  
  33.             return null;  
  34.         }  
  35.     }  
  36.   
  37.     /** 
  38.      * @author miracle.qu 
  39.      * @see AES算法解密密文 
  40.      * @param data 密文 
  41.      * @param key 密钥,长度16 
  42.      * @param iv 偏移量,长度16 
  43.      * @return 明文 
  44.      */  
  45.     public static String decryptAES(String data,String key,String iv) throws Exception {  
  46.         try  
  47.         {  
  48.             byte[] encrypted1 = Base64Helper.decode(data);  
  49.                
  50.             Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");  
  51.             SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");  
  52.             IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());  
  53.                
  54.             cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);  
  55.   
  56.             byte[] original = cipher.doFinal(encrypted1);  
  57.             String originalString = new String(original);  
  58.             return originalString.trim();  
  59.         }  
  60.         catch (Exception e) {  
  61.             e.printStackTrace();  
  62.             return null;  
  63.         }  
  64.     }  

其中Base64Helper类是个简单的类,引用:

import org.apache.commons.codec.binary.Base64;


其中核心代码:

[java]  view plain copy print ?
  1. /** 
  2.  * 编码 
  3.  * @param byteArray 
  4.  * @return 
  5.  */  
  6.    public static String encode(byte[] byteArray) {  
  7.        return new String(new Base64().encode(byteArray));  
  8.    }  
  9.   
  10.    /** 
  11.     * 解码 
  12.     * @param base64EncodedString 
  13.     * @return 
  14.     */  
  15.    public static byte[] decode(String base64EncodedString) {  
  16.     return new Base64().decode(base64EncodedString);  
  17.    }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值