com.blackcrowsys.sinscrypto.AesKeyGenerator.java Source code

Java tutorial

Introduction

Here is the source code for com.blackcrowsys.sinscrypto.AesKeyGenerator.java

Source

/**
 * Black Crow Systems Limited.
 * 2014.
 * This code is released under GNU General Public License Version 3.
 * See LICENSE for full details of the license conditions.
 */
package com.blackcrowsys.sinscrypto;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

/**
 * @author ramindursingh
 *
 */
public class AesKeyGenerator implements KeyGenerator {

    private static final String ENCRYPTION = "AES";
    private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
    private static final int KEYLENGTH = 256;
    private static final int ITERATION = 65536;
    private static final int SALTSIZE = 8;
    private static final int IVSIZE = 16;

    /*
     * (non-Javadoc)
     *
     * @see com.blackcrowsys.sinscrypto.KeyGenerator#generateSalt()
     */
    @Override
    public String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[SALTSIZE];
        random.nextBytes(bytes);
        return Hex.encodeHexString(bytes);
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.blackcrowsys.sinscrypto.KeyGenerator#generateSecretKey(java.lang.
     * String, java.lang.String)
     */
    @Override
    public SecretKey generateSecretKey(String password, String salt)
            throws NoSuchAlgorithmException, InvalidKeySpecException, DecoderException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), Hex.decodeHex(salt.toCharArray()), ITERATION,
                KEYLENGTH);
        SecretKey key = factory.generateSecret(spec);
        return new SecretKeySpec(key.getEncoded(), ENCRYPTION);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.blackcrowsys.sinscrypto.KeyGenerator#generateIV()
     */
    @Override
    public String generateIV() {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[IVSIZE];
        random.nextBytes(bytes);
        return Hex.encodeHexString(bytes);
    }

}