1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package com.persagy.iottransfer.communication.util;
- import javax.crypto.Cipher;
- import javax.crypto.spec.IvParameterSpec;
- import javax.crypto.spec.SecretKeySpec;
- public class AESHelper {
- private static final String KEY_ALGORITHM = "AES";
- private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
- private final String algorithm;
- private final byte[] password;
- private final String mode;
- private Cipher cipher;
- public AESHelper(String algorithm, byte[] password, String mode) throws Exception {
- if (algorithm != null) {
- this.algorithm = algorithm;
- } else {
- this.algorithm = DEFAULT_CIPHER_ALGORITHM;
- }
- this.password = password;
- this.mode = mode;
- if (this.mode.equals("encrypt")) {
- this.cipher = this.initCipher(this.password, Cipher.ENCRYPT_MODE);
- } else if (this.mode.equals("decrypt")) {
- this.cipher = this.initCipher(this.password, Cipher.DECRYPT_MODE);
- }
- }
- private Cipher initCipher(byte[] password, int CipherMode) throws Exception {
- Cipher cipher = Cipher.getInstance(this.algorithm);
- SecretKeySpec keySpec = new SecretKeySpec(password, KEY_ALGORITHM);
- IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
- cipher.init(CipherMode, keySpec, ivSpec);
- return cipher;
- }
- public synchronized byte[] encrypt(byte[] bytes) throws Exception {
- if (this.mode.equals("encrypt")) {
- byte[] results = this.cipher.doFinal(bytes);
- return results;
- } else {
- return null;
- }
- }
- public synchronized byte[] decrypt(byte[] bytes) throws Exception {
- if (this.mode.equals("decrypt")) {
- byte[] results = this.cipher.doFinal(bytes);
- return results;
- } else {
- return null;
- }
- }
- }
|