Sample Encrypt & Decrypt String in Java

In this tutorial, i will give a simple example how i encrypt & decrypt string with JAVA.

Below my code:

import java.util.Base64;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
 
public class SampleEncryptDecrypt {
 
	public String encrypt(String strClearText, String strKey) throws Exception {
		String strData = "";
 
		try {
			SecretKeySpec skeyspec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
			Cipher cipher = Cipher.getInstance("Blowfish");
			cipher.init(Cipher.ENCRYPT_MODE, skeyspec);
			byte[] encrypted = cipher.doFinal(strClearText.getBytes());
			strData = Base64.getEncoder().encodeToString(encrypted);
 
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
		return strData;
	}
 
	public String decrypt(String strEncrypted, String strKey) throws Exception {
		String strData = "";
 
		try {
			SecretKeySpec skeyspec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
			Cipher cipher = Cipher.getInstance("Blowfish");
			cipher.init(Cipher.DECRYPT_MODE, skeyspec);
			byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(strEncrypted));
			strData = new String(decrypted);
 
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
		return strData;
	}
 
	public static void main(String[] args) throws Exception {
		SampleEncryptDecrypt sed = new SampleEncryptDecrypt();
		String encryptResult = sed.encrypt("arifnasution", "key");
		String decryptResult = sed.decrypt(encryptResult, "key");
		System.out.println("Encryption Result : " + encryptResult);
		System.out.println("Decryption Result : " + decryptResult);
	}
}

CMIIW :)

Leave a Reply

Your email address will not be published. Required fields are marked *

Afiseaza emoticoanele Locco.Ro