Java String Encryption Decryption Example

In this tutorial, we will see how to use AES(Advanced Encryption Standard) algorithm to string or text in Java with an example.
Java support many secure encryption algorithms but some of them are weak to be used in security-intensive applications. For example, the Data Encryption Standard (DES) encryption algorithm is considered highly insecure; messages encrypted using DES have been decrypted by brute force within a single day by machines such as the Electronic Frontier Foundation’s (EFF) Deep Crack.
A more secure encryption algorithm is AES – Advanced Encryption Standard which is a symmetric encryption algorithm. AES encryption is used by the U.S. for securing sensitive but unclassified material, so we can say it is enough to secure.

Java String Encryption Decryption Example

Here is the complete Java program to encrypt and decrypt string or text in Java:
package net.javaguides.examples.security;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Java String Encryption Decryption Example
 * @author Ramesh Fadatare
 *
 */
public class AESEncryptionDecryption {
    private static SecretKeySpec secretKey;
    private static byte[] key;
    private static final String ALGORITHM = "AES";

    public void prepareSecreteKey(String myKey) {
        MessageDigest sha = null;
        try {
            key = myKey.getBytes(StandardCharsets.UTF_8);
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);
            secretKey = new SecretKeySpec(key, ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public String encrypt(String strToEncrypt, String secret) {
        try {
            prepareSecreteKey(secret);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        } catch (Exception e) {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

    public String decrypt(String strToDecrypt, String secret) {
        try {
            prepareSecreteKey(secret);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        } catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }

    public static void main(String[] args) {
        final String secretKey = "secrete";

        String originalString = "javaguides";

        AESEncryptionDecryption aesEncryptionDecryption = new AESEncryptionDecryption();
        String encryptedString = aesEncryptionDecryption.encrypt(originalString, secretKey);
        String decryptedString = aesEncryptionDecryption.decrypt(encryptedString, secretKey);

        System.out.println(originalString);
        System.out.println(encryptedString);
        System.out.println(decryptedString);
    }
}
Output:
javaguides
KGBmBZKY27xOHrL5t+LYAQ==
javaguides
Let's understand the above Java program.
To encrypt the string with a key, use below method:
public String encrypt(String strToEncrypt, String secret) {
    try {
        prepareSecreteKey(secret);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
    } catch (Exception e) {
        System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
}
To decrypt the string with a key, use below method:
public String decrypt(String strToDecrypt, String secret) {
    try {
        prepareSecreteKey(secret);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    } catch (Exception e) {
        System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
}
Here is the main method to test if we are able to get the decrypted string back from an encrypted string:
public static void main(String[] args) {
    final String secretKey = "secrete";

    String originalString = "javaguides";

    AESEncryptionDecryption aesEncryptionDecryption = new AESEncryptionDecryption();
    String encryptedString = aesEncryptionDecryption.encrypt(originalString, secretKey);
    String decryptedString = aesEncryptionDecryption.decrypt(encryptedString, secretKey);

    System.out.println(originalString);
    System.out.println(encryptedString);
    System.out.println(decryptedString);
}
Output:
javaguides
KGBmBZKY27xOHrL5t+LYAQ==
javaguides

Conclusion

In this tutorial, we have seen how to use AES(Advanced Encryption Standard) algorithm to string or text in Java with an example.

References


Comments

  1. java.lang.IllegalArgumentException: Illegal base64 character 40

    ReplyDelete

Post a Comment

Leave Comment