[C#] 與Android共舞-AES 加解密(Android 端)

2013-03-13

上一篇文章 [C#] 與Android共舞-AES 加密(C# 端) 我們提到 我們在 C# 端
使用AES 256 進行加密,其Key IV 如下:
2013-03-13_192105
現在,我們來看看Android 端的地方如何解密
Andoird Code 解密端:

public static byte[] decryptAES (byte[] ivBytes, byte[] keyBytes,byte[] textBytes) {
    try {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);

        return cipher.doFinal(textBytes);

    } catch (Exception ex) {

        return null;

    }

}



呼叫 解密:


try{

String key="12345678901234567890123456789012";
String iv="1234567890abcdef";
String encryptString="wifhXJU46ETengY/nA+sGQ==";

byte[] descryptBytes=decryptAES(iv.getBytes("UTF-8"),key.getBytes("UTF-8"),Base64.decode(encryptString, Base64.DEFAULT));

Toast.makeText(this,new String(descryptBytes), Toast.LENGTH_LONG).show();

}catch(Exception ex){}    




結果:

Screenshot_2013-03-13-19-28-44

OK 解密完成,順便附上 加密的 function




public static byte[] encryptAES(byte[] ivBytes, byte[] keyBytes,byte[] textBytes) {

    try {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = null;

        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);

        return cipher.doFinal(textBytes);

    } catch (Exception ex) {

        return null;

    }

}




文章參考來源

https://gist.github.com/dealforest/1949873


當麻許的超技八 2014 | Donma Hsu Design.