Low Orbit Flux Logo 2 D

Java How To Encrypt A String

Today we’re going to show you how to encrypt a string in Java. This isn’t incredibly difficult but it isn’t as easy as just writing a couple lines of code either.

Java How to Encrypt a String - AES Example

Here is an example showing how you can encrypt and then decrypt a simple string. The variable plainTextString holds the original message that you want to encrypt. The variable myKey holds the key that will be used to encrypt your string. The same key will be needed to decrypt your key.

import java.io.UnsupportedEncodingException;
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;

class Test1 {
    public static void main( String args[] ) {
        try {

            final String myKey = "This is my secret key. - horse cow frog rock pizza 123#$%";
            String plainTextString = "This is my secrete message that needs to be secure.";

            byte[] key = myKey.getBytes("UTF-8");
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);
            SecretKeySpec secretKey = new SecretKeySpec(key, "AES");

            Cipher cipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher1.init(Cipher.ENCRYPT_MODE, secretKey);
            String encrypted = Base64.getEncoder().encodeToString(cipher1.doFinal(plainTextString.getBytes("UTF-8")));

            Cipher cipher2 = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher2.init(Cipher.DECRYPT_MODE, secretKey);
            String decrypted = new String(cipher2.doFinal(Base64.getDecoder().decode(encrypted)));

            System.out.println("Plain text string: " + plainTextString);
            System.out.println("Encrypted String: " + encrypted);
            System.out.println("Decrypted String: " + decrypted);
        catch (NoSuchAlgorithmException e) {
        catch (UnsupportedEncodingException e) {
        catch (Exception e) {