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);
 }
}

R : load : Reload the data saved with function save

“load” function reload datasets written with the function save.

Synatx
load(file, envir = parent.frame(), verbose = FALSE)

Parameter
Description
file
File to reload
envir
Environment where data should be loaded
verbose
If verbose is TRUE, then item names are printed while loading, else not.


> x <- 1:50
> y <- list(a = 1, b = TRUE, c = "oops")
> save(x, y, file = "xy.RData")
> 
> x<-10
> y<-20
> 
> x
[1] 10
> y
[1] 20
> 
> data <- load("xy.RData")
> data
[1] "x" "y"
> 
> x
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
> y
$a
[1] 1

$b
[1] TRUE

$c
[1] "oops"


Prevoius                                                 Next                                                 Home

Friday, 3 July 2015

Convert String to secret key in Java

Step 1: Decodes a Base64 encoded String into a byte array.
byte[] decodedKey = Base64.getDecoder().decode(keyStr);
                 
Step 2: Construct secret key from the given byte array.
SecretKey secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");

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

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class SecretKeyGen {

 public static SecretKey generateSecretKey() {
  KeyGenerator keyGen = null;
  try {
   /*
    * Get KeyGenerator object that generates secret keys for the
    * specified algorithm.
    */
   keyGen = KeyGenerator.getInstance("AES");
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }

  /* Initializes this key generator for key size to 256. */
  keyGen.init(256);

  /* Generates a secret key */
  SecretKey secretKey = keyGen.generateKey();

  return secretKey;
 }

 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;
 }

 public static SecretKey decodeKeyFromString(String keyStr) {
  /* Decodes a Base64 encoded String into a byte array */
  byte[] decodedKey = Base64.getDecoder().decode(keyStr);

  /* Constructs a secret key from the given byte array */
  SecretKey secretKey = new SecretKeySpec(decodedKey, 0,
    decodedKey.length, "AES");

  return secretKey;
 }

 public static void main(String args[]) {
  SecretKey secretKey = generateSecretKey();
  String keyStr = keyToString(secretKey);
  SecretKey key = decodeKeyFromString(keyStr);

  System.out.println(keyStr);
  System.out.println(keyToString(key));

 }
}



Convert secret key into String in Java

Step 1: Get secret key in encoding format.
byte encoded[] = secretKey.getEncoded();

Step 2: Use following statement, to conver encoded byte array into string using Base64 encoding scheme.
String encodedKey = Base64.getEncoder().encodeToString(encoded);

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

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

public class SecretKeyGen {

 public static SecretKey generateSecretKey() {
  KeyGenerator keyGen = null;
  try {
   /*
    * Get KeyGenerator object that generates secret keys for the
    * specified algorithm.
    */
   keyGen = KeyGenerator.getInstance("AES");
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }

  /* Initializes this key generator for key size to 256. */
  keyGen.init(256);

  /* Generates a secret key */
  SecretKey secretKey = keyGen.generateKey();

  return secretKey;
 }

 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;
 }

 public static void main(String args[]) {
  SecretKey secretKey = generateSecretKey();
  System.out.println(keyToString(secretKey));
 }
}



Generate secret AES key in Java

Step 1: Get KeyGenerator object that generates secret keys for AES.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");

Step 2: Initialize key generator to specific key size.
keyGen.init(256);

Step 3: Generate a secret key.
SecretKey secretKey = keyGen.generateKey();

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

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

public class SecretKeyGen {

 public static SecretKey generateSecretKey() {
  KeyGenerator keyGen = null;
  try {
   /*
    * Get KeyGenerator object that generates secret keys for the
    * specified algorithm.
    */
   keyGen = KeyGenerator.getInstance("AES");
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }

  /* Initializes this key generator for key size to 256. */
  keyGen.init(256);

  /* Generates a secret key */
  SecretKey secretKey = keyGen.generateKey();

  return secretKey;
 }

 public static void main(String args[]) {
  SecretKey secretKey = generateSecretKey();
  String encodedKey = Base64.getEncoder().encodeToString(
    secretKey.getEncoded());
  System.out.println(encodedKey);
 }
}



Extract private, public key from keystore

In this post I am going to explain, how to extract public and private keys from keystore.

Step 1: generate jks file. Go through following post to generate jks file.

Step 2: Use following program to extract public and private keys form keystone.

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;

public class ExtractKeyPair {

 public static KeyPair getKeyPair(String jksFile) throws Exception {
  FileInputStream is = new FileInputStream(jksFile);

  KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
  keystore.load(is, "password123".toCharArray());

  String alias = "certificate1";

  KeyPair pair = null;

  Key key = keystore.getKey(alias, "password123".toCharArray());
  if (key instanceof PrivateKey) {
   /* Get certificate of public key */
   Certificate cert = keystore.getCertificate(alias);

   /* Get public key */
   PublicKey publicKey = cert.getPublicKey();

   /* Construct KeyPair object */
   pair = new KeyPair(publicKey, (PrivateKey) key);

  }
  return pair;

 }

 public static void main(String[] argv) throws Exception {
  KeyPair keyPair = getKeyPair("/Users/harikrishna_gurram/keystore.jks");

  PrivateKey priKey = keyPair.getPrivate();
  PublicKey pubKey = keyPair.getPublic();

  byte data[] = priKey.getEncoded();
  for (byte b : data) {
   System.out.print(b);
  }

  System.out.println();
  data = pubKey.getEncoded();
  for (byte b : data) {
   System.out.print(b);
  }
 }
}

"/Users/harikrishna_gurram/keystore.jks" represents jks file, where certificate resides.

keystore.load(is, "password123".toCharArray());
Above statement loads keystore.

keystore.getKey(alias, "password123".toCharArray())
Above statement returns key associate with given certificate.