package hh.dejsem.net;

import java.security.Key;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import hh.dejsem.K;
import hh.lib.D;

public class NetCrypt {

	D d;
	String alg = K.CRYPT_ALG;
	int keylen = K.CRYPT_KEYLEN;
	Key k;
	Cipher encoder, decoder;

	public NetCrypt(D d, String alg, String passwd, int keylen) {
		try {
			this.d = d.klon(this);
			if(alg != null) this.alg = alg;
			if(keylen > 0) this.keylen = keylen;
			k = new SecretKeySpec(rawKey(passwd, this.keylen), this.alg);
			encoder = Cipher.getInstance(this.alg);
			encoder.init(Cipher.ENCRYPT_MODE, k);
			decoder = Cipher.getInstance(this.alg);
			decoder.init(Cipher.DECRYPT_MODE, k);
		} catch(Exception e) { d.abendMsg(e); }
	}

	private byte[] rawKey(String passwd, int len) {
		String key = "";
		while (key.length() < len) key += passwd;
		return  Arrays.copyOf(key.getBytes(), len);
	}

	public synchronized String decrypt(byte[] enc) throws Exception {
		return new String(decoder.doFinal(enc)).trim();
	}

	public synchronized byte[] encrypt(String msg) throws Exception {
		byte[] bMsg = msg.getBytes();
		int len = bMsg.length;
		byte[] dec = new byte[len + 8 - len%8];
		for(int i=0; i<len; i++) dec[i] = bMsg[i];
		for(int i=len; i<dec.length; i++) dec[i] = ' ';
		return encoder.doFinal(dec); }
}
