package tr.gov.titck.recete.encryptor;

import java.io.FileInputStream;
import java.io.IOException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import tr.gov.titck.recete.encryptor.Utils.Hex;
import tr.gov.titck.recete.encryptor.Utils.RenkliRsaPublicKey;


public class RenkliEncryptor
{
  private static final RenkliRsa.KEYSIZE keysize = RenkliRsa.KEYSIZE.RSA_2K;
  private static final char[] PASSWORD = "ZJ=ENY'2H+0bm'oyIe6J".toCharArray();
  
  private static final int SALT_LENGTH = 32;
  private static final String CHARSET = "UTF-8";
  private static final String publicKeyfile = "./RenkliRsaPublicKey.pem";
  private static final String SALT_DAT = "./salt.dat";
  
  public RenkliEncryptor() {}
  
  public String Encrypt(String json)
    throws InvalidCipherTextException, IOException
  {
    json = json.replaceAll(" ", "");
    
    RenkliAes aesService = new RenkliAes();
    byte[] saltBytes = readSaltBytes();
    
    aesService.generateKey(PASSWORD, saltBytes);
    
    byte[] aesKey = aesService.getAesKey();
    
    byte[] msgBytes = json.getBytes("UTF-8");
    byte[] encryptedJson = aesService.encode(msgBytes);
    
    RenkliRsa rsaService = new RenkliRsa(keysize);
    RenkliRsaPublicKey publicKey = rsaService.readPublicKey("./RenkliRsaPublicKey.pem");
    byte[] encodedAesKey = rsaService.encode(aesKey, publicKey);
    
    return "encryptedJson=" + Hex.encode(encryptedJson) + "&encryptedAes=" + 
      Hex.encode(encodedAesKey) + "&platform=1";
  }
  


  private static byte[] readSaltBytes()
    throws IOException
  {
    FileInputStream is = new FileInputStream("./salt.dat");Throwable localThrowable3 = null;
    try {
      byte[] saltBytes = new byte[32];
      is.read(saltBytes);
    }
    catch (Throwable localThrowable1)
    {
      localThrowable3 = localThrowable1;throw localThrowable1;
    }
    finally
    {
      if (is != null) if (localThrowable3 != null) try { is.close(); } catch (Throwable localThrowable2) { localThrowable3.addSuppressed(localThrowable2); } else is.close(); }
    byte[] saltBytes; return saltBytes;
  }
}
