Saturday 4 July 2015

Generating secret keys in Java

In secure data communications, data is encrypted using a key, to provide confidentiality. There are two types of encryptions.

a.   Symmetric key encryption
b.   Public key encryption

a. Symmetric key Encryption
In Symmetric key encryption, data is encrypted and decrypted using same key, called secret key.

b. Public key encryption
It is also known as asymmetric key encryption. It uses two keys.
1.   Public key
2.   Private key
Every one knows public key, but only recipient knows private key. Suppose A wants to send a message M to B, then A encrypts M with B’s public key and send. At recipient end B decrypts message with his private key.

Each approach has their own advantages and disadvantages.

1.   Symmetric key encryption is easy to implement and faster. But main problem is both parties (sender and receiver) must exchange the key in secure way.
2.   Public key encryption works slow, but solves key exchange problem. In real world both the approaches combined to achieve more security and performance (See HTTPS).

In this post, I am going to explain how to generate Secret key.

“javax.crypto.KeyGenerator” class is used to generate secret key. KeyGenerator class provide “getInstance” method, which takes algorithm name as argument and generate secret key specific to the algorithm supplied.

Following are the algorithms that java provides.
Algorithm Name
Description
Returns Key generator for use with the AES algorithm.
Returns Key generator for use with the ARCFOUR (RC4) algorithm.
Returns Key generator for use with the Blowfish algorithm.
Returns Key generator for use with the DES algorithm.
Returns Key generator for use with the DESede (triple-DES) algorithm.
Returns Key generator for use with the HmacMD5 algorithm.
HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512
Returns Keys generator for use with the various flavors of the HmacSHA algorithms.

Returns Key generator for use with the RC2 algorithm.

KeyGenerator class provides 3 forms of getInstance method.
getInstance(String algorithm)
getInstance(String algorithm, Provider provider)
getInstance(String algorithm, String provider)

First method returns KeyGenerator instance for specific algorithm mentioned in above table. Second and 3rd methods returns a new KeyGenerator object encapsulating the KeyGeneratorSpi implementation from the specified Provider object.

Once you got the instance of KeyGenerator, you can initialize KeyGenerator with specified parameter set. There are two ways to initialize KeyGenerator.

a. Algorithm-Independent initialization
Following methods are used to initialize KeyGenerator to initialize in Algorithm independent manner.
init(int keysize)
init(SecureRandom random)
init(int keysize, SecureRandom random)

First method initializes this key generator for a certain keysize. Second method initialize KeyGenerator using a user-provided source of randomness. Third method is combination of first and second.

b. Algorithm specific initialization
Following methods are used to initialize KeyGenerator to initialize in Algorithm specific manner.
init(AlgorithmParameterSpec params)
init(AlgorithmParameterSpec params, SecureRandom random)
First method initializes this key generator with the specified parameter set. Second method initializes this key generator with the specified parameter set and a user-provided source of randomness.

import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecretKeyUtil {
 public static SecretKey getSecretKey(String algorithm) {
  KeyGenerator keyGenerator = null;
  try {
   keyGenerator = KeyGenerator.getInstance(algorithm);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  return keyGenerator.generateKey();
 }

 public static String keyToString(SecretKey secretKey) {
  /* Get key in encoding format */
  byte encoded[] = secretKey.getEncoded();

  /*
   * Encodes the specified byte array into a String using Base64 encoding
   * scheme
   */
  String encodedKey = Base64.getEncoder().encodeToString(encoded);

  return encodedKey;
 }
}


import javax.crypto.SecretKey;

public class Main {
 public static void main(String args[]) {
  SecretKey secretKey = SecretKeyUtil.getSecretKey("AES");
  String str = SecretKeyUtil.keyToString(secretKey);

  System.out.println(str);
 }
}

No comments:

Post a Comment