AES decrypt Base Text - Android java.security

Android examples for java.security:AES

Description

AES decrypt Base Text

Demo Code


//package com.java2s;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;

public class Main {
    public static String decryptBase64Text(String key, String src)
            throws Exception {
        byte[] enc = Base64.decode(src, Base64.DEFAULT);
        return decryptBytes(key, enc);
    }//from  ww  w .ja v  a  2s .  c om

    public static String decryptBytes(String key, byte[] src)
            throws Exception {
        byte[] rawKey = getRawKey(key);
        return new String(decrypt(rawKey, src));
    }

    private static byte[] getRawKey(String key) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(key.getBytes());
        kgen.init(256, sr);
        SecretKey skey = kgen.generateKey();
        return skey.getEncoded();
    }

    private static byte[] decrypt(byte[] key, byte[] src) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        return cipher.doFinal(src);
    }
}

Related Tutorials