encrypt_pdf.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // scripts/encrypt_pdf.ts
  2. import * as fs from 'fs'
  3. import * as path from 'path'
  4. import pako from 'pako'
  5. import { fileURLToPath } from 'url'
  6. const __filename = fileURLToPath(import.meta.url);
  7. const __dirname = path.dirname(__filename);
  8. const PDF_DIR = path.resolve(__dirname, '../../public/pdf')
  9. // 工具:ArrayBuffer / Uint8Array 转 Base64
  10. function ab2b64(buffer: ArrayBuffer) {
  11. let binary = '';
  12. const bytes = new Uint8Array(buffer);
  13. bytes.forEach(b => binary += String.fromCharCode(b));
  14. return btoa(binary);
  15. }
  16. // 简单混淆:Base64 -> URL安全 + 去掉 '='
  17. function obfuscate(base64str: string) {
  18. return base64str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  19. }
  20. // 主函数:压缩 + 混淆
  21. function compressAndObfuscate(inputPath: string, outputPath: string) {
  22. const input = fs.readFileSync(inputPath)
  23. // 压缩成 Uint8Array
  24. const compressed = pako.deflate(new Uint8Array(input));
  25. // 转 Base64 字符串
  26. const b64 = ab2b64(compressed.buffer);
  27. // 混淆返回
  28. const output = obfuscate(b64);
  29. fs.writeFileSync(outputPath, output)
  30. console.log(`✔ Compress: ${path.basename(inputPath)}`)
  31. }
  32. function encryptAllPDFs(): void {
  33. const files = fs.readdirSync(PDF_DIR)
  34. for (const file of files) {
  35. const fullPath = path.join(PDF_DIR, file)
  36. if (!fs.statSync(fullPath).isFile() || !file.endsWith('.pdf')) continue
  37. const encPath = fullPath + '.enc'
  38. if (fs.existsSync(encPath)) {
  39. console.log(`⏭ Skipped (already Compress): ${file}`)
  40. continue
  41. }
  42. compressAndObfuscate(fullPath, encPath)
  43. }
  44. }
  45. encryptAllPDFs()