package com.im.imjutil.cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.im.imjutil.exception.CipherException;
import com.im.imjutil.validation.Convert;
/**
* Classe responsavel por codificar e decodificar algoritmos de criptografia.
*
* @author Felipe Zappala
*/
public class CryptographyCipher extends Cipher {
private SecretKey secretKey;
private javax.crypto.Cipher cipherAlgorithm;
private boolean isStarted;
private CipherType type;
public CryptographyCipher(CipherType type) {
this.type = type;
}
/**
* Inicializa o algoritmo de criptografia usando o tipo configurado.
*/
protected void initialize() throws Exception {
if (!isStarted) {
secretKey = new SecretKeySpec(password, type.cipher);
cipherAlgorithm = javax.crypto.Cipher.getInstance(type.cipher);
isStarted = true;
}
}
@Override
public byte[] encrypt(byte[] value) throws CipherException {
try {
initialize();
cipherAlgorithm.init(javax.crypto.Cipher.ENCRYPT_MODE, secretKey);
return cipherAlgorithm.doFinal(value);
} catch (Exception e) {
throw new CipherException(Convert.toString(
"Cipher error: ", e.getMessage()), e);
}
}
@Override
public byte[] decrypt(byte[] value) throws CipherException {
try {
initialize();
cipherAlgorithm.init(javax.crypto.Cipher.DECRYPT_MODE, secretKey);
return cipherAlgorithm.doFinal(value);
} catch (Exception e) {
throw new CipherException(Convert.toString(
"Cipher error: ", e.getMessage()), e);
}
}
}