package com.interpress_project.modernshare.ipcommon;

import java.nio.ByteBuffer;
import java.util.Date;
import java.util.Random;

/**
 * Represents a singleton.
 */
public class HotShotCipher {
	private int code = 0;

	/**
	 * HotShotCipher
	 */
	public HotShotCipher() {
	}

	/**
	 * HotShotCipher
	 * @param key
	 */
	public HotShotCipher(int keycode) {
		for (int i = 0; i < 255; i++) {
			code = (keycode * (i + 1)) % 255;
			if (code == 0) {
				continue;
			}
		}
	}

	/**
	 * keygen
	 * @param hostname
	 * @param account
	 * @return
	 */
	public int keygen(String hostname, String account) {
		int k = 154311;
		Random random = new Random(new Date().getTime());
		String s = hostname + random.nextLong() + account + random.nextLong();
		byte[] b = s.getBytes();
		for (int i = 0; i < b.length; i++) {
			k += b[i];
		}
		return k * k;
	}

	/**
	 * encrypt
	 * @param buffer
	 * @param len
	 * @return
	 */
	public byte[] encrypt(byte[] buffer, int len) {
		byte[] result = buffer;
		for (int i = 0; i < len; i++) {
			result[i] ^= (byte) code;
		}
		return result;
	}

	/**
	 * encrypt
	 * @param buffer
	 * @param len
	 * @return
	 */
	public byte[] encrypt(ByteBuffer buffer, int len) {
		return encrypt(buffer.array(), len);
	}

	/**
	 * decrypt
	 * @param buffer
	 * @param len
	 * @return
	 */
	public byte[] decrypt(byte[] buffer, int len) {
		byte[] result = buffer;
		for (int i = 0; i < len; i++) {
			result[i] ^= (byte) code;
		}
		return result;
	}

	/**
	 * decrypt
	 * @param buffer
	 * @param len
	 * @return
	 */
	public byte[] decrypt(ByteBuffer buffer, int len) {
		return decrypt(buffer.array(), len);
	}
}
