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

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

 /// <summary>AES加密</summary>  

/// <param name="text">明文</param>  

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

 

 

Java,需要以下引用:

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

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

 

 

  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;

其中核心代码:

 
    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.    }  
posted on 2013-11-12 11:59  记性特差  阅读(1029)  评论(0编辑  收藏  举报