Member-only story
How to Encrypt and Decrypt Data In Java
Using AES encryption to encrypt secret data
Published in
3 min readSep 19, 2022
Originally Published in asyncq.com
Introduction
- 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
- 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.