package routines;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class CustomSecurity {

	private static final String ALGO = "AES";
	
	private static final byte[] keyValue = new byte[] { 'S', 'e', 'C', 'r', 'e', 't', 'P',	'@', 's', 'S', '0','r', 'D', '5', '6', '1'};
	
	public static Integer idEtapeErreur = null;
	    
    private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGO);
        return key;
    }
    
    /**
     * encrypt: return encrypted value
     * 
     * 
     * {talendTypes} String
     * 
     * {Category} CustomSecurity
     * 
     * {param} string("password") input: Le mot de passe à crypter.
     * 
     * {example} encrypt("password") # xxtj3NnaxAI2T+34Rc+r5g==
     */    
    public static String encrypt(String Data) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal(Data.getBytes());
        String encryptedValue = new BASE64Encoder().encode(encVal);
        return encryptedValue;
    }

    /**
     * decrypt: return decrypted value
     * 
     * 
     * {talendTypes} String
     * 
     * {Category} CustomSecurity
     * 
     * {param} string("password") input: Le mot de passe à décrypter.
     * 
     * {example} decrypt("xxtj3NnaxAI2T+34Rc+r5g==") # password
     */ 
    public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }

    /**
     * copyToClipboard: copie text to clipboard
     * 
     * 
     * {talendTypes} String
     * 
     * {Category} CustomSecurity
     * 
     * {param} string("mon texte") input: Le texte à copier dans le press-papier.
     * 
     * {example} copyToClipboard("mon texte") # 
     */   
    public static void copyToClipboard(String text) {
	    Toolkit toolKit = Toolkit.getDefaultToolkit();
	    Clipboard cb = toolKit.getSystemClipboard();
	    cb.setContents(new StringSelection(text), null);
	}
}
