Friday 3 July 2015

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



1 comment:

  1. There are a lot of good stuff here. You should consider write a book like "[Language] cookbook recipes".

    ReplyDelete