Crypto.js 2.1 KB

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