
var crypto = require("crypto");
var fs = require('fs')
var path = require('path')

const Encrypt = ({ str, method, pri = "", result = "hex" }) => {
	var c = null;
	if (pri) {
		c = crypto.createHmac(method, pri);
	} else {
		c = crypto.createHash(method);
	}
	c.update(str);
	return c.digest(result);
}

const aes_config = (method) => {
	let iv = null;
	let length = 0;
	switch (method) {
		case "aes-128-ecb":
			length = 16;
			iv = Buffer.alloc(0)
			break;
		case "aes-128-cbc":
			length = 16;
			iv = Buffer.alloc(16)
			break;
		case "aes-192-ecb":
			length = 24;
			iv = Buffer.alloc(0)
			break;
		case "aes-192-cbc":
			length = 24;
			iv = Buffer.alloc(16)
			break;
		case "aes-256-ecb":
			length = 32;
			iv = Buffer.alloc(0)
			break;
		case "aes-256-cbc":
			length = 32;
			iv = Buffer.alloc(16)
			break;
	}

	return { iv, length }
}

const ASE_Encrypt = ({ str, pri, method = "aes-128-ecb", result = "hex" }) => {
	let cfg = aes_config(method);
	if (pri.length !== cfg.length) {
		throw new Error(`${method}, 秘钥长度必须是${cfg.length}位`)
	}
	var cipher = crypto.createCipheriv(method, pri, cfg.iv);
	return cipher.update(str, 'utf8', result) + cipher.final(result);
}

const ASE_Decrypt = ({ str, pri, method = "aes-128-ecb", result = "hex" }) => {
	let cfg = aes_config(method);
	if (pri.length !== cfg.length) {
		throw new Error(`${method}, 秘钥长度必须是${cfg.length}位`)
	}
	var cipher = crypto.createDecipheriv(method, pri, cfg.iv);
	return cipher.update(str, result, 'utf8') + cipher.final('utf8');
}

function RSA2_Create(params, rsa_pri) {
	let signer = crypto.createSign('RSA-SHA256');
	var buff = new Buffer(params, 'utf-8');
	signer.update(buff);
	let rsa = rsa_pri || ""
	if (!rsa_pri) rsa = path.join(os.homedir(), '/.ssh/', 'id_rsa');
	var privateKey = fs.readFileSync(rsa).toString();
	let sign = signer.sign(privateKey, 'base64');
	return sign;
}

function RSA2_Valid(params, sign, rsa_pub) {
	let verify = crypto.createVerify('RSA-SHA256');
	var buff = new Buffer(params, 'utf-8');
	let rsa = rsa_pub || ""
	if (!rsa_pri) rsa = path.join(os.homedir(), '/.ssh/', 'id_rsa.pub');
	var publicKey = fs.readFileSync(rsa).toString();
	return verify.update(buff).verify(publicKey, sign, 'base64');
}

module.exports = {
    Encrypt,
    ASE_Encrypt,
    ASE_Decrypt,
    RSA2_Create,
    RSA2_Valid,
}