การสร้าง QR Code อย่างปลอดภัย: แนวทางปฏิบัติที่ดีสำหรับนักพัฒนา

Embed This Widget

Theme


      
    

Widget powered by . Free, no account required.

Developer guide: input validation, output sanitisation, secret handling, HTTPS enforcement, and preventing injection attacks.

Secure QR Code Generation: Best Practices for Developers

Developers building QR code generation features must address input validation, output safety, secret handling, and injection prevention to create secure systems.

Input Validation

URL validation: Before generating a URL QR code: - Validate the URL format (scheme, host, path) - Enforce HTTPS — reject HTTP URLs for consumer-facing codes - Check against a domain allowlist for enterprise applications - Validate URL length against QR code capacity limits

Contact data validation: For vCard and MeCard: - Sanitise phone numbers (validate E.164 format) - Validate email addresses - Escape special characters in names (semicolons, colons in vCard format)

Free-text validation: For plain text QR codes: - Limit input length to prevent oversized QR codes - Sanitise for the target encoding mode

Output Safety

  • Serve generated QR code images with correct Content-Type headers
  • Set Content-Disposition headers for downloads
  • Do not embed user input in SVG without XML escaping (XSS risk)
  • Rate-limit QR code generation API endpoints to prevent abuse

Secret Handling

For QR codes containing sensitive data (2FA secrets, payment addresses):

  • Generate QR codes in memory — do not write to disk
  • Serve over HTTPS only
  • Set no-cache headers to prevent browser caching
  • Clear memory after the QR code is delivered
  • Log generation events without logging the sensitive content

HTTPS Enforcement

All QR code URLs should use HTTPS:

  • Encode https:// (not http://) in all URL QR codes
  • Consider HSTS preloading for your domains
  • Use certificate transparency monitoring to detect rogue certificates
  • Redirect HTTP to HTTPS on your servers as a safety net

Injection Prevention

QR code content can be crafted to exploit vulnerabilities in scanner applications:

  • URL injection: Malformed URLs that exploit browser parsers
  • vCard injection: Special characters in contact fields that break parsers
  • Command injection: Unlikely but possible in poorly implemented scanner apps

Mitigate by validating all input against the expected format before encoding.

Key Takeaways

  • Validate all input data before encoding into QR codes
  • Enforce HTTPS for all URL QR codes
  • Handle sensitive QR code data in memory only, never persist to disk
  • Rate-limit generation APIs to prevent abuse
  • Escape user input in SVG output to prevent XSS