Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. import java.io.UnsupportedEncodingException;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.util.Arrays;
  5. import java.util.Base64;
  6.  
  7. import javax.crypto.Cipher;
  8. import javax.crypto.spec.SecretKeySpec;
  9.  
  10. public class AES {
  11.  
  12. private static SecretKeySpec secretKey;
  13. private static byte[] key;
  14.  
  15. public static void setKey(String myKey)
  16. {
  17. MessageDigest sha = null;
  18. try {
  19. key = myKey.getBytes("UTF-8");
  20. sha = MessageDigest.getInstance("SHA-1");
  21. key = sha.digest(key);
  22. key = Arrays.copyOf(key, 16);
  23. secretKey = new SecretKeySpec(key, "AES");
  24. }
  25. catch (NoSuchAlgorithmException e) {
  26. e.printStackTrace();
  27. }
  28. catch (UnsupportedEncodingException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32.  
  33. public static String encrypt(String strToEncrypt, String secret)
  34. {
  35. try
  36. {
  37. setKey(secret);
  38. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  39. cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  40. return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
  41. }
  42. catch (Exception e)
  43. {
  44. System.out.println("Error while encrypting: " + e.toString());
  45. }
  46. return null;
  47. }
  48.  
  49. public static String decrypt(String strToDecrypt, String secret)
  50. {
  51. try
  52. {
  53. setKey(secret);
  54. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
  55. cipher.init(Cipher.DECRYPT_MODE, secretKey);
  56. return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
  57. }
  58. catch (Exception e)
  59. {
  60. System.out.println("Error while decrypting: " + e.toString());
  61. }
  62. return null;
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement