java、C#配套版AES加密
java版加密:
public static String aesEncrypt(String str, String key) throws Exception {
if (str == null || key == null) return null;
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Md5Utils.ShortMd5(key).getBytes("UTF-8"), "AES"));
byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
return new BASE64Encoder().encode(bytes);
}
java版解密:
public static String aesDecrypt(String str, String key) throws Exception {
if (str == null || key == null) return null;
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Md5Utils.ShortMd5(key).getBytes("UTF-8"), "AES"));
byte[] bytes = new BASE64Decoder().decodeBuffer(str);
bytes = cipher.doFinal(bytes);
return new String(bytes, "utf-8");
}
C#版加密:
public static string Encrypt(string toEncrypt,string key)
{
// 256-AES key
//byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] keyArray = Encoding.UTF8.GetBytes(Get16ByteMd5(key));
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.ECB;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
C#版解密:
public static string Decrypt(string toDecrypt,string key)
{
// 256-AES key
//byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] keyArray = Encoding.UTF8.GetBytes(Get16ByteMd5(key));
byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.ECB;
rDel.Padding = PaddingMode.PKCS7;
//rDel.IV = IV;
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString(resultArray);
}
java版用到的代码:
public static String ShortMd5(String sourceStr)
{
String result = "";
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(sourceStr.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++)
{
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
result = buf.toString().substring(8, 24);
}
catch (NoSuchAlgorithmException e)
{
System.out.println(e);
}
return result.toUpperCase();
}
C#版用到的代码:
public static string Get16ByteMd5(string ConvertString)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(ConvertString)), 4, 8);
t2 = t2.Replace("-", "");
return t2.ToUpper();
}