Crypto.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const crypto = require('crypto')
  2. const KEY_STR = "Wet2C8d34f62ndi3"
  3. const IV_STR = "K6iv85jBD8jgf32D"
  4. const SALT = "rDJiNB9j7vD2"
  5. const KEY = Buffer.from(KEY_STR, 'utf-8')
  6. const IV = Buffer.from(IV_STR, 'utf-8')
  7. /**
  8. * AES 加密
  9. */
  10. function dataEncrypt(plainText) {
  11. try {
  12. const cipher = crypto.createCipheriv('aes-128-cbc', KEY, IV)
  13. cipher.setAutoPadding(true)
  14. let encrypted = cipher.update(plainText, 'utf-8')
  15. encrypted = Buffer.concat([encrypted, cipher.final()])
  16. return encrypted.toString('base64')
  17. } catch (err) {
  18. console.error('加密失败:', err.message)
  19. return null
  20. }
  21. }
  22. /**
  23. * AES 解密
  24. */
  25. function dataDecrypt(encryptedBase64Text) {
  26. try {
  27. const encryptedBuffer = Buffer.from(encryptedBase64Text, 'base64')
  28. const decipher = crypto.createDecipheriv('aes-128-cbc', KEY, IV)
  29. decipher.setAutoPadding(true)
  30. let decrypted = decipher.update(encryptedBuffer)
  31. decrypted = Buffer.concat([decrypted, decipher.final()])
  32. return decrypted.toString('utf-8')
  33. } catch (err) {
  34. console.error('解密失败:', err.message)
  35. return null
  36. }
  37. }
  38. /**
  39. * MD5 签名
  40. */
  41. function dataSign(dataObj) {
  42. if (typeof dataObj !== 'object') {
  43. throw new TypeError('data must be object')
  44. }
  45. const sortedKeys = Object.keys(dataObj).sort()
  46. let str = ''
  47. for (const key of sortedKeys) {
  48. str += key + String(dataObj[key])
  49. }
  50. str += SALT
  51. return crypto.createHash('md5').update(str, 'utf-8').digest('hex')
  52. }
  53. /**
  54. * OSS POST 签名
  55. */
  56. function ossPostSign(accessKeySecret, policyDocument) {
  57. const policyStr = JSON.stringify(policyDocument)
  58. const base64Policy = Buffer.from(policyStr).toString('base64')
  59. const signature = crypto
  60. .createHmac('sha1', accessKeySecret)
  61. .update(base64Policy)
  62. .digest('base64')
  63. return [base64Policy, signature]
  64. }
  65. module.exports = {
  66. dataEncrypt,
  67. dataDecrypt,
  68. dataSign,
  69. ossPostSign
  70. }