码迷,mamicode.com
首页 > 编程语言 > 详细

Java与.net 互通的AES加密

时间:2018-08-24 13:25:56      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:convert   plain   public   des   长度   密文   cipher   rom   rgs   

在用到AES加密的时候 。如果涉及到跨平台的问题。通知会遇到.net与java加密结果不一致的问题。现已找到解决办法,做以记录。

 public class AesHelper
    {

        public static string Encry(string text, string key)
        {
            string iv = key;
            if (key.Length > 16)
            {
                // IV为商户MD5密钥后16位
                iv = key.Substring(key.Length - 16);
                // RES的KEY 为商户MD5密钥的前16位
                key = key.Substring(0, 16);
            }
            return EncodeAES(text, key,iv);
        }

        /// <summary>AES加密</summary>  
        /// <param name="text">明文</param>  
        /// <param name="key">密钥,长度为16的字符串</param>  
        /// <param name="iv">偏移量,长度为16的字符串</param>  
        /// <returns>密文</returns>  
        public static string EncodeAES(string text, string key, string iv)
        {
    
            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(key);
            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 = Encoding.UTF8.GetBytes(iv);
            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
            byte[] plainText = Encoding.UTF8.GetBytes(text);
            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            return Convert.ToBase64String(cipherBytes);
        }

        /// <summary>AES解密</summary>  
        /// <param name="text">密文</param>  
        /// <param name="key">密钥,长度为16的字符串</param>  
        /// <param name="iv">偏移量,长度为16的字符串</param>  
        /// <returns>明文</returns>  
        public static string DecodeAES(string text, string key, string iv)
        {
            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(key);
            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 = Encoding.UTF8.GetBytes(iv);
            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            return Encoding.UTF8.GetString(plainText);
        }
    }

  以下是java代码

public class AesUtil {

	// 加密
	public static String encry(String content, String key) throws Exception {
		String IV = key;
		if (key.length() > 16) {
			// IV为商户MD5密钥后16位
			IV = key.substring(key.length() - 16);
			// RES的KEY 为商户MD5密钥的前16位
			key = key.substring(0, 16);
		}

		return encryptData(content, key, IV);
	}

	// 加密
	public static String desEncry(String content, String key) throws Exception {
		String IV = key;
		if (key.length() > 16) {
			// IV为商户MD5密钥后16位
			IV = key.substring(key.length() - 16);
			// RES的KEY 为商户MD5密钥的前16位
			key = key.substring(0, 16);
		}
		return decryptData(content, key, IV);
	}

	/**
	 * aes 加密
	 *
	 * @param data
	 * @return
	 */
	public static String encryptData(String data, String key, String IV) throws Exception {
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			byte[] dataBytes = data.getBytes("UTF-8");
			int plaintextLength = dataBytes.length;
			// if (plaintextLength % blockSize != 0) {
			// plaintextLength = plaintextLength + (blockSize - (plaintextLength
			// % blockSize));
			// }
			byte[] plaintext = new byte[plaintextLength];
			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
			byte[] encrypted = cipher.doFinal(plaintext);
			return new String(Base64.encodeBase64(encrypted));
		} catch (Exception e) {
			throw e;
		}

	}

	/**
	 * aes 解密
	 *
	 * @param data
	 *            密文
	 * @return
	 */
	public static String decryptData(String data, String key, String IV) throws Exception {
		try {
			byte[] encrypted1 = Base64.decodeBase64(data.getBytes("UTF-8"));
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original, "UTF-8");
			return originalString;
		} catch (Exception e) {
			throw e;
		}
	}
	
	public static void main(String[] args) throws Exception {
		String a = encry("测试电子有限公司", "XJQ4RSY0ZCO937VK7VDRZFD7R40RQ5PG");
		System.out.println(a);
		
	}

}

  

Java与.net 互通的AES加密

标签:convert   plain   public   des   长度   密文   cipher   rom   rgs   

原文地址:https://www.cnblogs.com/xinlulicheng/p/9528742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!