webpack.plugin.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const crypto = require("crypto");
  2. const { RawSource } = require("webpack-sources");
  3. class EncryptPlugin {
  4. constructor({ algorithm = "aes-256-cbc", key }) {
  5. this.algorithm = algorithm;
  6. this.key = key;
  7. }
  8. encrypt(buffer, key, algorithm) {
  9. const iv = crypto.randomBytes(16);
  10. let cipher = crypto.createCipheriv(
  11. algorithm,
  12. Buffer.from(key, "base64"),
  13. iv
  14. );
  15. let encrypted = cipher.update(buffer);
  16. encrypted = Buffer.concat([encrypted, cipher.final()]);
  17. return {
  18. iv: iv.toString("base64"),
  19. encryptedData: encrypted.toString("base64"),
  20. };
  21. }
  22. apply(compiler) {
  23. compiler.hooks.compilation.tap("EncryptPlugin", (compilation) => {
  24. compilation.hooks.afterProcessAssets.tap("EncryptPlugin", () => {
  25. console.log("Encrypt setup.js content.");
  26. compilation.updateAsset("setup.js", (rawSource) => {
  27. return new RawSource(
  28. JSON.stringify(
  29. this.encrypt(rawSource.buffer(), this.key, this.algorithm)
  30. )
  31. );
  32. });
  33. });
  34. });
  35. }
  36. }
  37. module.exports = EncryptPlugin;