Guest User

Untitled

a guest
Jan 18th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. package com.example.javieraviles.utils.security;
  2.  
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import sun.misc.BASE64Decoder;
  6. import sun.misc.BASE64Encoder;
  7.  
  8. /**
  9. * @author JAVIERAVILES
  10. *
  11. * This class will encrypt/decrypt strings (intended for passwords mainly) into any specified algorithm with a secret.
  12. *
  13. * The initial purpose of it is to encrypt/decrypt passwords (maybe stored in atable in the database and want to be read?)
  14. */
  15. public class StringCipher {
  16.  
  17. private static final String secret = "your-secret-here";
  18. private static final String algorithm = "Blowfish";
  19.  
  20. /**
  21. * Encrypts a string (intended for passwords) with the specified secret and algorithm. base 64.
  22. *
  23. * @param password the password to be encrypted, plain text
  24. * @return the encrypted password
  25. * @throws Exception in case some error happens in the process of encrypting
  26. */
  27. public static String encrypt(final String password) throws Exception {
  28. byte[] keyData = secret.getBytes();
  29. SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, algorithm);
  30. Cipher cipher = Cipher.getInstance(algorithm);
  31. cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
  32. byte[] hasil = cipher.doFinal(password.getBytes());
  33. return new BASE64Encoder().encode(hasil);
  34. }
  35.  
  36. /**
  37. * Decrypts a string (intended for passwords) with the specified secret and algorithm. base 64.
  38. *
  39. * @param password the password to be decrypted
  40. * @return the decrypted password, plain text
  41. * @throws Exception in case some error happens in the process of decrypting
  42. */
  43. public static String decrypt(final String string) throws Exception {
  44. byte[] keyData = secret.getBytes();
  45. SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, algorithm);
  46. Cipher cipher = Cipher.getInstance(algorithm);
  47. cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
  48. byte[] hasil = cipher.doFinal(new BASE64Decoder().decodeBuffer(string));
  49. return new String(hasil);
  50. }
  51. }
Add Comment
Please, Sign In to add comment