encrypt.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // 参考 https://github.com/darknessomi/musicbox/wiki/
  2. const crypto = require('crypto')
  3. const bigInt = require('big-integer')
  4. const modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'
  5. const nonce = '0CoJUm6Qyw8W8jud'
  6. const pubKey = '010001'
  7. String.prototype.hexEncode = function() {
  8. let hex, i
  9. let result = ""
  10. for (i = 0; i < this.length; i++) {
  11. hex = this.charCodeAt(i).toString(16)
  12. result += ("" + hex).slice(-4)
  13. }
  14. return result
  15. }
  16. const createSecretKey = (size) => {
  17. const keys = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  18. let key = ""
  19. for (let i = 0; i < size; i++) {
  20. let pos = Math.random() * keys.length
  21. pos = Math.floor(pos)
  22. key = key + keys.charAt(pos)
  23. }
  24. return key
  25. }
  26. const aesEncrypt = (text, secKey) => {
  27. const _text = text
  28. const lv = new Buffer('0102030405060708', "binary")
  29. const _secKey = new Buffer(secKey, "binary")
  30. const cipher = crypto.createCipheriv('AES-128-CBC', _secKey, lv)
  31. let encrypted = cipher.update(_text, 'utf8', 'base64')
  32. encrypted += cipher.final('base64')
  33. return encrypted
  34. }
  35. const zfill = (str, size) => {
  36. while (str.length < size) str = "0" + str
  37. return str
  38. }
  39. const rsaEncrypt = (text, pubKey, modulus) => {
  40. const _text = text.split('').reverse().join('')
  41. const biText = bigInt(new Buffer(_text).toString('hex'), 16),
  42. biEx = bigInt(pubKey, 16),
  43. biMod = bigInt(modulus, 16),
  44. biRet = biText.modPow(biEx, biMod)
  45. return zfill(biRet.toString(16), 256)
  46. }
  47. const encrypt = (params) => {
  48. const text = JSON.stringify(params)
  49. const secKey = createSecretKey(16)
  50. const encText = aesEncrypt(aesEncrypt(text, nonce), secKey)
  51. const encSecKey = rsaEncrypt(secKey, pubKey, modulus)
  52. return {
  53. params: encText,
  54. encSecKey: encSecKey
  55. }
  56. }
  57. module.exports = encrypt