Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
encrypt and decrypt with PBKDF2/SHA1 and AES
import javax.crypto.Cipher;
import java.security.spec.KeySpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.SecretKeyFactory;
import java.security.AlgorithmParameters;
import javax.crypto.spec.IvParameterSpec;
public class Decrypter {
Cipher dcipher;
byte[] salt = new String("12345678").getBytes();
int iterationCount = 1024;
int keyStrength = 256;
SecretKey key;
byte[] iv;
Decrypter(String passPhrase) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keyStrength);
SecretKey tmp = factory.generateSecret(spec);
key = new SecretKeySpec(tmp.getEncoded(), "AES");
dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
}
public String encrypt(String data) throws Exception {
dcipher.init(Cipher.ENCRYPT_MODE, key);
AlgorithmParameters params = dcipher.getParameters();
iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] utf8EncryptedData = dcipher.doFinal(data.getBytes());
String base64EncryptedData = new sun.misc.BASE64Encoder().encodeBuffer(utf8EncryptedData);
System.out.println("IV " + new sun.misc.BASE64Encoder().encodeBuffer(iv));
System.out.println("Encrypted Data " + base64EncryptedData);
return base64EncryptedData;
}
public String decrypt(String base64EncryptedData) throws Exception {
dcipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] decryptedData = new sun.misc.BASE64Decoder().decodeBuffer(base64EncryptedData);
byte[] utf8 = dcipher.doFinal(decryptedData);
return new String(utf8, "UTF8");
}
public static void main(String args[]) throws Exception {
Decrypter decrypter = new Decrypter("ABCDEFGHIJKL");
String encrypted = decrypter.encrypt("the quick brown fox jumps over the lazy dog");
String decrypted = decrypter.decrypt(encrypted);
System.out.println(decrypted);
}
}
@dipendrakangane

This comment has been minimized.

Copy link

dipendrakangane commented Sep 13, 2012

f5a00f26e3384a1d0ff8ff190cca366e5cb8c167

@danielcamargo

This comment has been minimized.

Copy link

danielcamargo commented Jul 4, 2014

Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1011)
at javax.crypto.Cipher.implInit(Cipher.java:786)
at javax.crypto.Cipher.chooseProvider(Cipher.java:849)
at javax.crypto.Cipher.init(Cipher.java:1213)
at javax.crypto.Cipher.init(Cipher.java:1153)
at Decrypter.encrypt(Decrypter.java:28)
at Decrypter.main(Decrypter.java:48)

@SoftwareJock

This comment has been minimized.

Copy link

SoftwareJock commented Aug 29, 2014

scotttam, thanks!

I made some minor adjustments to this code for the Android platform, & it worked fine.

@gl321

This comment has been minimized.

Copy link

gl321 commented Sep 7, 2014

This is awesome! What is the license for this code? Is it MIT License? Am I allowed to use this in my commercial app?
Also, can you make some adjustments for it to work for android? Thanks.

Thanks!

@SoftwareJock

This comment has been minimized.

Copy link

SoftwareJock commented Sep 10, 2014

gl321:

There's an Android version in the fork. It needs no license.

SoftwareJock

@martinsnelson

This comment has been minimized.

Copy link

martinsnelson commented Sep 28, 2016

I have this error can help me.

Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1026)
at javax.crypto.Cipher.implInit(Cipher.java:801)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1186)
at Decrypter.encrypt(Decrypter.java:28)
at Decrypter.main(Decrypter.java:48)
C:\Users\y9ld\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 0 segundos)

@hayderma

This comment has been minimized.

Copy link

hayderma commented Jun 1, 2017

how do i get the same encryption for the same string?, it's generating something new everytime!

@mathieu-veron

This comment has been minimized.

Copy link

mathieu-veron commented Jun 13, 2017

Nice and concise.
For all those with InvalidKeyException : illegal size, check here : http://opensourceforgeeks.blogspot.fr/2014/09/how-to-install-java-cryptography.html
I have added a static section to this class, with the reflection trick and it works fine

@thomaspreis

This comment has been minimized.

Copy link

thomaspreis commented Jan 12, 2018

I found the problem regarding "InvalidKeyException"

The length of salt was not compatible with keyStrength:
128bits == 16Bytes == 16 Chars

I changed the salt and keyStrength to this:

    byte[] salt = new String("1234567890123456").getBytes(); // length = 16
    int keyStrength = 128; // equals to 16 characters 

Then it works correctly, output:
YWa+UbQOEIXsN5uDnOUbN5SmI9Au4GcHwM8uWDTL6byPJBlxhievyh/G3q2H2zYk
the quick brown fox jumps over the lazy dog

@sonwani237

This comment has been minimized.

Copy link

sonwani237 commented Mar 6, 2018

I Have an Encrypted String, how can i decrypt it
String = "p1SvSCiAxupKrrZXzjXQk3lWe88xW7mTymvqGlmAOMM9DbYm3kkq7BLP336HwRdYOIBU9VNL0tFTchwBKbw+ZOlU6Ny3vTOtA3/hPqSUOOXDEu5aKnbbvywefu3jyX1u/EFbc1uqohJspem+d1kwxmzn
tbvui8AH6+mckIb6I9c="

@Yair0007

This comment has been minimized.

Copy link

Yair0007 commented Oct 15, 2018

In a scenario where decrypt is called first (no call to encrypt) , iv is null and there is a null pointer exception. I encountered this after reading encrypted data from Firebase and trying to decrypt.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.