在Android中使用openssl加密和openssl解密吗?和php函数一样?

时间:2019-07-11 13:11:19

标签: php android

此代码已在php中完成工作,但是我在android中也需要与php相同...? 请帮助我在android中如何openssl_encrypt和openssl_decrypt ..?

echo "<br>  ".$data =  openssl_encrypt("Testing", 'AES-256-CBC', "myKey", 0, '1234567890abcdef');

echo "<br>  ".$data1 =  openssl_decrypt("jf07URDndNdAaAvqlMK363//TFczc+qQUUbKk1qigCI=" ,'AES-256-CBC', "myKey", 0, '1234567890abcdef' );

1 个答案:

答案 0 :(得分:0)

查看此

String BuildConfig.AES_API_KEY= "myKey"
String BuildConfig.AES_API_IV="1234567890abcdef"

public static String encrypt(String data) {
    try {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(BuildConfig.AES_API_KEY.getBytes(), "AES");
        byte[] finalIvs = new byte[16];
        int len = BuildConfig.AES_API_IV.getBytes().length > 16 ? 16 : BuildConfig.AES_API_IV.getBytes().length;
        System.arraycopy(BuildConfig.AES_API_IV.getBytes(), 0, finalIvs, 0, len);
        IvParameterSpec ivps = new IvParameterSpec(finalIvs);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivps);
        return Base64.encodeToString(cipher.doFinal(data.getBytes()), Base64.DEFAULT).trim().replaceAll("\n", "").replaceAll("\r", "");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

public static String decrypt(@NonNull String data) {
    try {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(BuildConfig.AES_API_KEY.getBytes(), "AES");
        byte[] finalIvs = new byte[16];
        int len = BuildConfig.AES_API_IV.getBytes().length > 16 ? 16 : BuildConfig.AES_API_IV.getBytes().length;
        System.arraycopy(BuildConfig.AES_API_IV.getBytes(), 0, finalIvs, 0, len);
        IvParameterSpec ivps = new IvParameterSpec(finalIvs);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivps);
        return new String(cipher.doFinal(Base64.decode(data, Base64.DEFAULT)));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}