Skip to content

About

字体混淆服务

Topics

Resources

Stars

173 stars

Watchers

2 watching

Forks

Repository files navigation

font_obfuscator

Rust CI License CodeRabbit Pull Request Reviews

中文 | English


中文

简介

字体混淆反爬虫工具。通过重映射字体中的字形(glyph),使 HTML 中的文本与用户看到的内容不同,从而防止爬虫直接抓取页面文字。

支持混淆英文、数字及大部分 CJK(中日韩)字符,生成 TTF 和 WOFF2 格式的字体文件。

使用 Rust 实现,基于 Google fontations 项目进行字体解析和构建。

原理

普通混淆:用户提供明文和阴书(长度相同),生成一个自定义字体,其中阴书字符的 Unicode 码位指向明文字符的字形。HTML 中写阴书文本,浏览器加载自定义字体后渲染出明文内容,爬虫只能读到阴书。

加强混淆:只需提供明文,自动使用 Unicode Private Use Area(U+E000-U+F8FF)的随机码位进行映射,并返回对应的 HTML entity 编码。爬虫无法通过 Unicode 表反查字符含义。

快速开始

# 构建
cargo build --release

# 运行(默认监听 127.0.0.1:1323)
./target/release/font_obfuscator

# 自定义端口
PORT=8080 ./target/release/font_obfuscator

环境变量

变量 默认值 说明
PORT 1323 服务监听端口
LISTEN_ADDR 127.0.0.1 服务监听地址
BASE_FONT_PATH base-font/KaiGenGothicCN-Regular.ttf 基础字体文件路径
MAX_CHARS 3000 单次请求去重后的最大字符数(加强混淆另受私用区 6400 个码位限制)
MAX_CONCURRENCY CPU 核数 同时生成字体的最大任务数(上限 1024),超出的请求排队等待
FONT_FAMILY_NAME MyAwesomeFont 关闭加固(harden: false)时写入字体的字体名(所有模式;加固时使用随机名称)
FONT_COPYRIGHT Created by solarhell 同上,版权信息
FONT_VENDOR_URL https://solarhell.com/ 同上,厂商网址

启动时会校验基础字体(能否解析、是否为 TrueType 轮廓、必需的表是否齐全),不可用则直接退出,而不是让每个请求都失败。

API

GET /

健康检查,返回 it works。

POST /api/encrypt

普通混淆(明文 + 阴书)。生成的字体只包含映射的字符。

设置 keep_all: true 可保留原字体中的所有字符,仅替换指定字符的字形(#97)。

curl -X POST http://127.0.0.1:1323/api/encrypt \
  -H 'Content-Type: application/json' \
  -d '{
    "plaintext": "真0123456789好",
    "shadowtext": "假6982075431的",
    "only_ttf": false,
    "keep_all": false
  }'

响应:

{
  "message": "success",
  "hint": "",
  "response": {
    "base64ed": {
      "ttf": "AAEAAAALAIAAAwA...",
      "woff2": "d09GMgABAAAAA..."
    }
  }
}

POST /api/encrypt-plus

加强混淆(仅需明文)。

curl -X POST http://127.0.0.1:1323/api/encrypt-plus \
  -H 'Content-Type: application/json' \
  -d '{
    "plaintext": "价格998元",
    "only_ttf": false
  }'

响应:

{
  "message": "success",
  "hint": "",
  "response": {
    "base64ed": {
      "ttf": "AAEAAAALAIAAAwA...",
      "woff2": "d09GMgABAAAAA..."
    },
    "html_entities": {
      "价": "&#xeafb",
      "格": "&#xee75",
      "9": "&#xe104",
      "8": "&#xf349",
      "元": "&#xf0d0"
    }
  }
}

请求参数

