Sample code for encrypting and decrypting the given string
[code language="java"]
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.GeneralSecurityException;
import java.security.Key;
public class EncryptionUtil {
private static final byte[] FIXED_SALT = "we!2$ef4gmoq!".getBytes();
private static final BouncyCastleProvider BOUNCY_CASTLE_PROVIDER = new BouncyCastleProvider();
private static final String ENCRYPT_DECRYPT_ALGORITHM = "PBEWITHSHA256AND256BITAES-CBC-BC";
private static final String ALGORITHM_WITH_PADDING = "AES/CBC/PKCS7Padding";
private static final String KEY = "test";
private static final int ITERATION_COUNT = 100000;
public static String decrypt(String encrypted) {
try {
byte[] accountIdByteArray = org.apache.commons.codec.binary.Base64.decodeBase64(encrypted);
return new String(cipher(Cipher.DECRYPT_MODE, KEY).doFinal(accountIdByteArray));
} catch (IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException("Exception occurred in decryption.", e);
}
}
public static String encrypt(String value) {
try {
return Base64.encodeBase64URLSafeString(cipher(Cipher.ENCRYPT_MODE, KEY).doFinal(value.getBytes()));
} catch (IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException("Exception occurred in encryption.", e);
}
}
private static Cipher cipher(int mode, String key) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM_WITH_PADDING, BOUNCY_CASTLE_PROVIDER);
SecretKeyFactory factory = SecretKeyFactory.getInstance(ENCRYPT_DECRYPT_ALGORITHM, BOUNCY_CASTLE_PROVIDER);
PBEKeySpec keySpec = new PBEKeySpec(key.toCharArray(), FIXED_SALT, ITERATION_COUNT);
Key secretKey = factory.generateSecret(keySpec);
PBEParameterSpec parameter = new PBEParameterSpec(FIXED_SALT, ITERATION_COUNT);
cipher.init(mode, secretKey, parameter);
return cipher;
} catch (GeneralSecurityException e) {
throw new RuntimeException("Exception occurred in cipher init ", e);
}
}
}
[/code]