NFCcreate-web/linux64_release/API_DOCUMENTATION.md
2025-09-25 19:04:00 +08:00

328 lines
7.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# NTAG424 CMAC 驗證 API 文檔
## 概述
NTAG424 CMAC 驗證 API 是一個 HTTP 服務,提供 NTAG424 卡片的 CMACCipher-based Message Authentication Code驗證功能。這個 API 允許遠端驗證 NTAG424 卡片的真實性,無需直接存取讀卡機硬體。
## 功能特點
-**純軟體驗證**:無需讀卡機硬體,僅需 UID、計數器、CMAC 和金鑰索引
-**HTTP RESTful API**:標準 HTTP GET 請求,易於整合
-**JSON 回應格式**:結構化資料回應,易於程式處理
-**多金鑰支援**:支援 1-10 個不同的 AES 金鑰
-**CORS 支援**:跨域請求支援,適合 Web 應用程式
-**詳細錯誤處理**:提供清晰的錯誤訊息和狀態碼
-**多執行緒支援**:同時處理多個請求
## 快速開始
### 1. 啟動服務器
```bash
# 使用預設端口 8080
./cmac_api_server
# 或指定自訂端口
./cmac_api_server 8888
```
### 2. 基本驗證請求
```bash
curl "http://localhost:8888/verify?uid=0456735AD51F90&ctr=000028&cmac=222ED1BA962F7F5C&key=1"
```
## API 端點
### 1. `/verify` - CMAC 驗證
**方法**: `GET`
**用途**: 驗證 NTAG424 卡片的 CMAC
#### 查詢參數
| 參數 | 類型 | 必填 | 說明 | 範例 |
|--------|--------|------|----------------------------------------------|--------------------|
| `uid` | string | ✅ | 卡片 UID (14 位十六進位字元) | `0456735AD51F90` |
| `ctr` | string | ✅ | SDM 讀取計數器 (6 位十六進位字元) | `000028` |
| `cmac` | string | ✅ | CMAC 值 (16 位十六進位字元) | `222ED1BA962F7F5C` |
| `key` | int | ✅ | 金鑰索引 (1-10) | `1` |
#### 成功回應 (200 OK)
```json
{
"success": true,
"message": "CMAC verification successful",
"timestamp": "2025-07-04T15:30:14Z",
"details": {
"uid": "0456735AD51F90",
"counter": "000028",
"cmac": "222ED1BA962F7F5C",
"key_index": 1
}
}
```
#### 驗證失敗回應 (200 OK)
```json
{
"success": false,
"message": "CMAC verification failed (status: 0x000000CA)",
"timestamp": "2025-07-04T15:30:14Z"
}
```
#### 錯誤回應 (400 Bad Request)
```json
{
"success": false,
"message": "Invalid UID format - must be 14 hex characters",
"timestamp": "2025-07-04T15:30:14Z"
}
```
### 2. `/health` - 健康檢查
**方法**: `GET`
**用途**: 檢查 API 服務狀態
#### 回應 (200 OK)
```json
{
"success": true,
"message": "CMAC Verification API is running",
"timestamp": "2025-07-04T15:30:14Z",
"version": "1.0",
"endpoints": ["/verify", "/health"]
}
```
### 3. `/` - 首頁
**方法**: `GET`
**用途**: 顯示 API 說明頁面
回應 HTML 格式的說明頁面,包含可用端點和使用範例。
## 錯誤碼
| HTTP 狀態碼 | 說明 |
|-------------|---------------------|
| 200 | 請求成功(包含驗證失敗) |
| 400 | 請求參數錯誤 |
| 405 | 不允許的 HTTP 方法 |
| 500 | 內部服務器錯誤 |
## 使用範例
### cURL 範例
```bash
# 基本驗證
curl "http://localhost:8888/verify?uid=0456735AD51F90&ctr=000028&cmac=222ED1BA962F7F5C&key=1"
# 使用不同金鑰
curl "http://localhost:8888/verify?uid=0456735AD51F90&ctr=000028&cmac=222ED1BA962F7F5C&key=2"
# 健康檢查
curl "http://localhost:8888/health"
```
### JavaScript 範例
```javascript
// 驗證 CMAC
async function verifyCMAC(uid, ctr, cmac, key) {
const url = `http://localhost:8888/verify?uid=${uid}&ctr=${ctr}&cmac=${cmac}&key=${key}`;
try {
const response = await fetch(url);
const result = await response.json();
if (result.success) {
console.log('✅ CMAC 驗證成功');
return true;
} else {
console.log('❌ CMAC 驗證失敗:', result.message);
return false;
}
} catch (error) {
console.error('請求失敗:', error);
return false;
}
}
// 使用範例
verifyCMAC('0456735AD51F90', '000028', '222ED1BA962F7F5C', 1);
```
### Python 範例
```python
import requests
import json
def verify_cmac(uid, ctr, cmac, key, host='localhost', port=8888):
"""驗證 NTAG424 CMAC"""
url = f"http://{host}:{port}/verify"
params = {
'uid': uid,
'ctr': ctr,
'cmac': cmac,
'key': key
}
try:
response = requests.get(url, params=params, timeout=5)
result = response.json()
if result['success']:
print(f"✅ CMAC 驗證成功: {result['message']}")
return True
else:
print(f"❌ CMAC 驗證失敗: {result['message']}")
return False
except requests.RequestException as e:
print(f"請求錯誤: {e}")
return False
# 使用範例
verify_cmac('0456735AD51F90', '000028', '222ED1BA962F7F5C', 1)
```
## 部署說明
### 本地部署
1. **編譯 API 服務器**
```bash
make api-server
```
2. **準備配置檔案**
- 確保 `keys.txt` 檔案包含正確的 AES 金鑰
- 每行一個金鑰32 位十六進位字元
3. **啟動服務器**
```bash
cd linux64_release
./cmac_api_server 8888
```
### ARM 部署
```bash
# 編譯 ARM64 版本
make api-server-arm64
# 編譯 ARM32 版本
make api-server-arm32
# 複製到 ARM 設備並啟動
./cmac_api_server 8888
```
### 服務化部署
創建 systemd 服務檔案 `/etc/systemd/system/cmac-api.service`
```ini
[Unit]
Description=NTAG424 CMAC Verification API
After=network.target
[Service]
Type=simple
User=your-user
WorkingDirectory=/path/to/linux64_release
ExecStart=/path/to/linux64_release/cmac_api_server 8888
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
```
啟動服務:
```bash
sudo systemctl enable cmac-api
sudo systemctl start cmac-api
```
## 安全考量
1. **金鑰保護**
- `keys.txt` 檔案包含敏感的 AES 金鑰
- 設定適當的檔案權限(例如 600
- 避免在日誌中輸出完整金鑰
2. **網路安全**
- 在生產環境中使用 HTTPS
- 考慮使用反向代理(如 nginx
- 實施速率限制和 IP 白名單
3. **輸入驗證**
- API 已實施基本的輸入格式驗證
- 建議在客戶端也進行額外驗證
## 效能資訊
- **記憶體使用**:約 ~500KB
- **CPU 使用**:每次驗證 ~1ms
- **並發支援**:最多 10 個同時連接
- **吞吐量**:約 1000+ 驗證/秒(取決於硬體)
## 故障排除
### 常見問題
1. **端口已被使用**
```
bind failed: Address already in use
```
解決:使用不同端口或停止占用程序
2. **找不到金鑰檔案**
```
無法開啟 keys.txt 檔案
```
解決:確保 `keys.txt` 在執行目錄中
3. **連接被拒絕**
- 檢查服務器是否正在運行
- 檢查防火牆設定
- 驗證端口號
### 除錯模式
啟動時可以看到詳細的啟動訊息和請求日誌。
## 技術規格
- **語言**C
- **HTTP 服務器**:自定義輕量級實作
- **JSON 處理**:手動序列化
- **執行緒模型**:每請求一執行緒
- **依賴**uFCoder 函式庫、pthread
## 版本歷史
- **v1.0** (2025-07-04):初始版本
- 基本 CMAC 驗證功能
- HTTP API 介面
- 多金鑰支援
- 錯誤處理
## 授權
本軟體遵循與主專案相同的授權條款。
---
**製作**: 基於 NTAG424 管理工具開發
**更新**: 2025-07-04