package cn.superdesk.uniorder.common.security.crypt;

import cn.superdesk.uniorder.common.security.crypt.rsa.RSATest;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;


@Slf4j
public class SuperdeskUniorderRsaUtils {

	private static String PRIKEY = "MIIBVwIBADANBgkqhkiG9w0BAQEFAASCAUEwggE9AgEAAkEArjo6uGqOh3GTAcu9bHmVCj3qH92uZKueL+lxYiCUuTLNnp5ZRVjOHgoTr1YpVdVTjGZ8/NIZeAZrVWsBOjqkPQIDAQABAkEAlmm49iswH2iC1MMTJsoUTIJFVPtqKokrCQwNkfy0yOjMOV055Zk9eQfKLuEskgAgQQBNyLOqzSuKuIrrurDUNQIhAPpz7Ok9eJsEdHpMeTUMY7TGf2ODr8WB0kKNS+9kn3vTAiEAshYam3oq8SJGaGdi2Z9SsEYY1wUIvSNMojRroB5Cpa8CIQDizhpseht/HoCwxBI7pRWh/uQb5YRG8zLKzBRJHbGDuwIhAK9gjTtoCDoH4waWKgbem/P0VCoMTxrUVHe43/SDWGcJAiEAn6+zF5A1jvHdhC5Wut83diU9/FzTu4U2yAUWcICp4H0=";
	private static String PUBKEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK46OrhqjodxkwHLvWx5lQo96h/drmSrni/pcWIglLkyzZ6eWUVYzh4KE69WKVXVU4xmfPzSGXgGa1VrATo6pD0CAwEAAQ==";

	public static String readInputStream(InputStream is, Charset charset) {

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[]                buffer       = new byte[1024];
		int                   len          = 0;
		String                result       = "";
		if (is != null) {
			try {
				while ((len = is.read(buffer)) != -1) {
					outputStream.write(buffer, 0, len);
				}
				result = new String(outputStream.toByteArray(), charset);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/***
	 * 随机数
	 * @param machineId
	 * @return
	 */
	public static String genId(String machineId) {
		String orderId =
				machineId +
						(System.currentTimeMillis() + "").substring(1) +
						(System.nanoTime() + "").substring(7, 10);
		log.info("生产随机: {}\n", orderId);
		return orderId;
	}

	public static String encode(String content) throws Exception {
		String pubKeyStr = RSATest.encryptByPubKey(content, PUBKEY);
		String encodeUrl = java.net.URLEncoder.encode(pubKeyStr, "UTF-8");
		log.info("加密结果: {}\n", pubKeyStr);
		return encodeUrl;
	}

	public static String decode(String Content) throws Exception {
		String decodeUrl = java.net.URLDecoder.decode(Content, "UTF-8");
		String priKeyStr = RSATest.decryptByPriKey(decodeUrl, PRIKEY);
		log.info("解密结果: {}\n", priKeyStr);
		return priKeyStr;
	}

	public static void main(String[] args) {

		Long   saleId   = 1L;
		String saleName = "前台优选";

		String content = saleId + "::" + saleName;
		try {
			String encode = SuperdeskUniorderRsaUtils.encode(content);

			log.info(encode);

			String decode = SuperdeskUniorderRsaUtils.decode(encode);

			log.info(decode);

		} catch (Exception e){

		}



	}
}
