AESHelper.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package com.persagy.iottransfer.communication.util;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.spec.IvParameterSpec;
  4. import javax.crypto.spec.SecretKeySpec;
  5. public class AESHelper {
  6. private static final String KEY_ALGORITHM = "AES";
  7. private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
  8. private final String algorithm;
  9. private final byte[] password;
  10. private final String mode;
  11. private Cipher cipher;
  12. public AESHelper(String algorithm, byte[] password, String mode) throws Exception {
  13. if (algorithm != null) {
  14. this.algorithm = algorithm;
  15. } else {
  16. this.algorithm = DEFAULT_CIPHER_ALGORITHM;
  17. }
  18. this.password = password;
  19. this.mode = mode;
  20. if (this.mode.equals("encrypt")) {
  21. this.cipher = this.initCipher(this.password, Cipher.ENCRYPT_MODE);
  22. } else if (this.mode.equals("decrypt")) {
  23. this.cipher = this.initCipher(this.password, Cipher.DECRYPT_MODE);
  24. }
  25. }
  26. private Cipher initCipher(byte[] password, int CipherMode) throws Exception {
  27. Cipher cipher = Cipher.getInstance(this.algorithm);
  28. SecretKeySpec keySpec = new SecretKeySpec(password, KEY_ALGORITHM);
  29. IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
  30. cipher.init(CipherMode, keySpec, ivSpec);
  31. return cipher;
  32. }
  33. public synchronized byte[] encrypt(byte[] bytes) throws Exception {
  34. if (this.mode.equals("encrypt")) {
  35. byte[] results = this.cipher.doFinal(bytes);
  36. return results;
  37. } else {
  38. return null;
  39. }
  40. }
  41. public synchronized byte[] decrypt(byte[] bytes) throws Exception {
  42. if (this.mode.equals("decrypt")) {
  43. byte[] results = this.cipher.doFinal(bytes);
  44. return results;
  45. } else {
  46. return null;
  47. }
  48. }
  49. }