Home » Core Java » crypto » Get bytes of generated symmetric key

About Ilias Tsagklis

Avatar photo
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

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



Key Length: 24
Keys Equal: true

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

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

Inline Feedbacks
View all comments