const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const NodeRSA = require('node-rsa');


// def sign(privatekey, data):
//     '''
//     加签
//     :param privatekey:私钥文件路径
//     :param data:要加签的数据
//     :return string:签名
//     '''
//     signEVP = EVP.load_key(privatekey)
//     signEVP.sign_init()
//     signEVP.sign_update(data)
//     result = signEVP.sign_final()
//     return base64.b64encode(result)

const private_key = fs.readFileSync(path.join(__dirname, 'keys/rsa_private_key.pem')).toString()
const zmop_public_key = fs.readFileSync(path.join(__dirname, 'keys/zmop_public_key.pem')).toString()

//params= URLEncode(Base64(RSAEncrypt(param1=URLEncode(param1value)&param2=URLEncode(param2value))))
// 加签
// :param privatekey:私钥文件路径
// :param data:要加签的数据
// :return string:签名
function RSAEncrypt(data) {
    let str = params2str(data)
    let key = new NodeRSA(zmop_public_key)
    key.setOptions({encryptionScheme: 'pkcs1'});
    let encrypted = key.encrypt(str, 'base64')
    return encrypted
}

function RSADecrypt(str) {
    let key = new NodeRSA(private_key)
    key.setOptions({encryptionScheme: 'pkcs1'});
    let encrypted = key.decrypt(str, 'utf8')
    return encrypted
}

//  转换业务参数为str
function params2str(data) {
    let str = ''
    for (let k of Object.keys(data)) {
        let v = data[k]
        if (Object.prototype.toString.call(v) === '[object Object]') {
            v = JSON.stringify(v)
        }
        str += k + '=' + encodeURIComponent(v) + '&'
    }
    return str.slice(0, str.length - 1)
}


//  str 转为 json
function str2params(str) {
    let ret = {}
    let arr = str.split('&')
    for (let item of arr) {
        let index = item.indexOf('=')
        ret[item.slice(0, index)] = decodeURIComponent(item.slice(index + 1))
    }
    return ret
}


//  加签
function sign(data) {
    //  签名采用sha1withRsa算法
    let str = params2str(data)
    let sign = crypto.createSign('RSA-SHA1')
    sign.update(str)
    return sign.sign(private_key, 'base64')
}


//  验签
//  sign_value: 签名,
//  str: 待验签的数据
function verify(sign_value, str) {
    var verify = crypto.createVerify('RSA-SHA1');
    verify.update(str);
    return verify.verify(zmop_public_key, sign_value, 'base64')
}


// let resp = {
//     "encrypted": true,
//     "sign": {
//         "signSource": "zhima_sign_value",
//         "signResult": "OKICqUJzHMn9ee5p0xIlJE7L5FZ5nOmjtdDYCqHD3FsQCM5RLJ2U3kFCpXf4sWnSW5J/DRsCmYRffofZapP7wH//xrJq5n9rVDg+CHQ3i5E5Mrtv4/X3wsURaDXpX1wJr+mGd2RL8zTwDi9FW1N7bHK28I3sNgwaoWLeS15iJ4s="
//     },
//     "biz_response_sign": "cEHP5udepFpo6Ow/ejWwLR0Q1MPaxUZA17zt7Ezd73DVNUl8RqDf/mNzap79aOucOc53n0GXwY1HIQMLLNKI9w2va62SajFhrLFYMy+QtWN3w6EsnuWNOz0xQLKpKCw3HbloD2S6nYk1dg3fBWMhC2pyZ8xXES4l6nZXWzTsOnc=",
//     "biz_response": "gG4WYaHXetiko/9nqvGPGDVIyY055WgIDQ3RxVEmX9xVRAO9m8rzO33G0lO8S3iQkfHnkjZhbiQhWP7Fm8x9LtEwm8GjnSl+6egPgORUazOAdKdbvRWr9ri18znCJLu5JBr9QH6J7NoPU5YV231fN4bCPRnpD603p96TPQ/Zw/k="
// }
// if (resp.encrypted) {
//     let decrypted_res = RSADecrypt(resp.biz_response)
//     console.log(JSON.parse(decrypted_res))
//     if (verify(resp.biz_response_sign, decrypted_res)) {
//         console.log('success')
//     } else {
//         console.log('error')
//     }
// }


module.exports = {
    sign,
    verify,
    RSAEncrypt,
    RSADecrypt,
    params2str,
    str2params
}
