android中的AES加密/解密
String encData= encrypt("keykey".getBytes("UTF-16LE"), ("0123000000000215").getBytes("UTF-16LE"));
String decData= decrypt("keykey",Base64.decode(encData.getBytes("UTF-16LE"), Base64.DEFAULT));
加密功能
private static String encrypt(byte[] key, byte[] clear) throws Exception
{
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest(key);
SecretKeySpec skeySpec = new SecretKeySpec(digestOfPassword, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return Base64.encodeToString(encrypted,Base64.DEFAULT);
}
解密功能
private static String decrypt(String key, byte[] encrypted) throws Exception
{
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest(key.getBytes("UTF-16LE"));
SecretKeySpec skeySpec = new SecretKeySpec(digestOfPassword, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted, "UTF-16LE");
}
AES在C#中进行加密/解密
static void Main(string[] args)
{
string enc = encryptAES("0123000000000215", "keykey");
string dec = decryptAES(enc, "keykey");
Console.ReadKey();
}
加密功能
public static string encryptAES(string input, string key)
{
var plain = Encoding.Unicode.GetBytes(input);
// 128 bits
AesCryptoServiceProvider provider = new AesCryptoServiceProvider();
provider.KeySize = 128;
provider.Mode = CipherMode.ECB;
provider.Padding = PaddingMode.PKCS7;
provider.Key = CalculateMD5Hash(key);
var enc = provider.CreateEncryptor().TransformFinalBlock(plain, 0, plain.Length);
return Convert.ToBase64String(enc);
}
解密功能
public static string decryptAES(string encryptText, string key)
{
byte[] enc = Convert.FromBase64String(encryptText);
// 128 bits
AesCryptoServiceProvider provider = new AesCryptoServiceProvider();
provider.KeySize = 128;
provider.Mode = CipherMode.ECB;
provider.Padding = PaddingMode.PKCS7;
provider.Key = CalculateMD5Hash(key);
var dec = provider.CreateDecryptor().TransformFinalBlock(enc, 0, enc.Length);
return Encoding.Unicode.GetString(dec);
}
创建md5
public static byte[] CalculateMD5Hash(string input)
{
MD5 md5 = MD5.Create();
byte[] inputBytes = Encoding.Unicode.GetBytes(input);
return md5.ComputeHash(inputBytes);
}