Java Encrypting and Decrypting String Example

In this tutorial, we will write a Java program on how to use Cipher class, which provides cryptographic encryption and decryption functionality in Java.

Encrypting and Decrypting Data Example

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

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class JavaCipherClassDemo {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    public String encryptMessage(byte[] message, byte[] keyBytes) throws InvalidKeyException, NoSuchPaddingException,
        NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedMessage = cipher.doFinal(message);
            return new String(encryptedMessage);
        }

    public String decryptMessage(byte[] encryptedMessage, byte[] keyBytes) throws NoSuchPaddingException,
        NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] clearMessage = cipher.doFinal(encryptedMessage);
            return new String(clearMessage);
        }

    public static void main(String[] args) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException,
        BadPaddingException, IllegalBlockSizeException {
            String encKeyString = "1234567890123456";
            String message = "Java Guides";

            JavaCipherClassDemo cipherClassDemo = new JavaCipherClassDemo();
            String encryptedstr = cipherClassDemo.encryptMessage(message.getBytes(), encKeyString.getBytes());

            String decryptedStr = cipherClassDemo.decryptMessage(encryptedstr.getBytes(), encKeyString.getBytes());
            System.out.println("Original String -> " + message);
            System.out.println("Encrypted String -> " + encryptedstr);
            System.out.println("Decrypted String -> " + decryptedStr);

        }
}
Output:
Original String -> Java Guides
Encrypted String -> øgY};Ù’}±Ýë00®H³
Decrypted String -> Java Guides

References



Comments