字段 接口 默认 说明
plaintext 两者 必填 明文
shadowtext /api/encrypt 必填 阴书,去重后长度需与明文一致
only_ttf 两者 必填 为 true 时只返回 TTF,不生成 WOFF2
keep_all /api/encrypt false 保留原字体全部字符,只替换指定字形
harden 两者 true 防指纹加固,见下文;设为 false 时字形轮廓与原字体完全一致

请求本身不合法(含空格/emoji、长度不一致、字体缺字、超出字符上限等)时返回 HTTP 200,message 为 error,hint 说明原因。服务端故障(字体生成失败等)返回 HTTP 500,hint 为 内部错误,详情记录在服务日志中。

防指纹加固(harden)

基础字体都是公开字体,爬虫可以预先对原字体的每个字形轮廓算哈希,再到混淆字体里逐个查表还原文字。默认开启的加固让每次请求生成的字形在结构和数值上都独一无二,肉眼看不出差别:

  • 随机拆分曲线段(精确细分,形状不变,但点数与点序列改变)
  • 每条轮廓随机起点,轮廓顺序随机打乱
  • 以字形中心做微小的随机缩放/错切/平移(≤1.2%)
  • 每个点叠加亚像素级随机偏移(≤0.2% em)
  • 字形顺序随机,字体名随机,厂商 ID、版权、时间戳等可识别信息清空

keep_all 模式下只有被替换的字形会被加固(并清空字体名等标识),其余字形按原字节保留、字形顺序不变——完整字体本身就能通过字形数量识别出基础字体,加固保护的是被替换字形不被按轮廓查表还原。

这能挡住基于轮廓精确匹配和结构匹配的自动还原;对“渲染后 OCR”无效——任何字体方案都挡不住 OCR。

实现说明

  • 字形轮廓经 skrifa 读取:组合字形(如 é、文泉驿中大量由部件组成的汉字)会被展开为完整轮廓;可变字体取默认实例。
  • 生成的字体从基础字体继承 OS/2、hhea、post 等全局度量,包围盒、侧边距极值、maxp 按新字形重新计算,可通过 OTS(Chrome/Firefox 使用的字体校验器)检查。
  • keep_all 模式按字节复制未改动的字形(保留 hinting 与组合字形),但字体名称改为上述配置(或加固时的随机名称)——修改后的字体不沿用原字体名,这也是多数开源字体许可的要求;fvar/STAT/排版表引用的名称(轴名、实例名等)会保留,其中出现的原字体名同样被替换;引用了被替换字形的组合字形会先展开,避免连带变形;可变字体的 gvar 按字形重建:按字节复制的替换字形在各字重下与其显示的字形一致,重新生成轮廓的字形(加固后的字形、被展开的组合字形)不带变化数据,在各字重下保持默认字重的形状;竖排度量 vmtx/vhea 同步更新。
  • WOFF2 不使用可选的 glyf/loca 变换:变换后的数据在部分字体上会被浏览器的 WOFF2 解码器拒绝,体积比变换版本大约 10%。keep_all 生成整套字体的 WOFF2 需要数秒到十余秒(Brotli 最高压缩级别)。

作为 Rust 库使用

use font_obfuscator::{FontConfig, Obfuscator, Options};

let font = std::fs::read("base-font/KaiGenGothicCN-Regular.ttf")?;
let obfuscator = Obfuscator::new(font, FontConfig::default())?; // 会校验基础字体
let files = obfuscator.obfuscate("真好", "假的", &Options::default(), &mut rand::rng())?;
// files.ttf / files.woff2

前端使用示例

<style>
  @font-face {
    font-family: 'ObfuscatedFont';
    src: url(data:font/woff2;base64,d09GMgABAAAAA...) format('woff2');
  }
  .protected {
    font-family: 'ObfuscatedFont';
  }
</style>

<!-- 普通混淆:HTML 中写阴书,用户看到明文 -->
<span class="protected">假6982075431的</span>
<!-- 用户看到的是:真0123456789好 -->

