Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

1. Overview

In this article, we’ll deep dive into the purpose of keys in AES or Ciphers in general. We’ll go over the best practices to keep in mind while generating one.

Finally, we’ll look at the various ways to generate one and weigh them against the guidelines.

2. AES

Advanced Encryption Standard (AES) is the successor of the Data Encryption Standard(DES), published in 2001 by the National Institute of Standards and Technology(NIST). It’s classified as a symmetric block cipher.

A symmetric cipher uses the same secret key for both encryption and decryption. A block cipher means it works on 128 bits blocks of the input Plaintext:

AES Key

2.1. AES Variants

Based on the key size, AES supports three variants: AES-128 (128 bits), AES-192 (192 bits), and AES-256 (256 bits). Increasing the key size increases the strength of encryption as a larger key size means the number of possible keys is larger. Consequently, the number of rounds to be performed during the execution of the algorithm increases as well and hence the compute required:

Key Size Block Size # Rounds
128 128 10
192 128 12
256 128 14

2.2. How Secure Is AES?

The AES algorithm is public information – it’s the AES key that is a secret and must be known to successfully decipher. So, it boils down to cracking the AES keys. Assuming the key is securely preserved, an attacker would have to try to guess the key.

Let’s see how the brute-force approach fares in guessing the key.

AES-128 keys are 128 bits, which means there are 2^128 possible values. It’d take a humongous and infeasible amount of time and money to search through this. Hence, AES is practically unbreakable by a brute-force approach.

There have been a few non-brute-force approaches but these could only reduce the possible key lookup space by a couple of bits.

All this means is that with zero knowledge about the key, AES is practically impossible to break.

3. Properties of a Good Key

Let’s now look at some of the important guidelines to follow while generating an AES key.

3.1. Key Size

Since AES supports three key sizes, we should choose the right key size for the use case. AES-128 is the most common choice in commercial applications. It offers a balance between security and speed. National Governments typically make use of AES-192 and AES-256 to have maximum security. We can use AES-256 if we want to have an extra level of security.

The quantum computers do pose a threat of being able to reduce the compute required for large keyspaces. Hence, having an AES-256 key would be more future-proof, although as of now, they’re out of the reach of any threat actors of commercial applications.

3.2. Entropy

Entropy refers to randomness in the key. If the generated key isn’t random enough and has some co-relation with being time-dependent, machine-dependent, or a dictionary word, for example, it becomes vulnerable. An attacker would be able to narrow down the key search space, robbing the strength of AES. Hence, it’s of utmost importance that the keys are truly random.

4. Generating AES Keys

Now, armed with the guidelines for generating an AES key, let’s see the various approaches to generating them.

For all the code snippets, we define our cipher as:

private static final String CIPHER = "AES";

4.1. Random

Let’s use the Random class in Java to generate the key:

private static Key getRandomKey(String cipher, int keySize) {
    byte[] randomKeyBytes = new byte[keySize / 8];
    Random random = new Random();
    random.nextBytes(randomKeyBytes);
    return new SecretKeySpec(randomKeyBytes, cipher);
}

We create a byte array of desired key size and fill it with random bytes obtained from random.nextBytes(). The random byte array is then used to create a SecretKeySpec.

The Java Random class is a Pseudo-Random Number Generator (PRNG), also known as Deterministic Random Number Generator (DRNG). This means it’s not truly random. The sequence of random numbers in a PRNG can be completely determined based on its seed. Java doesn’t recommend using Random for cryptographic applications.

With that said, NEVER use Random for generating keys.

4.2. SecureRandom

We’ll now use SecureRandom class in Java to generate the key:

private static Key getSecureRandomKey(String cipher, int keySize) {
    byte[] secureRandomKeyBytes = new byte[keySize / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(secureRandomKeyBytes);
    return new SecretKeySpec(secureRandomKeyBytes, cipher);
}

Similar to the previous example, we instantiate a byte array of the desired key size. Now, instead of using Random, we use SecureRandom to generate the random bytes for our byte array. SecureRandom is recommended by Java for generating a random number for cryptographic applications. It minimally complies with FIPS 140-2, Security Requirements for Cryptographic Modules.

Clearly, in Java, SecureRandom is the de-facto standard for obtaining randomness. But is it the best way to generate keys? Let’s move on to the next approach.

4.3. KeyGenerator

Next, let’s generate a key using the KeyGenerator class:

private static Key getKeyFromKeyGenerator(String cipher, int keySize) throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(cipher);
    keyGenerator.init(keySize);
    return keyGenerator.generateKey();
}

We get an instance of KeyGenerator for the cipher we’re working with. We then initialize the keyGenerator object with the desired keySize. Finally, we invoke the generateKey method to generate our secret key. So, how’s it different from the Random and SecureRandom approaches?

