Advertisement
Guest User

Untitled

a guest
May 30th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. import javax.crypto.BadPaddingException;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.IllegalBlockSizeException;
  4. import javax.crypto.NoSuchPaddingException;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import java.io.UnsupportedEncodingException;
  7. import java.security.InvalidKeyException;
  8. import java.security.MessageDigest;
  9. import java.security.NoSuchAlgorithmException;
  10. import java.util.Arrays;
  11. import java.util.Base64;
  12.  
  13. public class Coder {
  14. private final String SALT = "dominikszczygiel";
  15. private final String KEY = "dominikszczygiel";
  16. private final Cipher encrypter;
  17. private final Cipher decrypter;
  18.  
  19. public Coder() throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
  20. encrypter = Cipher.getInstance("AES/ECB/PKCS5Padding");
  21. decrypter = Cipher.getInstance("AES/ECB/PKCS5Padding");
  22. encrypter.init(Cipher.ENCRYPT_MODE, keyToSpec(SALT + KEY));
  23. decrypter.init(Cipher.DECRYPT_MODE, keyToSpec(SALT + KEY));
  24. }
  25.  
  26. public String encrypt(String value) throws UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
  27. return Base64.getEncoder().encodeToString(encrypter.doFinal(value.getBytes("UTF-8")));
  28. }
  29.  
  30. public String decrypt(String encryptedValue) throws UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
  31. return Base64.getEncoder().encodeToString(decrypter.doFinal(encryptedValue.getBytes("UTF-8")));
  32. }
  33.  
  34. private SecretKeySpec keyToSpec(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
  35. byte[] bytes = (SALT + key).getBytes("UTF-8");
  36. MessageDigest sha = MessageDigest.getInstance("SHA-1");
  37. byte[] digest = sha.digest(bytes);
  38. digest = Arrays.copyOf(digest, 16);
  39. return new SecretKeySpec(digest, "AES");
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement