Package com.im.imjutil.cipher

Source Code of com.im.imjutil.cipher.CryptographyCipher

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);
    }
  }

}
TOP

Related Classes of com.im.imjutil.cipher.CryptographyCipher

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.