<!-- 加强混淆:HTML 中写 entity 编码 -->
<span class="protected">&#xeafb;&#xee75;&#xe104;&#xe104;&#xf349;&#xf0d0;</span>
<!-- 用户看到的是:价格998元 -->

English

Introduction

A font obfuscation tool for anti-scraping. It remaps glyphs in a font so that the text in HTML differs from what users actually see, preventing crawlers from directly extracting page content.

Supports obfuscation of English, digits, and most CJK characters. Generates TTF and WOFF2 font files.

Built with Rust, using Google's fontations project for font parsing and building.

How It Works

Basic obfuscation: Provide plaintext and shadow text (same length). A custom font is generated where shadow characters' Unicode codepoints map to plaintext characters' glyphs. The HTML contains shadow text, but the browser renders plaintext when the custom font is loaded. Crawlers can only read the shadow text.

Enhanced obfuscation: Only plaintext is needed. Random codepoints from Unicode Private Use Area (U+E000-U+F8FF) are used for mapping, and corresponding HTML entity codes are returned. Crawlers cannot reverse-lookup character meanings from Unicode tables.

Quick Start

# Build
cargo build --release

# Run (listens on 127.0.0.1:1323 by default)
./target/release/font_obfuscator

# Custom port
PORT=8080 ./target/release/font_obfuscator

Environment Variables

Variable Default Description
PORT 1323 Server listening port
LISTEN_ADDR 127.0.0.1 Server listen address
BASE_FONT_PATH base-font/KaiGenGothicCN-Regular.ttf Base font file path
MAX_CHARS 3000 Maximum distinct characters per request (enhanced mode is also capped at the 6400 Private Use Area code points)
MAX_CONCURRENCY CPU cores Maximum fonts generated at once (at most 1024); further requests wait
FONT_FAMILY_NAME MyAwesomeFont Font name written when hardening is off (harden: false), in every mode; hardened fonts get a random name
FONT_COPYRIGHT Created by solarhell Likewise, copyright notice
FONT_VENDOR_URL https://solarhell.com/ Likewise, vendor URL

The base font is checked at startup (parseable, TrueType outlines, required tables present); the server refuses to start with an unusable font instead of failing every request.

API

GET /

Health check, returns it works.

POST /api/encrypt

Basic obfuscation (plaintext + shadow text). The generated font only contains the mapped characters.

Set keep_all: true to preserve all characters from the original font, only replacing the specified character glyphs (#97).

curl -X POST http://127.0.0.1:1323/api/encrypt \
  -H 'Content-Type: application/json' \
  -d '{
    "plaintext": "real0123456789content",
    "shadowtext": "fake6982075431garbage",
    "only_ttf": false,
    "keep_all": false
  }'

Response:

{
  "message": "success",
  "hint": "",
  "response": {
    "base64ed": {
      "ttf": "AAEAAAALAIAAAwA...",
      "woff2": "d09GMgABAAAAA..."
    }
  }
}

POST /api/encrypt-plus

Enhanced obfuscation (plaintext only).

curl -X POST http://127.0.0.1:1323/api/encrypt-plus \
  -H 'Content-Type: application/json' \
  -d '{
    "plaintext": "price998usd",
    "only_ttf": false
  }'

Response:

{
  "message": "success",
  "hint": "",
  "response": {
    "base64ed": {
      "ttf": "AAEAAAALAIAAAwA...",
      "woff2": "d09GMgABAAAAA..."
    },
    "html_entities": {
      "p": "&#xeafb",
      "r": "&#xee75",
      "i": "&#xe104",
      "c": "&#xf349",
      "e": "&#xf0d0",
      "9": "&#xe832",
      "8": "&#xef11",
      "u": "&#xe5a3",
      "s": "&#xf721",
      "d": "&#xe009"
    }
  }
}

Request Fields

