标签:isnull utils digest encoding utf-8 base64 blog trace try
java代码
private static final String defaultCharset = "UTF-8"; private static final String KEY_AES = "AES"; private static final String KEY_MD5 = "MD5"; public static final String key = "test"; public static String encrypt(String data, String key) { return doAES(data, key, Cipher.ENCRYPT_MODE); } /** * 加解密 * * @param data * @param key * @param mode * @return */ private static String doAES(String data, String key, int mode) { try { if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) { return null; } boolean encrypt = mode == Cipher.ENCRYPT_MODE; byte[] content; if (encrypt) { content = data.getBytes(defaultCharset); } else { content = Base64.decodeBase64(data.getBytes(defaultCharset)); } // 创建密钥 SecretKeySpec keySpec = new SecretKeySpec(md5Digest.digest(key.getBytes(defaultCharset)), KEY_AES); // 创建密码器 Cipher cipher = Cipher.getInstance(KEY_AES); // 初始化 cipher.init(mode, keySpec); byte[] result = cipher.doFinal(content); if (encrypt) { return new String(Base64.encodeBase64(result)); } else { return new String(result, defaultCharset); } } catch (Exception e) { System.err.println("AES密文处理异常" + e); e.printStackTrace(); } return null; }
对应的.Net代码:
public static string AesEncrypt(string str, string key) { //秘钥取md5 MD5 md5 = new MD5CryptoServiceProvider(); byte[] t = md5.ComputeHash(Encoding.UTF8.GetBytes(key)); if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); RijndaelManaged rm = new RijndaelManaged { Key = t, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; ICryptoTransform cTransform = rm.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } public static string AesDecrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; MD5 md5 = new MD5CryptoServiceProvider(); byte[] t = md5.ComputeHash(Encoding.UTF8.GetBytes(key)); Byte[] toEncryptArray = Convert.FromBase64String(str); RijndaelManaged rm = new RijndaelManaged { Key = t, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); }
标签:isnull utils digest encoding utf-8 base64 blog trace try
原文地址:http://www.cnblogs.com/request/p/7680605.html