
//一键登录服务端请求demo

var FormData = require('form-data');
var https = require('https');
var http = require('http');
var cryptoJS = require('crypto-js');
var md5=require('md5-node');

//应用私钥,可选，如不用RSA解密可不写。
var fs = require('fs')
var crypto = require('crypto');
var privateKey = fs.readFileSync('./rsa_private_key.pem').toString('utf-8'); //rsa_private_key.pem为应用私钥


//应用对应的APPKEY
var appKey="xxxxxxxx";

//组装请求参数
var params={
	appId:"xxxxxxxx", //应用对应的闪验appId
	token:"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", //SDK返回的token
	clientIp:"", //可以不传 ，如不传不用拼接到签名中
	outId:"", //可以不传 ，如不传不用拼接到签名中
	encryptType:"0" //可以不传 ，如不传默认：0 AES解密
};

//拼接请求字符串
var content="";
var keys=Object.keys(params).sort();
for (i = 0; i < keys.length; i++) { 
    content += keys[i] + params[keys[i]];
}

//生成签名
var sign=cryptoJS.enc.Hex.stringify(cryptoJS.HmacSHA256(content, appKey));

//发送HTTP POST请求
var form = new FormData();
form.append('appId', params.appId);
form.append('token', params.token);
form.append('clientIp', params.clientIp);
form.append('outId', params.outId);
form.append('encryptType', params.encryptType);
form.append('sign', sign);

var headers = form.getHeaders();//这个不能少
var request = https.request({
        method: 'post',
        host: 'api.253.com',
        path: "/open/flashsdk/mobile-query",
        headers: headers
    },function(res){
        var str='';
        res.on('data',function(buffer){
            str+=buffer;//用字符串拼接
        });
        res.on('end',()=>{
            var result = JSON.parse(str);
            //result就是返回的结果
            console.log(result);
            if(result.code=="200000"){
                var mobileName=result.data.mobileName;
				if("1" == params.encryptType){
					//RSA解密
					var decrypted = crypto.privateDecrypt({
							key: privateKey,
							padding: crypto.constants.RSA_PKCS1_PADDING
						},
						Buffer.from(mobileName, 'hex'));

					mobileName =decrypted.toString('utf-8');
				}else{
					//AES解密
					var key=md5(appKey);
					mobileName=aesDecrypt(mobileName,key.substring(0,16),key.substring(16));
				}
				
                console.log("手机号："+mobileName);
            }
        });
    }
);
form.pipe(request);


//AES解密 
var aesDecrypt = function(content,keys,ivs){
  var key = cryptoJS.enc.Utf8.parse(keys);
  var iv = cryptoJS.enc.Utf8.parse(ivs);
  var encryptedHexStr = cryptoJS.enc.Hex.parse(content);
  var srcs = cryptoJS.enc.Base64.stringify(encryptedHexStr);
  var decrypt = cryptoJS.AES.decrypt(srcs, key, {
      iv: iv,
      mode: cryptoJS.mode.CBC,
      padding: cryptoJS.pad.Pkcs7
  });
  var decryptedStr = decrypt.toString(cryptoJS.enc.Utf8);
  return decryptedStr.toString();
}

