Published in


How to Encrypt and Decrypt Data In Java

Using AES encryption to encrypt secret data

Photo by Markus Spiske on Unsplash

Originally Published in


  • Encryption and Decryption of Secret data is very common process in building any kind of application.
  • We often need to encrypt some kind of secret data/config value such as db-password, hashing token etc.
  • We can encrypt our data either using symmetric or asymmetric encryption. Usually when we talk about symmetric encryption algorithm we use AES and RSA for asymmetric encryption. In Some cases we also use hybrid approach.
  • AES is faster and can encrypt large data sizes while RSA is suitable for encrypting smaller data sizes.
  • This article mainly discusses about Symmetric encryption with AES.

BouncyCastle Dependency

  • BouncyCastle is a great and popular library that supports all the necessary features that we need to encrypt and decrypt the data.
  • You can get latest version from here.

Encrypt Data

  • Secret Key is something that we would need to protect our input byte array. so that only someone who has access to this secret key can decrypt it. Secret key can be of 128 bits, 192 bits or 256 bits , we are using 192 bits here.
  • But what is IvParameterSpec ? IV stands for Initialization Vector, which is kind of random bytes that introduces randomness in the input bytes to avoid detecting pattern. It is used by AES in CBC mode. AES encryption can be done in 5 modes.
  • Now let’s execute client code to run encryption process.
  • As we can see in the output , our data is not readable at all.
  • Now let’s decrypt and make sure we get our input data back.

Decrypt Data

  • First and foremost lets write decrypt method , it might look like similar to encrypt method but there are some differences.
  • Of course we have to pass same secret key and iv vector that we used for encryption. Other than that we again use Cipher object of AES algorithm with CBC mode and PKCS5 padding.
  • As we can see in we can read our original text back and decryption process is successful.

Entire Code

  • Below is the entire code that we used for demonstration above.


  • In this article we discuss how we can encrypt and decrypt sensitive data by using AES encryption which is symmetric encryption algorithm.
  • We saw that Bouncy Castle library indeed very helpful in achieving our goal.
  • We can extend this idea to encrypt and decrypt entire file as next step which we will cover in upcoming blogs.

Follow me on Medium & LinkedIn
More blogs @



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suraj Mishra

Suraj Mishra

Google Cloud Certified Professional Data Engineer | Backend Engineering @ Rakuten Card | Blogs @