encryption.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const crypto = require('crypto');
  2. function getIV() {
  3. if (process.env.ENCRYPTION_IV) {
  4. return Buffer.from(process.env.ENCRYPTION_IV, 'hex');
  5. }
  6. return crypto.randomBytes(16);
  7. }
  8. function encryptLicenseKey(text) {
  9. const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
  10. const iv = getIV();
  11. const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  12. let encrypted = cipher.update(text, 'utf8', 'hex');
  13. encrypted += cipher.final('hex');
  14. return iv.toString('hex') + ':' + encrypted;
  15. }
  16. function decryptLicenseKey(encrypted) {
  17. const [ivHex, encryptedText] = encrypted.split(':');
  18. const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
  19. const iv = Buffer.from(ivHex, 'hex');
  20. const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
  21. let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  22. decrypted += decipher.final('utf8');
  23. return decrypted;
  24. }
  25. function generateLicenseKey() {
  26. const randomBytes = crypto.randomBytes(16);
  27. const timestamp = Date.now().toString();
  28. const combined = randomBytes.toString('hex') + timestamp;
  29. const encrypted = encryptLicenseKey(combined);
  30. return encrypted;
  31. }
  32. function encryptResponse(data) {
  33. // 在开发模式下直接返回原始数据
  34. if (process.env.NODE_ENV === 'development') {
  35. return data;
  36. }
  37. // 生产模式下加密数据
  38. const jsonStr = JSON.stringify(data);
  39. const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
  40. const iv = getIV();
  41. const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  42. let encrypted = cipher.update(jsonStr, 'utf8', 'hex');
  43. encrypted += cipher.final('hex');
  44. return {
  45. encrypted_data: iv.toString('hex') + ':' + encrypted
  46. };
  47. }
  48. module.exports = {
  49. encryptLicenseKey,
  50. decryptLicenseKey,
  51. generateLicenseKey,
  52. encryptResponse
  53. };