generate AES Master Key - Android java.security

Android examples for java.security:AES

Description

generate AES Master Key

Demo Code

/* $Id: CryptoHelper.java 81 2009-01-01 03:22:36Z rmceoin $
 * /* w  ww  .j av a 2s  .  c o  m*/
 * Copyright 2007-2008 Steven Osborn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import android.util.Log;

public class Main {
    private static String TAG = "CryptoHelper";

    /**
     * @author Isaac Potoczny-Jones
     * 
     * @return null if failure, otherwise hex string version of key
     */
    public static String generateMasterKey() {
        try {
            KeyGenerator keygen;
            keygen = KeyGenerator.getInstance("AES");
            keygen.init(256);
            SecretKey genDesKey = keygen.generateKey();
            return toHexString(genDesKey.getEncoded());
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "generateMasterKey(): " + e.toString());
        }
        return null; //error case.
    }

    /**
     * 
     * @param bytes
     * @return
     */
    public static String toHexString(byte bytes[]) {

        StringBuffer retString = new StringBuffer();
        for (int i = 0; i < bytes.length; ++i) {
            retString.append(Integer.toHexString(
                    0x0100 + (bytes[i] & 0x00FF)).substring(1));
        }
        return retString.toString();
    }
}

Related Tutorials