How to Encrypt and Decrypt Data In Java
Using AES encryption to encrypt secret data
Originally Published in asyncq.com
- 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 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.
- Let’s use this library to encrypt byte array which we passed as argument. We have also passed Secret Key and IvParameterSpec.
- Our Cipher is using AES in CBC mode with PKC padding.
- 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.
- 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.
- 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.