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 secure.
Read More : Java AES 256 Encryption Decryption Example
1. AES Encryption and Decryption
Let’s see an example of using AES encryption in this java program.
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;
public class AES {
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(final String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(final String strToEncrypt, final String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
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 static String decrypt(final String strToDecrypt, final String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
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;
}
}
2. Encryption and decryption example
Let’s test if we are able to get the decrypted string back from the encrypted string.
final String secretKey = "ssshhhhhhhhhhh!!!!";
String originalString = "howtodoinjava.com";
String encryptedString = AES.encrypt(originalString, secretKey) ;
String decryptedString = AES.decrypt(encryptedString, secretKey) ;
System.out.println(originalString);
System.out.println(encryptedString);
System.out.println(decryptedString);
Program Output.
howtodoinjava.com
Tg2Nn7wUZOQ6Xc+1lenkZTQ9ZDf9a2/RBRiqJBCIX6o=
howtodoinjava.com
Drop me your question and comments below.
Happy Learning !!
How do i decrypt this using python .if data is encrypted using this method in java
how to encrypt a text file with some records. can anyone help me
Try using a hash file first.
Does it generates fixed output for fixed inputs
Did you tried it?
How many rounds are you using here? 16?
Hi, The encryption works good for me. But when I try to decrypt the string its returning the null value. Could you explain why is it happening and how to solve it? Below is the line of code for decryption:
Cipher cipher = Cipher.getInstance(“AES/ECB/PKCS5PADDING”);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
Is there a reason why you have SecretKeySpec as you instance variable resulting in the encrypt() and decrypt() methods having to init the ciphers every time?
Could you init the two ciphers and keep these as your instance variables?
Hi.. i wanted the same encryption to be done in PHP.Can you help me out?
java: cant find symbol
symbol : variable AES
Can be customize to support for 512 Key length(encryption key)? How?
Suppose, I want to encrypt message with 512 key if possible, Are there any possibilities?
In javascript to use above encryption and decryption using CryptoJS how to achieve?
This method works very good! Thanks for that!
However, I’d like to send some encrypted data to my PHP API, and decipher the data there, applying the same key.
Do you have, by change, any idea how I manage that?
And also, do you have any solution how I can avoid hardcoding the encryption key?
Hie, thank you for this really informative blogpost.
Kindly help me please. Here’s my encryption block:
When I print the values in console, the final encrypted value remains same for an unchanging message and key (exactly what I desire).
However, I just want to know that why ‘encVal’ which is the value resulting from doFinal() method, changes every time for the same unchanging message and key?
Thank you 🙂
Huh, this question is not relevant is is not helpful. Please use python instead.
Hi,
Thank you for this example. I was building a file encryption program.
This example really helped. If possible, please have a look:
https://github.com/Pratik-Doshi-99/File-Encryption-in-Java
Regards,
Pratik Doshi
Looks good to me. And thanks for the link.
while sending the encrypted string in URl , its considering the special character as spaces.. so how we can remove special characters while encrypting the number.
I am also facing same issue please let me know if you had solved it.
You have to encode base 64
That’s good example. I used in my test program.
Hi,
Its working fine. but what my doubt is, Is this enough for complete security or need something more.
Thank you.
Satya.
Is there any way to encrypt and decrypt video file?
Yes is work fine thank you very much.
from encrypted value only doing dycrypt what is the use
please can you explain each line of the codes..Thanks
That would be also my wish 🙂
Really awesome example.
I want to encrypt and decrypt a JSON object. Can I use this code with some changes? If yes, what all changes required? Thanks in advance!
Probably, just deserialize the object to String. And then encrypt the string value.
how do we write this code mySQL ? I tried with aes_encrypt() and decrypt() getting null value so please guide me
here we can use either “AES” or “Rijndael” secret key, do we use another secret key for encryption
Hi I got import java.util.Base64 not found.
Kindly advise.
Thank you!
It’s included in 1.8 or above.
Could you please suggest, what change I need to do in the code if I want to use CTR mode instead of ECB? Thank you.
java.util.Base64 available in JDK 1.8
Really? You still use AES with ECB mode to encrypt a message!
Any suggestion. I will appreciate it and learn as well.
ECB mode is insecure when using in block cipher because this mode do not satisfy semantically secure.
You can learn more about it: https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption/20946#20946
And when using block cipher (AES, 3DES), you should use CTR (Counter mode) or CBC mode with RANDOM IV.
But CTR or CBC mode just prevent against eavesdropping attackers, and is NOT secure again active attackers who can modify, reject, delete packets. To prevent against active attackers, you should use Authenticated Encryption like Encrypt-then-MAC.
https://codeinsecurity.wordpress.com/2013/04/05/quick-crypto-lesson-why-mac-then-encrypt-is-bad/