Data Encryption

Hello everyone, for today’s blog post I will go over one of the ways to protect your data as a developer. We will talk about data encryption. Essentially data encryption is when you alter your data based on specific key, and in order the change the data back to it’s initial state you use the same key that was used to encrypt the data to decrypt it. Alright so now that we went over what encryption is let’s get started on showing on to implement it.

So for this tutorial we will be using JAVA 8 to implement as we will be using some of the security and encryption based API’s that JAVA offers. This mini program will just take a message and encrypt it then decrypt it, let us begin.


Step 1: Create a new java class and import the following package members

These imported package members will be required to create our program.

import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;

Step 2: Create a few global variables

This step we will create some global variables that we will used in multiple methods throughout the program.

byte[] key = new byte[1000];
String keyString;
byte[] raw;

Step 3: Generate a Symmetric Key

For this step we will create a method to accomplish the task of generating a symmetric key to encrypt and decrypt our message.

public void generateKey()
{
try
{
Random rand = new Random();
int num = rand.nextInt(10000);
String keyNum = String.valueOf(num);
byte[] keyNumber = keyNum.getBytes();
key = getRawKey(keyNumber);
keyString = new String(key);
}
catch(Exception e)
{
System.out.println(e);
}
}

so this method will generate a random number from 0 to 9999. Using this generated number it will be convert it into a byte array. Once converted it will call another method that we will implement in step 4 called getRawKey() and the returned value will be our key. Finally we will store the string version of the key.

Step 4: Getting the raw key

We will now create the method getRawKey() called in the previous step.

private byte[] getRawKey(byte[] seed) throws Exception 
{
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(seed);
keyGen.init(128, sr);
SecretKey skey = keyGen.generateKey();
raw = skey.getEncoded();
return raw;
}

In detail the key generator we set to AES will generate AES keys, AES is a type of encryption which stands for Advanced Encryption Standard. Also a SecureRandom object will be used to get the given seed from the parameter of the method to help generate the key. A SecretKey object will be created from the key generator, also the raw key will be the encoded version of the SecretKey.

Step 5: Encrypt method

Now that we have implemented the methods to generate the key for encryption we can now start the implementation of encrypting the data.

private String encrypt(byte[] key, byte[] input) throws Exception 
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(input);
return new String(encrypted);
}

The Cipher object is the object that will encrypt the data using the key. The SecretKeySpec recreates a SecretKey from the byte array version of the key. Using the Cipher in ENCRYPT_MODE will make it so then the input will be encrypted

Step 6: Decrypt method

Now that we have the encrypt method its time to implement the decrypt method.

private String decrypt(byte[] key, byte[] input) throws Exception 
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(input);
return new String(decrypted);
}

This method is similar to to the encrypt method the only real difference is that the Cipher object is set to DECRYPT_MODE which will decrypt the input instead of encrypting it.

Step 7: Tying it all together

Okay so now all the methods are implemented now it is time to use them together to encrypt a message. For this tutorial we will just use a basic main method to a constructor.

public EncryptDecrypt() 
{
try
{
generateKey();
   inputMessage=JOptionPane.showInputDialog(null,"Enter message to encrypt");
byte[] ibyte = inputMessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);
String encryptedData = new String(ebyte);
System.out.println("Encrypted message "+encryptedData);
JOptionPane.showMessageDialog(null,"Encrypted Data "+"\n"+encryptedData);
byte[] dbyte= decrypt(raw,ebyte);
String decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);
JOptionPane.showMessageDialog(null,"Decrypted Data "+"\n"+decryptedMessage);
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[]) 
{
EncryptDecrypt run = new EncryptDecrypt();
}

Now the program should be finished, also I will put the full program code below.

import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;
public class EncryptDecrypt
{
byte[] key = new byte[1000];
String keyString;
byte[] raw;
 public EncryptDecrypt() 
{
try
{
generateKey();
inputMessage=JOptionPane.showInputDialog(null,"Enter message to encrypt");
byte[] ibyte = inputMessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);
String encryptedData = new String(ebyte);
System.out.println("Encrypted message "+encryptedData);
JOptionPane.showMessageDialog(null,"Encrypted Data "+"\n"+encryptedData);
byte[] dbyte= decrypt(raw,ebyte);
String decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);
JOptionPane.showMessageDialog(null,"Decrypted Data "+"\n"+decryptedMessage);
}
catch(Exception e)
{
System.out.println(e);
}
}
 public void generateKey() 
{
try
{
Random rand = new Random();
int num = rand.nextInt(10000);
String keyNum = String.valueOf(num);
byte[] keyNumber = keyNum.getBytes();
key = getRawKey(keyNumber);
keyString = new String(key);
}
catch(Exception e)
{
System.out.println(e);
}
}
 private byte[] getRawKey(byte[] seed) throws Exception 
{
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(seed);
keyGen.init(128, secureRandom);
SecretKey skey = keyGen.generateKey();
raw = skey.getEncoded();
return raw;
}

private String encrypt(byte[] key, byte[] input) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(input);
return new String(encrypted);
}
 private String decrypt(byte[] key, byte[] input) throws Exception 
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(input);
return new String(decrypted);
}
 public static void main(String args[]) 
{
EncryptDecrypt run = new EncryptDecrypt();
}
}

This is the end of this blog post and also the last one revolving the topic of data security. My next couple of blog posts in the future will be about data analytics.

Show your support

Clapping shows how much you appreciated Markus Salvador’s story.