decrypt By AES - Android java.security

Android examples for java.security:AES

Description

decrypt By AES

Demo Code


//package com.java2s;

import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static String AP_VIDEO_AES_KEY;
    private static String AP_VIDEO_AES_IV;
    private static final String UTF8 = "UTF-8";

    public static String decryptByAes(String base64EncodedCryptedText) {
        return decryptBase64(base64EncodedCryptedText, AP_VIDEO_AES_KEY,
                AP_VIDEO_AES_IV);//  w  ww .j a  va  2  s  .  c  o m
    }

    static String decryptBase64(String base64EncodedCryptedText,
            String encryptKey, String encryptIv) {
        byte[] byteArray = Base64.decode(base64EncodedCryptedText,
                Base64.DEFAULT);
        String ret = decrypt(byteArray, encryptKey, encryptIv);
        return ret;
    }

    static String decrypt(byte[] byteArray, String encryptKey,
            String encryptIv) {

        if (byteArray == null) {
            return null;
        }

        String strResult = null;

        try {
            byte[] byteKey = encryptKey.getBytes(UTF8);
            byte[] byteIv = encryptIv.getBytes(UTF8);
            SecretKeySpec key = new SecretKeySpec(byteKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(byteIv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, iv);
            byte[] byteResult = cipher.doFinal(byteArray);

            strResult = new String(byteResult, UTF8);

        } catch (Exception e) {
        }

        return strResult;
    }
}

Related Tutorials