Generate raw AES Key as byte array of RAW_KEY_SIZE size - Android java.security

Android examples for java.security:AES

Description

Generate raw AES Key as byte array of RAW_KEY_SIZE size

Demo Code


//package com.java2s;
import android.util.Base64;
import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;
import java.io.*;

import java.util.ArrayList;

import java.util.List;
import java.util.Random;

public class Main {
    public static final Integer MAX_INT_VALUE_LIMIT = 256;
    public static Integer RAW_KEY_SIZE = 16;
    public static boolean isKeysEncrypted = false;

    /**/*from   w  w  w .j a  v a2 s  .c o  m*/
     * Generate rawKey as byte array of RAW_KEY_SIZE size
     *
     * @return rawKey
     */
    public static String generateKey() throws Exception {
        List<Integer> seed = new ArrayList<Integer>(MAX_INT_VALUE_LIMIT);
        byte[] key = new byte[RAW_KEY_SIZE];
        Random random = new Random();

        // make list of non repeated elements which can be converted to byte
        for (Integer i = 0; i < MAX_INT_VALUE_LIMIT; i++) {
            seed.add(i);
        }

        // randomly non-repeated choose element from non-repeated list;
        // RAW_KEY_SIZE cannot be bigger than MAX_INT_VALUE_LIMIT
        Integer seedSize = seed.size();
        for (int i = 0; i < RAW_KEY_SIZE; i++) {
            int index = random.nextInt(seedSize - i);
            key[i] = ((Integer) seed.toArray()[index]).byteValue();
            seed.remove(index);
        }
        if (isKeysEncrypted) {
            return encodeKey(getHexStringKey(key));
        }
        return getHexStringKey(key);
    }

    public static String encodeKey(String key) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(getCryptoStringKey(),
                "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] keyBytes = key.getBytes("UTF-8");
        return Base64.encodeToString(cipher.doFinal(keyBytes),
                Base64.DEFAULT);
    }

    /**
     * Method generates special HexString from key or use own mechanism to make key
     *
     * @param key rawKey that encode to Hex String, if not - method generate with own key
     * @return Special encoded Hex String
     */
    public static String getHexStringKey(byte[] key) {
        String result = "";
        for (int i = 0; i < RAW_KEY_SIZE; i++) {
            String hexInt = Integer.toHexString(key[i] + 128);
            if (hexInt.length() < 2) {
                hexInt = "0" + hexInt;
            }
            result = result + hexInt;
        }
        if (result.length() != RAW_KEY_SIZE * 2) {
            result = null;
        }
        return result;
    }

    private static byte[] getCryptoStringKey() {
        //  byte[] key = new byte[16];
        try {
            return ("d12Vp54R4sb0ymVF").getBytes("UTF-8");
        } catch (UnsupportedEncodingException x) {
            throw new RuntimeException(x);
        }
    }
}

Related Tutorials