crypto

Get bytes of generated symmetric key

In this example we shall show you how to get the bytes of a generated symmetric key.
To get the bytes of a generated symmetric key one should perform the following steps:

  • Create a new KeyGenerator for the DESede algorithm.
  • Generate a SecretKey, using generateKey() API method of KeyGenerator.
  • Use getEncoded() API method of SecretKey, to get a byte array that is the key in its primary encoding format.
  • Construct a new SecretKey, using a SecretKeySpec from the given byte array and using the same algorithm. The new key is equal to the initial key.

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.security.NoSuchAlgorithmException;

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

public class GetBytesOfGeneratedSymmetricKey {
	
	public static void main(String[] args) {
		
		try {
			
			String algorithm = "DESede";
			
			// create a key generator
		    KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);
		    
		    // generate a key
		    SecretKey key = keyGen.generateKey();

		    // get the raw key bytes
		    byte[] keyBytes = key.getEncoded();
		    
		    System.out.println("Key Length: " + keyBytes.length);

		    // construct a secret key from the given byte array
		    SecretKey keyFromBytes = new SecretKeySpec(keyBytes, algorithm);
		    
		   	System.out.println("Keys Equal: " + key.equals(keyFromBytes));
			
		}
		catch (NoSuchAlgorithmException e) {
			System.out.println("No Such Algorithm:" + e.getMessage());
			return;
		}
		
	}

}

Output:

Key Length: 24
Keys Equal: true

 
This was an example of how to get the bytes of a generated symmetric key in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button