How to encrypt and decrypt text with passphrase in Java

By | November 30, 2018

In this quick snippet we are going to explain how to encrypt and decrypt text with passphrase in java.

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

This is just a snippet. It explains how encryption and decryption works with java. Normally, in production, we create custom classes. A custom class allows to use the encryption more efficiently. If you want to know more, you can follow: Stack Overflow Question Related to Encrypt And Decrypt in Java.

String text = "Hello World";
String key = "Bar12345Bar12345"; // 128 bit key
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
System.err.println(new String(encrypted)); // decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
System.err.println(decrypted);

Leave a Reply

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