import { util as UTIL, pki as PKI, md as SHA1 } from 'node-forge';
const PRIVATE_KEY = `
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDNVDPPQWzRINwz
9uXuop/y4zOQt7i2RPB79ITp40G3ceFiMp0SHo7Usc5WDkN6lEF2CvI20+cztT/7
scf40snP5vm75NHU3t0lOZjSllZjAsBfJHgHrXJIBgWt484CoHGimFyd2xGUs44z
IFHus6ilMAY3aqfUHtuMnggTdHYYMZPYX28fY5h0mixAJylqR7oadxgk6oUMWDtn
tBYZZd1eMy6P7TYo5ecbfFfGuJ9xOMHlbybJl88b+E/YIvf5K8csS1W5262AW8v/
yyEj0Fr/QtGsycW5klEoOdDCy+8IFYBl4R9IohHPcVd84Ya4xb2tED1gTFP6+61D
Sf6X/Ky9AgMBAAECggEBAJ3GoRUWKf68qFiJ1P89GXkzGrGOazIr4Trulp9+kEXd
DRo+2DFPJ+PKSUoZJcLwXyjMmniE9fjmwqauYoIRvx+xVZ8K4i4Xnoj3LDZNbU4h
lB7H0C/eGJ29eum2zdt43DjbqPdnmafRHWit4idxCBr+vxggLZwypfP0jzIb4I8P
UTggJqs2mt574FDaov2vf1BYoc8MXQWDCHrMJQOaZbZJhzIisu/gOzbMcq2m8gT4
3wtPEe3Hs0froQ2mwpLpURu6JwgYwTfWoV/hkBuvBeTJ8qHLhjiql69v3PIuMQPi
4Rz7TbQTcQhHRnHHqrIn7/iEoVtHoAesvfXoqqmHaUUCgYEA5rHwf1l164UeZe99
yj3d8Dntu6mH/xbRrHT+gSJJBZ5Jd0/RWRo6CA/gxnBXUotDHGLNZSKBt5/sENtl
vRmk9LMm4RPELDs8b9LdlbOYOOFEWbcHDGUInMSIZBNlisyp6J8bLVP6jTWsLQBw
kAJPzq7A2iiQdzXxKbOmq3AgqPcCgYEA49n3J7cZNIMRqFlmf8W4Dd1YKt0RivJW
hkGTnrd6+4YbdJZM1R55oW2WuxuoSwsQiHeiuzUi7WE+NPIoAfxBCnUj7uvEca0H
r2PKE8BMimQQ1+MQDyTR7eI39mg5pUPS56Tf06vc7LeeckPM4uC4wB26aUCVlQEf
xmP7l4HofusCgYACHK7u+4qw1U8p779fEqHtiRo8FZlBJJxWz9tko0O34XMavIhW
IH9Xg42zQ2QJRW0f3Wez/VTisXwfy2JrEMkJ1HoOpXeuT/yFqZCNxk8mdimCCMLv
wh0KEmKNSAAt/SGxF4PQLmykzlD9OHvPVbYVVlQ9qxFnhf7nOtXTy/sAkQKBgQCa
RHVGen2iRCusY/s1/1RCbt7HBq5d+P4EIFomV+v4aDAmm6yhjuSjG2O2g19Kj889
1mJjhfKD7hcEGgBkd7pBrlYJ6a8zmAdgBJxJCyXHfUC6Ko4w8qj/+u4Q8zg0YNtm
4wZ4diA6VYf9rVIHOkdcK8SOhp/AJuawl/k790TGyQKBgC9vau2PNLh2SaTEk5yj
fU7YAa1tVA/I6mSCtn5txDxImmAdrr+0CUgkxseRD6C9R7+LhTAI7ut9Dfyas2rt
qaWaTzv8WpQKzz5bTnJ0jIDzixKTwh/HsbSLKLNFSq1ll6p5McXdl1x0mRJP0/Vi
hSPWLmUrK0i/WulMr0sOaDT/
-----END PRIVATE KEY-----`;

/**
 * @description: 数据加密
 * @param {String} data 数据源
 * @return {String} 加密后的数据base64
 */

export function encryption(data = '') {
  if (!data) return null;
  const plaintext = typeof data === 'object' ? JSON.stringify(data) : data;
  const signData = generateSign(plaintext);
  return signData;
}

/**
 * @description: RSA私钥+SHA1生成签名
 *                签名组成结构nonce+appid+timestamp+body
 * @param {String} txt 数据源
 * @return {Object} 生成的sign数据，时间戳、Nonce
 */
function generateSign(txt) {
  const privateKey = PKI.privateKeyFromPem(PRIVATE_KEY);
  const md = SHA1.sha1.create();
  md.update(txt, 'utf8');
  let signData = privateKey.sign(md);
  signData = buffer2Base64(signData);
  return {
    signData
  };
}

/**
 * @description: buffer转base64
 * @param {Buffer} buf buffer源数据
 * @return {String} base64 字符串
 */
function buffer2Base64(buf) {
  return UTIL.encode64(buf);
}
