fork download
  1. import javax.crypto.Cipher;
  2. import javax.crypto.SecretKey;
  3. import javax.crypto.SecretKeyFactory;
  4. import javax.crypto.spec.IvParameterSpec;
  5. import javax.crypto.spec.PBEKeySpec;
  6. import javax.crypto.spec.SecretKeySpec;
  7. import java.nio.charset.StandardCharsets;
  8. import java.security.spec.KeySpec;
  9. import java.util.*;
  10. import java.lang.*;
  11. import java.io.*;
  12.  
  13. class Ideone {
  14. private static final String SECRET_KEY = "my_super_secret_key";
  15. private static final String SALT = "ssshhhhhhhhhhh!!!!";
  16.  
  17. public static String encrypt(String strToEncrypt) {
  18. try {
  19. byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  20. IvParameterSpec ivspec = new IvParameterSpec(iv);
  21.  
  22. SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
  23. KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
  24. SecretKey tmp = factory.generateSecret(spec);
  25. SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
  26.  
  27. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  28. cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
  29. return Base64.getEncoder()
  30. .encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
  31. } catch (Exception e) {
  32. System.out.println("Error while encrypting: " + e.toString());
  33. }
  34. return null;
  35. }
  36.  
  37. public static String decrypt(String strToDecrypt) {
  38. try {
  39. byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  40. IvParameterSpec ivspec = new IvParameterSpec(iv);
  41.  
  42. SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
  43. KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
  44. SecretKey tmp = factory.generateSecret(spec);
  45. SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
  46.  
  47. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
  48. cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
  49. return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
  50. } catch (Exception e) {
  51. System.out.println("Error while decrypting: " + e.toString());
  52. }
  53. return null;
  54. }
  55.  
  56. public static void main(String[] args) {
  57. String originalString = "howtodoinjava.com";
  58.  
  59. String encryptedString = Ideone.encrypt(originalString);
  60. String decryptedString = Ideone.decrypt(encryptedString);
  61.  
  62. System.out.println(originalString);
  63. System.out.println(encryptedString);
  64. System.out.println(decryptedString);
  65. }
  66.  
  67. }
  68.  
Success #stdin #stdout 0.9s 70996KB
stdin
Standard input is empty
stdout
howtodoinjava.com
T0azvkYywVCO6qqGSm+mm5UQYzWLlCII+Z9TuOYmpnI=
howtodoinjava.com