AES decrypt String and return a String - Android java.security

Android examples for java.security:AES

Description

AES decrypt String and return a String

Demo Code


//package com.java2s;

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static final String AES = "AES";
    public static String CRYPT_KEY = "your key";
    public static byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0 };/*from  ww w  .  ja  v  a2  s. c  o  m*/

    public final static String decrypt(String data) {
        try {
            return new String(decrypt(hex2byte(data.getBytes("utf-8")),
                    CRYPT_KEY));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] decrypt(byte[] src, String key) throws Exception {

        //SecretKey seckey = geneKey(key);

        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), AES);

        IvParameterSpec ivspec = new IvParameterSpec(iv);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);// ,
        // cipher.update(src);
        return cipher.doFinal(src);// 

    }

    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("");
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }
}

Related Tutorials