Java String Encryption
Java Security
Encrypting Data in Java
Java Programming
Encryption Techniques

How to encrypt String in Java

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Encryption is a fundamental aspect of securing data in modern applications. Java, being one of the most popular programming languages, offers robust support for encryption through its built-in libraries. This article provides a comprehensive guide on how to encrypt strings in Java using various cryptographic libraries.

Encryption Overview

Before diving into the technical aspects of string encryption in Java, it's important to understand a few basic concepts:

  • Encryption: The process of transforming plain text data into a format known as ciphertext, which is unreadable without the proper decryption key.
  • Symmetric Encryption: Uses the same key for both encryption and decryption. It is faster but requires the secure management of the keys.
  • Asymmetric Encryption: Uses a pair of keys, a public key for encryption and a private key for decryption. It offers higher security at the cost of performance.
  • Algorithms: Common algorithms include AES (Advanced Encryption Standard) for symmetric encryption and RSA (Rivest-Shamir-Adleman) for asymmetric encryption.

Prerequisites

Make sure you have the Java Development Kit (JDK) installed on your system. We'll use JDK 8 or newer for our examples.

Using Java's Crypto Library

Java provides the javax.crypto package, with classes designed for encryption and decryption tasks.

Symmetric Encryption Example with AES

Below is an example using AES for symmetric encryption:

java
1import javax.crypto.Cipher;
2import javax.crypto.KeyGenerator;
3import javax.crypto.SecretKey;
4import javax.crypto.spec.SecretKeySpec;
5import java.util.Base64;
6
7public class AESSymmetricEncryptionExample {
8
9    public static void main(String[] args) throws Exception {
10        // Create a key generator for AES algorithm
11        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
12        keyGen.init(128);  // Set key size (128, 192, or 256)
13
14        // Generate a secret key
15        SecretKey secretKey = keyGen.generateKey();
16
17        // Transform the key into a byte array
18        byte[] rawKey = secretKey.getEncoded();
19
20        // Create a secret key from the byte array
21        SecretKeySpec keySpec = new SecretKeySpec(rawKey, "AES");
22
23        // Encrypt
24        Cipher cipher = Cipher.getInstance("AES");
25        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
26        
27        String plainText = "Hello, World!";
28        byte[] encryptedText = cipher.doFinal(plainText.getBytes());
29
30        // Encode the byte array to a base64 string for easy handling
31        String encodedText = Base64.getEncoder().encodeToString(encryptedText);
32        System.out.println("Encrypted Text: " + encodedText);
33
34        // Decrypt
35        cipher.init(Cipher.DECRYPT_MODE, keySpec);
36        byte[] decryptedText = cipher.doFinal(Base64.getDecoder().decode(encodedText));
37        System.out.println("Decrypted Text: " + new String(decryptedText));
38    }
39}

Asymmetric Encryption Example with RSA

For stronger encryption, consider RSA, which involves public and private key pairs:

java
1import javax.crypto.Cipher;
2import java.security.*;
3
4public class RSAAsymmetricEncryptionExample {
5
6    public static void main(String[] args) throws Exception {
7        // Generate key pair
8        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
9        keyGen.initialize(2048);
10        KeyPair keyPair = keyGen.generateKeyPair();
11
12        PublicKey publicKey = keyPair.getPublic();
13        PrivateKey privateKey = keyPair.getPrivate();
14
15        // Encrypt
16        Cipher cipher = Cipher.getInstance("RSA");
17        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
18        
19        String plainText = "Hello, World!";
20        byte[] encryptedText = cipher.doFinal(plainText.getBytes());
21        System.out.println("Encrypted Text: " + Base64.getEncoder().encodeToString(encryptedText));
22
23        // Decrypt
24        cipher.init(Cipher.DECRYPT_MODE, privateKey);
25        byte[] decryptedText = cipher.doFinal(encryptedText);
26        System.out.println("Decrypted Text: " + new String(decryptedText));
27    }
28}

Key Points Summary

Here's a table summarizing key points related to Java string encryption:

AspectSymmetric EncryptionAsymmetric Encryption
SpeedFastSlower
Key ManagementSingle key shares for both operationsPublic & Private keys need to be paired
Use CasesEncrypting large amounts of dataSecure key exchanges and short messages
Example AlgorithmAESRSA
Security LevelSecure with key management precautionsHighly secure

Additional Considerations

  • Block Modes and Padding: For AES, different modes (such as CBC) and padding schemes may affect data security. For most use cases, the default settings are sufficient.
  • Key Length: The longer the key, the more secure the encryption. Ensure compliance with any applicable security standards.
  • Handling Exceptions: Always handle exceptions like NoSuchAlgorithmException and InvalidKeyException to make your encryption robust.

Conclusion

Encrypting strings in Java can be efficiently handled using Java's cryptography libraries. By choosing the right encryption algorithm and managing keys securely, you can safeguard sensitive data in your applications. Always stay updated with the latest security practices to ensure your encryption strategy remains effective.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.