Java: Simple AES Encryption Working Example

Post Visual Studio nowadays I am developing more dynamic web applications on Java. So again having a requirement to store passwords securely. After long research found the following piece of code which can be used to encrypt/decrypt secure data using random hash value (private key). This code uses Advanced Encryption Standards (AES) which is the symmetric algorithm.

The code uses basic java security jars and doesnt need any thirdparty base64 jar for encoding and decoding passwords.


AES Class 


import java.util.Arrays;
import java.util.Base64;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESEcryption {

private static byte[] key;
private static SecretKeySpec secretKeySpec;

 

public static void setKey(String inputKeyValue)
{
MessageDigest sha = null;
try {
key = inputKeyValue.getBytes(“UTF-8”);
sha = MessageDigest.getInstance(“SHA-1”);
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKeySpec = new SecretKeySpec(key, “AES”);
}
catch (Exception e) {
e.printStackTrace();
}

}

public static String encrypt(String strToEncrypt, String secretKeyValue)
{
try
{
setKey(secretKeyValue);
Cipher cipher = Cipher.getInstance(“AES/ECB/PKCS5Padding”);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(“UTF-8”)));
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}

public static String decrypt(String strToDecrypt, String secretKeyValue)
{
try
{
setKey(secretKeyValue);
Cipher cipher = Cipher.getInstance(“AES/ECB/PKCS5Padding”);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}


Main Class for testing code


public static void main(String[] args)
{
           // private key
    final String privateKeyVal = "abcdEFGHijklmnOPqrstuvwxyz";
    
    String originalText = "thisisMainText";
    String encryptedData =AESEcryption.encrypt(originalText,privateKeyVal) ;
    String decryptedData =AESEcryption.decrypt(encryptedData,privateKeyVal) ;
    
            // printing all variable data
    System.out.println(originalText);
    System.out.println(encryptedData);
    System.out.println(decryptedData);
}

 

In the above example, longer private Key value gives better-encrypted text. Also, don’t forget to keep private key value isolated. This can be achieved by storing the private key into the read-only file on server-side which is having access to the application user only.
Thanks.
Advertisements

Digital Security: Understanding Ransomware

The word ransom was linked to the kidnapping 10 years back mainly for the purpose of gaining the big chunk of money. But today the equations have changed as it is not limited to the human being. Even with the computers early years, the common destructive approach is virus infection destroying important data and information.

Personal data and information are very important and valuable piece of information and moving toward digital technologies we are becoming more dependent on this information. This can contain pictures, videos, banking/financial information, passwords, certificates and much more. Nowadays cyber criminals have come up with the new approach of ransomware tools which people downloads and unknowingly executes results in encrypting all personal information. Most of the times these files looks like some important update files, pdf documents and sometimes just simple HTML page and Windows machines are most popular targets for these ransomware tools. We have almost 90% of these built for only windows environments.

Ransomware tools mainly come  in 2 categories:

Nondestructive: – this ransomware does not destroy or encrypt your personal information, but creates an impression that your personal information is affected with the virus and needs advance cleanup. Most of the times this is achieved with popups/big screensavers telling end user to contact some number and then requesting remote access or money for data cleanup. One the example of such message is shown below.

hoax-police-warning-big

Destructive: – these are the once which are dangerous and can encrypt all data present on your machines in seconds of execution. Most of the times after execution of such files gives immediate error creating an impression that nothing has happened. But within seconds after that we get the message on the screen telling all your personal information is now encrypted and the only way to recover this information is by paying portions of bitcoins which is equivalent to 100/300 dollars. And yes this message comes with the deadline clock which ranges from 1 to 4 days. One of such example is shown below. Most of such ransomware are still not having any decryption solution unless paying money to the owner of ransomware.

ctb-locker

How can we save our information from Ransomware then ?

  • Always keep one or multiple backups of your critical personal information, pictures and other files.
  • Do not open any emails or attachments which you are not expected to receive. Free lottery/iPhone emails are 100% hoax. None of the company is that rich to give away his money or gadgets for free. So if we receive any emails with attachments that we are not expecting, just better to delete them.
  • Always update anti-virus software. Still most of the antivirus unable to give 100% protection against all ransomware, so better not to run any unknown attachment on the computer.
  • Finally – if we still left with some curiosity to find what is inside in the attachment/document we downloaded/received. First open https://www.virustotal.com/ website. This will show below the screen. You can upload your file to this website first and scan to find ransomware score. This website runs your file against most of the antivirus software available and provides you ransomware score.

virtustotal1virustotal

If results showing all green then that file is safe to execute. If we get at least one hit from any antivirus then better not to run that file.

In summary, it’s individual’s responsibility to protect his/her personal information. Always take backup, strong passwords and never open any unknown file on your machine which could leave you in regret afterward. 

THANK YOU.


Digital India : Can anyone read data from formatted memory card / phone ?

The reason for this post tagging against digital India is because smartphones, memory cards or pen drive usage is very high due to the population and digital exposure. Also, sale and usage of used phones is equally high compare to the new devices. Taking photos/videos is one of the prime use of our mobile phone nowadays and sometimes people do store very much personal photos/clips on their device. Later people delete all these information assuming that no one else can access during resell.

But does that really remove information from the memory card? NO – the way delete or format process works is just clearing mapping of that information. Means marking that space as free so that device software can rewrite the data on that location. So if the location is not reused after format/delete then anyone can easily recover this information.

On the internet, there are many software available which can help any novice person to recover information from the memory card/ hard drive. These generally come at the very much nominal price or some of them are free to use with easy steps. This software looks for the raw data on the card and joins them together like solving some jigsaw puzzle.

Does that mean we should not be storing sensitive information on the memory cards or other storage? Ideally Yes – but if we cannot resist then it’s better to store all such information in the separate memory card attached to the device. During resell we can just sell the device without the memory card or just destroy memory card. As memory cards are not very costly so should not be affecting your device’s reselling value.

Another way is to format your device then store some junk information ensuring all storage is used and format again. Doing this activity 2/3 times will ensure that original set of information is completely overwritten.

In a summary its individual’s responsibility to protect his/her personal data and how far he/she is going with respect to sharing personal information. All the best and happy new year.

Digital India : Is Google Tracking Your Andriod Phone ?

Today most of the mobile companies use Andriod as an operating system. The reason behind this that it is open source, user-friendly, robust, stables and saves the good amount of time in investment on building new OS from scratch. Any Andriod based phone provides a large number of apps via google app store. When individual signs into app store we also authorize access to the Gmail, calendars, and other google services by default. One of the hidden services is google location history. This tracks your location and stores on your Gmail location data. Those who have Android phones can search for “google location history”  and view their past location data date by date.

The functionality is very much effective with respect to tracking your device, but we can switch off location tracking if we want by going on to the below link

https://www.google.co.uk/maps/timeline

We can also delete historic data. More information on how to do it can be found on the below link

https://support.google.com/accounts/answer/3118687?source=gsearch&hl=en

The purpose of this post is just to provide more knowledge about the hidden features of the smartphones.

Digital India : Twitter Accounts hacking

Last month there was big noise for some of the known journalist’s twitter account getting hacked. After this, some people including victims started blaming the government for the same. Does that mean ruling government failed to implement digital India?

First twitter is private firm independent from any government and has its own strong security policies otherwise, hackers could have hacked every other account from twitter. Therefore its individual’s responsibility to secure own account information from hackers.

So what could be the reasons then? Sometimes by clicking unwanted links for free goodies, discounts, WhatsApp forwards, lottery winnings and more we authorize access to the personal information to unwanted peoples. Also, most of the people tend to write passwords physically on the notes. And most common typing passwords in presence of others or personally giving passwords details 🙂

Most the above reasons are very common but very much important, therefore its individual’s choice how much personal data he/she sharing knowing/unknowingly over the internet.