There are two crucial differences worth highlighting.

For one, neither the Random nor SecureRandom approach can tell whether we’re generating keys of the right sizes as per the Cipher specification. It’s only when we go for encryption that we’ll encounter exceptions if the keys are of an unsupported size.

Using SecureRandom with invalid keySize throws an exception when we initialize the cipher for encryption:

encrypt(plainText, getSecureRandomKey(CIPHER, 111));
java.security.InvalidKeyException: Invalid AES key length: 13 bytes
  at java.base/com.sun.crypto.provider.AESCrypt.init(AESCrypt.java:90)
  at java.base/com.sun.crypto.provider.GaloisCounterMode.init(GaloisCounterMode.java:321)
  at java.base/com.sun.crypto.provider.CipherCore.init(CipherCore.java:592)
  at java.base/com.sun.crypto.provider.CipherCore.init(CipherCore.java:470)
  at java.base/com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:322)
  at java.base/javax.crypto.Cipher.implInit(Cipher.java:867)
  at java.base/javax.crypto.Cipher.chooseProvider(Cipher.java:929)
  at java.base/javax.crypto.Cipher.init(Cipher.java:1299)
  at java.base/javax.crypto.Cipher.init(Cipher.java:1236)
  at com.baeldung.secretkey.Main.encrypt(Main.java:59)
  at com.baeldung.secretkey.Main.main(Main.java:51)

Using KeyGenerator, on the other hand, fails during key generation itself, allowing us to handle it more appropriately:

encrypt(plainText, getKeyFromKeyGenerator(CIPHER, 111));
java.security.InvalidParameterException: Wrong keysize: must be equal to 128, 192 or 256
  at java.base/com.sun.crypto.provider.AESKeyGenerator.engineInit(AESKeyGenerator.java:93)
  at java.base/javax.crypto.KeyGenerator.init(KeyGenerator.java:539)
  at java.base/javax.crypto.KeyGenerator.init(KeyGenerator.java:516)
  at com.baeldung.secretkey.Main.getKeyFromKeyGenerator(Main.java:89)
  at com.baeldung.secretkey.Main.main(Main.java:58)

The other key difference is the default use of SecureRandom. The KeyGenerator class is part of Java’s crypto package javax.crypto, which ensures the usage of SecureRandom for randomness. We can see the definition of the init method in the KeyGenerator class:

public final void init(int keysize) {
    init(keysize, JCAUtil.getSecureRandom());
}

Hence, using a KeyGenerator as a practice ensures we never use a Random class object for key generation.

4.4. Password-Based Key

So far, we’ve been generating keys from random and not-so-human-friendly byte arrays. Password-Based Key (PBK) offers us the ability to generate a SecretKey based on a human-readable password:

private static Key getPasswordBasedKey(String cipher, int keySize, char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] salt = new byte[100];
    SecureRandom random = new SecureRandom();
    random.nextBytes(salt);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password, salt, 1000, keySize);
    SecretKey pbeKey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(pbeKeySpec);
    return new SecretKeySpec(pbeKey.getEncoded(), cipher);
}

We’ve got quite a few things going on here. Let’s break it down.

We start with our human-readable password. This is a secret and must be protected. The password guidelines must be followed, such as a minimum length of 8 characters, the use of special characters, the combination of uppercase and lowercase letters, digits, and so on. Additionally, OWASP guidelines suggest checking against already exposed passwords.

A user-friendly password doesn’t have enough entropy. Hence, we add additional randomly generated bytes called a salt to make it harder to guess. The minimum salt length should be 128 bits. We used SecureRandom to generate our salt. The salt isn’t a secret and is stored as plaintext. We should generate salt in pairs with each password and not use the same salt globally. This’ll protect from Rainbow Table attacks, which use lookups from a precomputed hash table for cracking the passwords.

The iteration count is the number of times the secret generation algorithm applies the transformation function. It should be as large as feasible. The minimum recommended iteration count is 1,000. A higher iteration count increases the complexity for the attacker while performing a brute-force check for all possible passwords.

The key size is the same we discussed earlier, which can be 128, 192, or 256 for AES.

We’ve wrapped all the four elements discussed above into a PBEKeySpec object. Next, using the SecretKeyFactory, we get an instance of PBKDF2WithHmacSHA256 algorithm to generate the key.

Finally, invoking generateSecret with the PBEKeySpec, we generate a SecretKey based on a human-readable password.

5. Conclusion

There are two primary bases for generating a key. It could be a random key or a key based on a human-readable password. We’ve discussed three approaches to generating a random key. Among them, KeyGenerator provides true randomness and also offers checks and balances. Hence, KeyGenerator is a better option.

For a key based on a human-readable password, we can use SecretKeyFactory along with a salt generated using SecureRandom and high iteration count.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments