1.9 KiB
1.9 KiB
身份证识别(百度 OCR + AES)
调用百度身份证 OCR 接口,对图片做 AES 加密上传,对返回的 result 密文做 Base64 解码 + AES 解密后解析出所需字段。
依赖
- JDK 8+
- fastjson(解析返回 JSON)
配置
从百度控制台获取:
- access_token:OAuth2 获取(或使用 API Key + Secret Key 换 token)
- aesKey:16 位 hex 字符串(控制台身份证 OCR 安全设置里)
使用示例
// 构造识别器(accessToken、aesKey 建议从配置文件或环境变量读取)
IdcardRecognizer recognizer = new IdcardRecognizer(accessToken, aesKey);
// 方式一:本地文件
IdcardRecognizer.IdcardResult result = recognizer.recognize("/path/to/idcard_front.jpg", "front");
if (result != null) {
System.out.println("姓名: " + result.getName());
System.out.println("身份证号: " + result.getIdNumber());
System.out.println("出生: " + result.getBirth());
System.out.println("住址: " + result.getAddress());
// ...
}
// 方式二:上传的图片字节(如 MultipartFile.getBytes())
byte[] imgBytes = ...;
IdcardRecognizer.IdcardResult back = recognizer.recognize(imgBytes, "back");
if (back != null) {
System.out.println("签发机关: " + back.getIssueAuthority());
System.out.println("有效期限: " + back.getValidDate());
}
返回字段说明
- 正面 (side=front):
name姓名、gender性别、nation民族、birth出生、address住址、idNumber公民身份号码 - 反面 (side=back):
issueAuthority签发机关、validDate有效期限
按百度接口约定,请求时 id_card_side 传 front 或 back。
集成到现有后端
将 com.ydoyun.ocr 包拷贝到你的项目中,并加入 fastjson 依赖即可;若项目已使用 Spring,可把 IdcardRecognizer 做成 Bean,accessToken、aesKey 从 @Value 或配置类注入。