Field Endpoint Default Description
plaintext both required Plain text
shadowtext /api/encrypt required Shadow text; after de-duplication it must have the same length as the plain text
only_ttf both required When true, only TTF is returned (no WOFF2)
keep_all /api/encrypt false Keep every character of the base font and only replace the given glyphs
harden both true Anti-fingerprinting hardening (see below); with false the outlines match the base font exactly

Invalid requests (spaces/emoji, length mismatch, characters missing from the font, too many characters, …) get HTTP 200 with message: "error" and the reason in hint. Server-side failures (e.g. font generation) get HTTP 500 with hint: "内部错误"; details go to the server log.

Anti-Fingerprinting (harden)

The base fonts are public, so a crawler can hash every glyph outline of the base font once and map an obfuscated font back to text by looking the hashes up. Hardening (on by default) makes every generated glyph structurally and numerically unique while looking the same:

  • segments are split at random positions (exact subdivision: same shape, different points)
  • every contour starts at a random point and contour order is shuffled
  • a small random scale/shear/offset around the glyph centre (≤1.2%)
  • a sub-pixel random offset per point (≤0.2% em)
  • random glyph order and font name; vendor ID, copyright and timestamps are cleared

In keep_all mode only the replaced glyphs are hardened (and the font name and other identifiers cleared); all other glyphs keep their original bytes and glyph order. A full font reveals its base font through its glyph count anyway; hardening keeps the replaced glyphs from being looked up by outline.

This defeats exact and structural outline matching. It does not defeat rendering the text and running OCR, which no font technique can prevent.

Implementation Notes

  • Outlines are read with skrifa: composite glyphs (e.g. é, or the many component-built CJK glyphs in WenQuanYi) are flattened; variable fonts use their default instance.
  • Generated fonts inherit global metrics (OS/2, hhea, post) from the base font; bounding boxes, side-bearing extremes and maxp are recomputed from the new glyphs. Output passes OTS, the sanitizer used by Chrome and Firefox.
  • keep_all copies untouched glyphs byte for byte (hinting and composites stay intact) but writes its own font names (configured, or random when hardened): a modified font does not keep the original name, as most open font licenses require. Names referenced by fvar/STAT/layout tables (axis and instance names, …) are kept, with the original family name replaced there too. Composites that use a replaced glyph are flattened first so they keep their shape. For variable fonts gvar is rebuilt per glyph: a replaced glyph copied byte for byte varies like the glyph it shows, while rebuilt outlines (hardened glyphs, flattened composites) carry no variation data and keep the default shape at every weight. Vertical metrics (vmtx/vhea) are updated too.
  • WOFF2 is written without the optional glyf/loca transform, whose output is rejected by the browsers' WOFF2 decoder for some fonts; files are about 10% larger. A full-font WOFF2 in keep_all mode takes several seconds (Brotli at maximum quality).

Using as a Rust Library

use font_obfuscator::{FontConfig, Obfuscator, Options};

let font = std::fs::read("base-font/KaiGenGothicCN-Regular.ttf")?;
let obfuscator = Obfuscator::new(font, FontConfig::default())?; // validates the base font
let files = obfuscator.obfuscate("真好", "假的", &Options::default(), &mut rand::rng())?;
// files.ttf / files.woff2

Frontend Usage

<style>
  @font-face {
    font-family: 'ObfuscatedFont';
    src: url(data:font/woff2;base64,d09GMgABAAAAA...) format('woff2');
  }
  .protected {
    font-family: 'ObfuscatedFont';
  }
</style>

<!-- Basic: HTML contains shadow text, user sees plaintext -->
<span class="protected">fake6982075431garbage</span>
<!-- User sees: real0123456789content -->

<!-- Enhanced: HTML contains entity codes -->
<span class="protected">&#xeafb;&#xee75;&#xe104;&#xf349;&#xf0d0;&#xe832;&#xe832;&#xef11;&#xe5a3;&#xf721;&#xe009;</span>
<!-- User sees: price998usd -->

License

MIT

About

字体混淆服务

Topics

Resources

Stars

173 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages