package com.capgemini.framework.common.security;

import com.capgemini.framework.teamcenter.exceptions.KurtException;
import sun.misc.BASE64Decoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * This program generates a AES key, retrieves its raw bytes, and then reinstantiates a AES key from the key bytes. The
 * reinstantiated key is used to initialize a AES cipher for encryption and decryption.
 */
public class AesEncoded {
  private final String encodedText;

  public AesEncoded(final String encodedText) {
    this.encodedText = encodedText;
  }

  /**
   * Décodage d'une chaine de caractères suivant le cryptage défini.
   */
  public String decode() throws KurtException {
    try {
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec("pvsir123niabppq6".getBytes(), "AES"));
      return new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(encodedText)));
    }
    catch (NoSuchPaddingException | IOException | NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
      throw new KurtException("Error decoding the string " + encodedText, e);
    }
  }
}
