ID card identification
Interface description
|
|
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
For video tutorials, see ID card recognition API call tutorial (video version)
Online debugging
Request Description
|
|
---|---|
|
|
|
|
---|---|
|
|
|
|
|
|
|
---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
curl -i -k ' https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token= [Call the token obtained from the authentication interface] ' --data 'id_card_side=front&image=[Picture Base64 encoding, UrlEncode required]' -H 'Content-Type:application/x-www-form-urlencoded'
# encoding:utf-8
import requests import base64 ''' ID card identification ''' request_url = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard "
#Open picture file in binary mode f = open ( '[Local file]' , 'rb' ) img = base64 . b64encode ( f . read ( ) ) params = { "id_card_side" : "front" , "image" : img } access_token = '[Token obtained by calling the authentication interface]' request_url = request_url + "?access_token=" + access_token headers = { 'content-type' : 'application/x-www-form-urlencoded' } response = requests . post ( request_url , data = params , headers = headers )
if response :
print ( response . json ( ) )
package com . baidu . ai . aip ;
import com . baidu . ai . aip . utils . Base64Util ;
import com . baidu . ai . aip . utils . FileUtil ;
import com . baidu . ai . aip . utils . HttpUtil ;
import java . net . URLEncoder ;
/** *ID card identification */
public class Idcard {
/** *Tool class required in important tip code *FileUtil, Base64Util, HttpUtil, GsonUtils * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72 * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3 * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3 *Download */
public static String idcard ( ) {
//Request url
String url = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard " ;
try {
//Local file path
String filePath = [Local file path] ;
byte [ ] imgData = FileUtil . readFileByBytes ( filePath ) ;
String imgStr = Base64Util . encode ( imgData ) ;
String imgParam = URLEncoder . encode ( imgStr , "UTF-8" ) ;
String param = "id_card_side=" + "front" + "&image=" + imgParam ;
//Note that the purpose here is to simplify the encoding and obtain access_token for each request. The online environment access_token has an expiration time, and the client can cache it and retrieve it after expiration.
String accessToken = "[Token obtained by calling the authentication interface]" ;
String result = HttpUtil . post ( url , accessToken , param ) ;
System . out . println ( result ) ;
return result ;
} catch ( Exception e ) { e . printStackTrace ( ) ;
}
return null ;
}
public static void main ( String [ ] args ) {
Idcard . idcard ( ) ;
}
}
# include <iostream>
# include <curl/curl.h>
//Download link of libcurl library: https://curl.haxx.se/download.html
//Download link of jsoncpp library: https://github.com/open-source-parsers/jsoncpp/
const static std :: string request_url = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard " ;
static std :: string idcard_result ;
/** *The curl sends the callback function called by the http request. The returned body in json format is parsed in the callback function, and the parsing result is stored in the global static variable *See the libcurl document for @ param parameter definitions *@ return See the libcurl document for the definition of the return value */
static size_t callback ( void * ptr , size_t size , size_t nmemb , void * stream ) {
//The obtained body is stored in ptr and converted to string format first idcard_result = std :: string ( ( char * ) ptr , size * nmemb ) ;
return size * nmemb ;
}
/** *ID card identification *@ return If the call is successful, 0 will be returned. If an error occurs, other error codes will be returned */
int idcard ( std :: string & json_result , const std :: string & access_token ) { std :: string url = request_url + "?access_token=" + access_token ; CURL * curl = NULL ; CURLcode result_code ;
int is_success ; curl = curl_easy_init ( ) ;
if ( curl ) {
curl_easy_setopt ( curl , CURLOPT_URL , url . data ( ) ) ;
curl_easy_setopt ( curl , CURLOPT_POST , one ) ; curl_httppost * post = NULL ; curl_httppost * last = NULL ;
curl_formadd ( & post , & last , CURLFORM_COPYNAME , "id_card_side" , CURLFORM_COPYCONTENTS , "front" , CURLFORM_END ) ;
curl_formadd ( & post , & last , CURLFORM_COPYNAME , "image" , CURLFORM_COPYCONTENTS , "【base64_img】" , CURLFORM_END ) ;
curl_easy_setopt ( curl , CURLOPT_HTTPPOST , post ) ;
curl_easy_setopt ( curl , CURLOPT_WRITEFUNCTION , callback ) ; result_code = curl_easy_perform ( curl ) ;
if ( result_code != CURLE_OK ) {
fprintf ( stderr , "curl_easy_perform() failed: %s\n" ,
curl_easy_strerror ( result_code ) ) ; is_success = one ;
return is_success ;
} json_result = idcard_result ;
curl_easy_cleanup ( curl ) ; is_success = zero ;
} else {
fprintf ( stderr , "curl_easy_init() failed." ) ; is_success = one ;
}
return is_success ;
}
<? php
/** *Initiate http post requests (REST APIs) and obtain the results of REST requests * @param string $url * @param string $param * @return - http response body if succeeds, else false. */
function request_post ( $url = '' , $param = '' )
{
if ( empty ( $url ) || empty ( $param ) ) {
return false ;
}
$postUrl = $url ;
$curlPost = $param ;
//Initialize curl
$curl = curl_init ( ) ;
curl_setopt ( $curl , CURLOPT_URL , $postUrl ) ;
curl_setopt ( $curl , CURLOPT_HEADER , zero ) ;
//The result is required to be a string and output to the screen
curl_setopt ( $curl , CURLOPT_RETURNTRANSFER , one ) ;
curl_setopt ( $curl , CURLOPT_SSL_VERIFYPEER , false ) ;
//Post submission method
curl_setopt ( $curl , CURLOPT_POST , one ) ;
curl_setopt ( $curl , CURLOPT_POSTFIELDS , $curlPost ) ;
//Run curl
$data = curl_exec ( $curl ) ;
curl_close ( $curl ) ;
return $data ;
}
$token = '[Token obtained by calling the authentication interface]' ;
$url = ' https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token= ' . $token ;
$img = file_get_contents ( '[Local file path]' ) ;
$img = base64_encode ( $img ) ;
$bodys = array (
'id_card_side' = > "front" ,
'image' = > $img
) ;
$res = request_post ( $url , $bodys ) ;
var_dump ( $res ) ;
using System ;
using System . IO ;
using System . Net ;
using System . Text ;
using System . Web ;
namespace com . baidu . ai {
public class Idcard
{
//ID card identification
public static string idcard ( )
{
string token = "[Token obtained by calling the authentication interface]" ;
string host = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token= " + token ;
Encoding encoding = Encoding . Default ;
HttpWebRequest request = ( HttpWebRequest ) WebRequest . Create ( host ) ; request . Method = "post" ; request . KeepAlive = true ;
//Base64 encoding of pictures
string base64 = getFileBase64 ( [Local picture file] ) ;
String str = "id_card_side=" + "front" + "&image=" + HttpUtility . UrlEncode ( base64 ) ;
byte [ ] buffer = encoding . GetBytes ( str ) ; request . ContentLength = buffer . Length ; request . GetRequestStream ( ) . Write ( buffer , zero , buffer . Length ) ;
HttpWebResponse response = ( HttpWebResponse ) request . GetResponse ( ) ;
StreamReader reader = new StreamReader ( response . GetResponseStream ( ) , Encoding . Default ) ;
string result = reader . ReadToEnd ( ) ; Console . WriteLine ( "ID card identification:" ) ; Console . WriteLine ( result ) ;
return result ;
}
public static String getFileBase64 ( String fileName ) {
FileStream filestream = new FileStream ( fileName , FileMode . Open ) ;
byte [ ] arr = new byte [ filestream . Length ] ; filestream . Read ( arr , zero , ( int ) filestream . Length ) ;
string baser64 = Convert . ToBase64String ( arr ) ; filestream . Close ( ) ;
return baser64 ;
}
}
}
Return description
|
|
|
|
---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
{
"log_id" : "1559208562721579319" ,
"direction" : zero ,
"image_status" : "normal" ,
"photo" : "/9j/4AAQSkZJRgABA......" ,
"photo_location" : {
"width" : one thousand one hundred and eighty-nine ,
"top" : six hundred and thirty-eight ,
"left" : two thousand two hundred and forty-eight ,
"height" : one thousand four hundred and eighty-three
} ,
"card_image" : "/9j/4AAQSkZJRgABA......" ,
"card_location" : {
"top" : three hundred and twenty-eight ,
"left" : two hundred and seventy-five ,
"width" : one thousand three hundred and twenty-nine ,
"height" : five hundred and seventy-one
} ,
"words_result" : {
Address : {
"location" : {
"left" : two hundred and sixty-seven ,
"top" : four hundred and fifty-three ,
"width" : four hundred and fifty-nine ,
"height" : ninety-nine
} ,
"words" : "3889 Hongjing Avenue, Jiangning District, Nanjing"
} ,
"Citizenship ID Number" : {
"location" : {
"left" : four hundred and forty-three ,
"top" : six hundred and eighty-one ,
"width" : five hundred and eighty-nine ,
"height" : forty-five
} ,
"words" : "330881199904173914"
} ,
Birth : {
"location" : {
"left" : two hundred and seventy ,
"top" : three hundred and fifty-five ,
"width" : three hundred and fifty-seven ,
"height" : forty-five
} ,
"words" : "19990417"
} ,
Name : {
"location" : {
"left" : two hundred and sixty-seven ,
"top" : one hundred and seventy-six ,
"width" : one hundred and fifty-two ,
"height" : fifty
} ,
"words" : "Wu Yunlong"
} ,
Gender : {
"location" : {
"left" : two hundred and sixty-nine ,
"top" : two hundred and sixty-two ,
"width" : thirty-three ,
"height" : fifty-two
} ,
"words" : Male
} ,
"Nation" : {
"location" : {
"left" : four hundred and ninety-two ,
"top" : two hundred and seventy-nine ,
"width" : thirty ,
"height" : thirty-seven
} ,
"words" : Han
}
} ,
"words_result_num" : six
}
{
"words_result" : {
"Expiration date" : {
"words" : "20390711" ,
"location" : {
"top" : four hundred and forty-five ,
"left" : five hundred and twenty-three ,
"width" : one hundred and fifty-three ,
"height" : thirty-eight
}
} ,
"Issuing Authority" : {
"words" : "Lufeng Public Security Bureau" ,
"location" : {
"top" : three hundred and seventy-seven ,
"left" : three hundred and thirty-nine ,
"width" : one hundred and ninety-five ,
"height" : thirty-eight
}
} ,
"Date of issue" : {
"words" : "20190606" ,
"location" : {
"top" : four hundred and forty-five ,
"left" : three hundred and forty-three ,
"width" : one hundred and fifty-two ,
"height" : thirty-eight
}
}
} ,
"log_id" : "1559208562721579328" ,
"words_result_num" : three ,
"error_code" : zero ,
"image_status" : "normal"
}
AES encryption
-
Get your AES Key in Baidu Cloud Console "Character Recognition - Application List - Management" -
Use AES Key to encrypt the image to be recognized -
Pass the encrypted image into the interface, and set the request parameter AESEncryption to true -
The interface returns the encrypted identification result, decrypts it using the AES Key, and obtains the clear text identification result
Request Description
|
|
---|---|
|
|
|
|
---|---|
|
|
|
|
|
|
|
---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# -*- coding: utf-8 -*-
#
from urllib import urlencode import base64 from urllib import unquote import requests import json from Crypto . Cipher import AES import binascii ak = "ak"
#API Key for Character Recognition Applications sk = "sk"
#Secret Key of character recognition application aes = 'res'
#Aes key is obtained from console character recognition - application list - application management
class AESCipher :
def __init__ ( self , key ) : self . key = self . get_key ( key )
def get_key ( self , key ) : st = bytearray ( )
for s in key : st . append ( int ( s , sixteen ) )
str = st . decode ( 'utf-8' )
return str
def pad ( self , text ) :
#Filling method, the encrypted content must be a multiple of 16 bytes text_length = len ( text ) amount_to_pad = AES . block_size - ( text_length % AES . block_size )
if amount_to_pad == zero : amount_to_pad = AES . block_size pad = chr ( amount_to_pad )
return text + pad * amount_to_pad def __unpad ( self , text ) :
#Intercept filled characters pad = ord ( text [ - one ] )
return text [ : - pad ]
#Cryptographic function
def encrypt ( self , raw ) : raw = self . pad ( raw ) cipher = AES . new ( self . key , AES . MODE_ECB )
return base64 . b64encode ( cipher . encrypt ( raw ) )
def decrypt ( self , enc ) :
""" Decryption method : param enc: base64 encoded ciphertext str : return: decrypted plaintext str """ cipher = AES . new ( self . key , AES . MODE_ECB )
return self . __unpad ( cipher . decrypt ( enc ) )
def get_accessToken ( ) : url = " https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id= {ak}&client_secret={sk}" . format ( ak = ak , sk = sk ) response = requests . get ( url )
return response . json ( ) [ 'access_token' ] encryptor = AESCipher ( aes ) token = get_accessToken ( )
#Change to the url in the interface document nameurl = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard " url = nameurl + "?access_token={token}" . format ( token = token )
print url f = open ( 'resources/my.jpg' , 'rb' ) d = f . read ( ) r_data = encryptor . encrypt ( d )
#Construct request data format data = { } data [ 'image' ] = r_data data [ 'id_card_side' ] = 'front' data [ 'AESEncry' ] = 'true' headers = { 'content-type' : 'application/x-www-form-urlencoded' } res = requests . post ( url = url , data = data , headers = headers )
#res= json.dumps(res.content, ensure_ascii=False) data = json . loads ( res . content ) result = encryptor . decrypt ( base64 . b64decode ( data [ 'result' ] ) )
print result
package AES ;
import com . alibaba . fastjson . JSONObject ;
import javax . crypto . Cipher ;
import javax . crypto . spec . SecretKeySpec ;
import java . net . URLEncoder ;
import java . util . Base64 ;
public class Idcard {
/** *Tool class required in important tip code *FileUtil, HttpUtil * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3 *Download */
//Request url
static String url = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard " ;
//The aes key is obtained from the console
static String aesKey = "[16 bit aeskey]" ;
static byte [ ] originAesKey = null ;
public static String idcard ( ) {
try {
//Local file path
String filePath = [Local file path] ;
byte [ ] imgData = FileUtil . readFileByBytes ( filePath ) ;
String imgStr = encryptImg ( aesKey , imgData ) ;
String imgParam = URLEncoder . encode ( imgStr , "UTF-8" ) ;
String param = "id_card_side=" + "front" +
"&image=" + imgParam +
"&AESEncry=" + true ;
String accessToken = "[access token]" ;
String encryptResult = HttpUtil . post ( url , accessToken , param ) ;
String decryptResult = parseResult ( encryptResult ) ;
return decryptResult ;
} catch ( Exception e ) { e . printStackTrace ( ) ;
}
return null ;
}
/** *Encrypt pictures * * @param aesKey * @param imgData * @return * @throws Exception */
private static String encryptImg ( String aesKey , byte [ ] imgData ) throws Exception { originAesKey = AesKeyUtil . parseAesKey ( aesKey ) ;
byte [ ] encImgBytes = AesUtil . encrypt ( imgData , originAesKey ) ;
String imgStr = Base64Util . encodeBase64 ( encImgBytes ) ;
return imgStr ;
}
/** *Decryption result * * @param encryptResult * @return * @throws Exception */
private static String parseResult ( String encryptResult ) throws Exception {
JSONObject obj = JSONObject . parseObject ( encryptResult ) ;
String result = obj . getString ( "result" ) ;
byte [ ] arr = Base64Util . decodeBase64 ( result ) ;
String decryptResult = new String ( AesUtil . decrypt ( arr , originAesKey ) ) ;
return decryptResult ;
}
public static void main ( String [ ] args ) {
Idcard . idcard ( ) ;
}
static class AesKeyUtil {
private static final String HEX = "0123456789abcdef" ;
/** *Get native 128 bit aeskey *Because the length of the byte array generated by 8 bits of a byte is 16 * <p> * 16 * 8 = 128 * * @param hex * @return */
public static byte [ ] parseAesKey ( String hex ) throws Exception {
char [ ] data = hex . toCharArray ( ) ;
if ( data . length != sixteen ) {
throw new Exception ( " ase key illegal " ) ;
}
return decode ( hex . toCharArray ( ) ) ;
}
private static byte [ ] decode ( char [ ] data ) throws IllegalArgumentException {
int len = data . length ;
byte [ ] out = new byte [ len ] ;
for ( int i = zero ; i < len ; i ++ ) {
int f = toDigit ( data [ i ] ) ; out [ i ] = ( byte ) ( f ) ;
}
return out ;
}
private static int toDigit ( char ch ) {
return HEX . indexOf ( ch ) ;
}
}
static class AesUtil {
private static final String ALGORITHM = "AES" ;
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding" ;
/** *Aes encryption */
private static byte [ ] encrypt ( byte [ ] src , byte [ ] aesKey ) throws Exception {
Cipher cipher = getCipher ( aesKey , Cipher . ENCRYPT_MODE ) ;
byte [ ] ret = cipher . doFinal ( src ) ;
return ret ;
}
/** *Aes decryption */
public static byte [ ] decrypt ( byte [ ] src , byte [ ] aesKey ) throws Exception {
Cipher cipher = getCipher ( aesKey , Cipher . DECRYPT_MODE ) ;
byte [ ] original = cipher . doFinal ( src ) ;
return original ;
}
private static Cipher getCipher ( byte [ ] aesKey , int mode ) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec ( aesKey , ALGORITHM ) ;
Cipher cipher = Cipher . getInstance ( ALGORITHM_STR ) ; cipher . init ( mode , secretKeySpec ) ;
return cipher ;
}
}
static class Base64Util {
private static Base64 . Encoder ENCODER = Base64 . getEncoder ( ) ;
//Base64 encryption
private static Base64 . Decoder DECODER = Base64 . getDecoder ( ) ;
/** *Base64 encryption * * @param arr * @return */
private static String encodeBase64 ( byte [ ] arr ) {
String base64 = null ;
try { base64 = ENCODER . encodeToString ( arr ) ;
} catch ( Exception e ) {
}
return base64 ;
}
/** *Base64 decryption * * @param str * @return */
public static byte [ ] decodeBase64 ( String str ) {
byte [ ] encodeBase64 = new byte [ zero ] ;
try { encodeBase64 = DECODER . decode ( str ) ;
} catch ( Exception e ) {
}
return encodeBase64 ;
}
}
}
# include <iostream>
# include <map>
# include <curl/curl.h>
# include <cryptopp/aes.h>
# include <cryptopp/filters.h>
# include "json/json.h"
# include "aip/base/base64.h"
# include "cryptopp/hex.h"
# include "openssl/aes.h"
# include <openssl/evp.h>
# include <fstream>
# define KEY_SIZE_16B 16
# define KEY_SIZE_24B 24
# define KEY_SIZE_32B 32
using CryptoPP :: HexEncoder ;
using CryptoPP :: HexDecoder ;
using CryptoPP :: StringSource ;
//Download link of libcurl library: https://curl.haxx.se/download.html
//Download link of jsoncpp library: https://github.com/open-source-parsers/jsoncpp/
//const static std::string request_url = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard ";
//Get token
inline size_t onWriteData ( void * buffer , size_t size , size_t nmemb , void * userp ) { std :: string * str = dynamic_cast < std :: string * > ( ( std :: string * ) userp ) ; str -> append ( ( char * ) buffer , size * nmemb ) ;
return nmemb ;
}
int get_token ( std :: string ak , std :: string sk , std :: string * token ) { CURL * curl = curl_easy_init ( ) ;
struct curl_slist * slist = NULL ; std :: map < std :: string , std :: string > params ; std :: string response ; std :: string error ; params [ "grant_type" ] = "client_credentials" ; params [ "client_id" ] = ak ; params [ "client_secret" ] = sk ; std :: string url = " https://aip.baidubce.com/oauth/2.0/token? "
"grant_type=client_credentials&client_id=" + ak + "&client_secret=" + sk ;
curl_easy_setopt ( curl , CURLOPT_URL , url . c_str ( ) ) ;
curl_easy_setopt ( curl , CURLOPT_HTTPHEADER , slist ) ;
curl_easy_setopt ( curl , CURLOPT_WRITEFUNCTION , onWriteData ) ;
curl_easy_setopt ( curl , CURLOPT_WRITEDATA , & response ) ;
curl_easy_setopt ( curl , CURLOPT_NOSIGNAL , true ) ;
curl_easy_setopt ( curl , CURLOPT_CONNECTTIMEOUT_MS , two thousand ) ;
curl_easy_setopt ( curl , CURLOPT_TIMEOUT_MS , two thousand ) ;
curl_easy_setopt ( curl , CURLOPT_SSL_VERIFYPEER , false ) ;
curl_easy_setopt ( curl , CURLOPT_SSL_VERIFYHOST , false ) ;
curl_easy_setopt ( curl , CURLOPT_VERBOSE , false ) ;
int status_code = curl_easy_perform ( curl ) ;
curl_easy_cleanup ( curl ) ;
curl_slist_free_all ( slist ) ; Json :: CharReaderBuilder crbuilder ; std :: unique_ptr < Json :: CharReader > reader ( crbuilder . newCharReader ( ) ) ; Json :: Value obj ; reader -> parse ( response . data ( ) , response . data ( ) + response . size ( ) , & obj , & error ) ;
* token = obj [ "access_token" ] . asString ( ) ;
return status_code ;
} std :: string JsonToString ( const Json :: Value & root ) {
static Json :: Value def = [ ] ( ) { Json :: Value def ; Json :: StreamWriterBuilder :: setDefaults ( & def ) ; def [ "emitUTF8" ] = true ;
return def ;
} ( ) ; std :: ostringstream stream ; Json :: StreamWriterBuilder stream_builder ; stream_builder . settings_ = def ; //Config emitUTF8 std :: unique_ptr < Json :: StreamWriter > writer ( stream_builder . newStreamWriter ( ) ) ; writer -> write ( root , & stream ) ;
return stream . str ( ) ;
}
int hex_char_value ( char c ) {
if ( c >= '0' && c <= '9' )
return c - '0' ;
else if ( c >= 'a' && c <= 'f' )
return ( c - 'a' + ten ) ;
else if ( c >= 'A' && c <= 'F' )
return ( c - 'A' + ten ) ;
assert ( zero ) ;
return zero ;
} std :: string get_key ( std :: string res ) { std :: string lvStr ;
for ( int i = zero ; i < sixteen ; i ++ ) {
int x = hex_char_value ( res [ i ] ) ;
char c = x ; std :: cout << c ; lvStr . append ( one , c ) ;
}
return lvStr ;
} std :: string ecb_encrypt ( std :: string res , std :: string source ) {
int outlen = zero ;
int i = source . size ( ) / sixteen ;
int tail = source . size ( ) % sixteen ;
if ( tail > zero ) { i ++ ;
}
unsigned char encData [ sixteen * i ] ; EVP_CIPHER_CTX * ctx ; ctx = EVP_CIPHER_CTX_new ( ) ;
EVP_CipherInit_ex ( ctx , EVP_aes_128_ecb ( ) , NULL ,
reinterpret_cast < const unsigned char * > ( get_key ( res ) . c_str ( ) ) , NULL , one ) ;
EVP_CipherUpdate ( ctx , encData , & outlen , reinterpret_cast < const unsigned char * > ( source . c_str ( ) ) , source . size ( ) ) ;
EVP_CipherFinal ( ctx , encData + outlen , & outlen ) ;
EVP_CIPHER_CTX_free ( ctx ) ; std :: string data = aip :: base64_encode ( reinterpret_cast < const char * > ( encData ) , sizeof ( encData ) ) ;
return data ;
} std :: string ecb_decrypt ( std :: string res , std :: string decode ) { std :: string data = aip :: base64_decode ( decode ) ;
int decLen = zero ;
int outlen = zero ;
unsigned char decData [ data . size ( ) ] ; EVP_CIPHER_CTX * ctx2 ; ctx2 = EVP_CIPHER_CTX_new ( ) ;
EVP_CipherInit_ex ( ctx2 , EVP_aes_128_ecb ( ) , NULL , reinterpret_cast < const unsigned char * > ( get_key ( res ) . c_str ( ) ) ,
NULL , zero ) ;
EVP_CipherUpdate ( ctx2 , decData , & outlen , reinterpret_cast < const unsigned char * > ( data . c_str ( ) ) , data . size ( ) ) ; decLen = outlen ;
EVP_CipherFinal ( ctx2 , decData + outlen , & outlen ) ; decLen += outlen ;
EVP_CIPHER_CTX_free ( ctx2 ) ; decData [ decLen ] = '\0' ;
printf ( "decrypt: %s\n" , decData ) ; std :: string result ; result = reinterpret_cast < const char * > ( decData ) ;
return result ;
}
template < class CharT , class Traits , class Allocator > std :: basic_istream < CharT , Traits > & getall ( std :: basic_istream < CharT , Traits > & input , std :: basic_string < CharT , Traits , Allocator > & str ) { std :: ostringstream oss ; oss << input . rdbuf ( ) ; str . assign ( oss . str ( ) ) ;
return input ;
}
inline int get_file_content ( const char * filename , std :: string * out ) { std :: ifstream in ( filename , std :: ios :: in | std :: ios :: binary ) ;
if ( in ) {
getall ( in , * out ) ;
return zero ;
} else {
return - one ;
}
}
/** *ID card identification *@ return If the call is successful, 0 will be returned. If an error occurs, other error codes will be returned */ Json :: Value idcard ( const std :: string & access_token ) { Json :: Value obj ; std :: string url = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token= " + access_token ; CURL * curl = NULL ; CURLcode result_code ;
//Picture content std :: string file_content ;
get_file_content ( "/Users/lidang/pyproject/baidu/aip/api-python-sdk/test/resources/my.jpg" , & file_content ) ;
// std::string base64 = aip::base64_encode(file_content.c_str(), (int) file_content.size()); std :: string res = "e1ad10e3d69689e0" ; std :: string base64 = ecb_encrypt ( res , file_content ) ;
int is_success ; std :: string response ; std :: string error ; curl = curl_easy_init ( ) ;
if ( curl ) {
curl_easy_setopt ( curl , CURLOPT_URL , url . data ( ) ) ;
curl_easy_setopt ( curl , CURLOPT_POST , one ) ; curl_httppost * post = NULL ; curl_httppost * last = NULL ;
curl_formadd ( & post , & last , CURLFORM_COPYNAME , "id_card_side" , CURLFORM_COPYCONTENTS , "front" , CURLFORM_END ) ;
curl_formadd ( & post , & last , CURLFORM_COPYNAME , "image" , CURLFORM_COPYCONTENTS , base64 . c_str ( ) , CURLFORM_END ) ;
curl_formadd ( & post , & last , CURLFORM_COPYNAME , "AESEncry" , CURLFORM_COPYCONTENTS , "true" , CURLFORM_END ) ;
curl_easy_setopt ( curl , CURLOPT_WRITEDATA , & response ) ;
curl_easy_setopt ( curl , CURLOPT_HTTPPOST , post ) ;
curl_easy_setopt ( curl , CURLOPT_WRITEFUNCTION , onWriteData ) ; result_code = curl_easy_perform ( curl ) ;
if ( result_code != CURLE_OK ) {
fprintf ( stderr , "curl_easy_perform() failed: %s\n" ,
curl_easy_strerror ( result_code ) ) ; is_success = one ;
return is_success ;
} Json :: CharReaderBuilder crbuilder ; std :: unique_ptr < Json :: CharReader > reader ( crbuilder . newCharReader ( ) ) ; reader -> parse ( response . data ( ) , response . data ( ) + response . size ( ) , & obj , & error ) ;
curl_easy_cleanup ( curl ) ; is_success = zero ;
return obj ;
} else {
fprintf ( stderr , "curl_easy_init() failed." ) ; is_success = one ;
}
return obj ;
}
int main ( ) {
// aipt::test_ocr();
// aipt::test_kg();
// aipt::test_speech();
// aipt::test_face();
// aipt::test_nlp();
// aipt::test_ocr();
// aipt::test_image_censor();
// aipt::run_test(1); std :: string ak = "ak" ; std :: string sk = "sk" ; std :: string res = "Aeskey of console" ; std :: string output ; std :: string token ;
get_token ( ak , sk , & token ) ; Json :: Value result ; result = idcard ( token ) ; std :: cout << result [ "result" ] ; std :: string data = ecb_decrypt ( res , result [ "result" ] . asString ( ) ) ; std :: cout << data + "\n" ;
// std::string encate = ecb_encrypt(res, "123456789123456789");
// std::cout << encate + "\n";
// std::string decode = ecb_decrypt(res,encate);
// std::cout << decode+"\n";
return zero ;
}
<? php
function buildUrl ( $url , $params )
{
if ( ! empty ( $params ) ) {
$str = http_build_query ( $params ) ;
return $url . ( strpos ( $url , '?' ) === false ? '?' : '&' ) . $str ;
} else {
return $url ;
}
}
function buildHeaders ( $headers )
{
$result = array ( ) ;
foreach ( $headers as $k = > $v ) {
$result [ ] = sprintf ( '%s:%s' , $k , $v ) ;
}
return $result ;
}
function get ( $url , $params = array ( ) , $headers = array ( ) )
{
$url = buildUrl ( $url , $params ) ;
$headers = array_merge ( $headers , buildHeaders ( $headers ) ) ;
$ch = curl_init ( ) ;
curl_setopt ( $ch , CURLOPT_URL , $url ) ;
curl_setopt ( $ch , CURLOPT_HEADER , false ) ;
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , true ) ;
curl_setopt ( $ch , CURLOPT_SSL_VERIFYPEER , false ) ;
curl_setopt ( $ch , CURLOPT_HTTPHEADER , $headers ) ;
$content = curl_exec ( $ch ) ;
$code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE ) ;
if ( $code === zero ) {
throw new Exception ( curl_error ( $ch ) ) ;
}
curl_close ( $ch ) ;
return array (
'code' = > $code ,
'content' = > $content ,
) ;
}
function post ( $url , $data = array ( ) , $headers = array ( ) )
{
$ch = curl_init ( ) ;
var_dump ( $url ) ;
curl_setopt ( $ch , CURLOPT_URL , $url ) ;
curl_setopt ( $ch , CURLOPT_POST , one ) ;
curl_setopt ( $ch , CURLOPT_HEADER , false ) ;
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , true ) ;
curl_setopt ( $ch , CURLOPT_SSL_VERIFYPEER , false ) ;
curl_setopt ( $ch , CURLOPT_HTTPHEADER , $headers ) ;
curl_setopt ( $ch , CURLOPT_POSTFIELDS , is_array ( $data ) ? http_build_query ( $data ) : $data ) ;
$content = curl_exec ( $ch ) ;
$code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE ) ;
if ( $code === zero ) {
throw new Exception ( curl_error ( $ch ) ) ;
}
curl_close ( $ch ) ;
return array (
'code' = > $code ,
'content' = > $content ,
) ;
}
function decrypt ( $sStr , $key )
{
$sStr = base64_decode ( $sStr ) ;
$decrypted = openssl_decrypt ( $sStr , 'AES-128-ECB' , get_key ( $key ) , OPENSSL_RAW_DATA ) ;
return $decrypted ;
}
function encrypt ( $input , $key )
{
$data = openssl_encrypt ( $input , 'AES-128-ECB' , get_key ( $key ) , OPENSSL_RAW_DATA ) ;
$data = base64_encode ( $data ) ;
return $data ;
}
function bytesToStr ( $bytes )
{
$str = '' ;
foreach ( $bytes as $ch ) {
$str . = chr ( $ch ) ;
}
return $str ;
}
function get_key ( $key )
{
$arr = str_split ( $key ) ;
$bytes = array ( ) ;
for ( $i = zero ; $i < count ( $arr ) ; $i ++ ) {
$bytes [ ] = ord ( chr ( hexdec ( $arr [ $i ] ) ) ) ;
}
return bytesToStr ( $bytes ) ;
}
$ak = "ak" ;
$sk = "sk" ;
#Aes key is obtained from console character recognition - application list - application management
$aes = 'res' ;
$response = get ( ' https://aip.baidubce.com/oauth/2.0/token ' , array (
'grant_type' = > 'client_credentials' ,
'client_id' = > $ak ,
'client_secret' = > $sk ,
) ) ;
$obj = json_decode ( $response [ 'content' ] , true ) ;
$token = $obj [ 'access_token' ] ;
$url = ' https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token= ' . $token ;
$img = file_get_contents ( 'idcard.jpg' ) ;
$img_data = encrypt ( $img , $aes ) ;
$data = array ( ) ;
$data [ 'image' ] = $img_data ;
$data [ 'id_card_side' ] = 'front' ;
$data [ 'AESEncry' ] = 'true' ;
$response = post ( $url , $data , array ( ) ) ;
$result = $response [ 'content' ] ;
$book = json_decode ( $result , true ) ;
$res = decrypt ( $book [ "result" ] , $aes ) ;
echo $res ;
//Construct the request data json_decode ($content, true);
using System ;
using NUnit . Framework ;
using System . Text ;
using System . Security . Cryptography ;
using System . IO ;
using System . Net ;
using System . Collections . Generic ;
using Newtonsoft . Json ;
using Newtonsoft . Json . Linq ;
using System . Linq ;
namespace Baidu . Aip {
[ TestFixture ]
public class Demo
{
public static byte [ ] getFileByte ( String fileName )
{
FileStream filestream = new FileStream ( fileName , FileMode . Open ) ;
byte [ ] arr = new byte [ filestream . Length ] ; filestream . Read ( arr , zero , ( int ) filestream . Length ) ; filestream . Close ( ) ;
return arr ;
}
public static string ParseQueryString ( Dictionary < string , string > querys )
{
if ( querys . Count == zero )
return "" ;
return querys . Select ( pair => pair . Key + "=" + pair . Value )
. Aggregate ( ( a , b ) => a + "&" + b ) ;
}
public static string StreamToString ( Stream ss , Encoding enc )
{
string ret ;
using ( var reader = new StreamReader ( ss , enc ) )
{ ret = reader . ReadToEnd ( ) ;
} ss . Close ( ) ;
return ret ;
}
public static JObject OpenApiFetchToken ( string ak , string sk , bool throws = false , bool debugLog = false )
{
var querys = new Dictionary < string , string >
{
{ "grant_type" , "client_credentials" } ,
{ "client_id" , ak } ,
{ "client_secret" , sk }
} ;
var url = string . Format ( "{0}?{1}" , " https://aip.baidubce.com/oauth/2.0/token " , ParseQueryString ( querys ) ) ;
if ( debugLog ) Console . WriteLine ( url ) ;
var webReq = ( HttpWebRequest ) WebRequest . Create ( url ) ;
try
{
var resp = ( HttpWebResponse ) webReq . GetResponse ( ) ;
if ( resp . StatusCode == HttpStatusCode . OK )
{
var respStr = StreamToString ( resp . GetResponseStream ( ) , Encoding . UTF8 ) ;
var obj = JsonConvert . DeserializeObject ( respStr ) as JObject ;
if ( obj [ "access_token" ] != null && obj [ "expires_in" ] != null )
return obj ;
if ( throws )
throw new AipException ( "Failed to request token. " + ( string ) obj [ "error_description" ] ) ;
return null ;
}
if ( throws )
throw new AipException ( "Failed to request token. " + resp . StatusCode + resp . StatusDescription ) ;
}
catch ( Exception e )
{
if ( throws )
throw new AipException ( "Failed to request token. " + e . Message ) ;
return null ;
}
return null ;
}
public static string UrlEncode ( string str )
{
StringBuilder sb = new StringBuilder ( ) ;
byte [ ] byStr = System . Text . Encoding . UTF8 . GetBytes ( str ) ; //The default is System Text.Encoding.Default.GetBytes(str)
for ( int i = zero ; i < byStr . Length ; i ++ )
{ sb . Append ( @"%" + Convert . ToString ( byStr [ i ] , sixteen ) ) ;
}
return ( sb . ToString ( ) ) ;
}
public static string Encrypt ( string toEncrypt , string key )
{
byte [ ] keyArray = GetKey ( key ) ;
byte [ ] toEncryptArray = UTF8Encoding . UTF8 . GetBytes ( toEncrypt ) ; Console . WriteLine ( "Hello World!" + keyArray . Length ) ;
RijndaelManaged rDel = new RijndaelManaged ( ) ; rDel . Key = keyArray ; rDel . Mode = CipherMode . ECB ; rDel . Padding = PaddingMode . PKCS7 ;
ICryptoTransform cTransform = rDel . CreateEncryptor ( ) ;
byte [ ] resultArray = cTransform . TransformFinalBlock ( toEncryptArray , zero , toEncryptArray . Length ) ;
return Convert . ToBase64String ( resultArray , zero , resultArray . Length ) ;
}
public static string Encrypt ( byte [ ] toEncryptArray , string key )
{
byte [ ] keyArray = GetKey ( key ) ; Console . WriteLine ( "Hello World!" + keyArray . Length ) ;
RijndaelManaged rDel = new RijndaelManaged ( ) ; rDel . Key = keyArray ; rDel . Mode = CipherMode . ECB ; rDel . Padding = PaddingMode . PKCS7 ;
ICryptoTransform cTransform = rDel . CreateEncryptor ( ) ;
byte [ ] resultArray = cTransform . TransformFinalBlock ( toEncryptArray , zero , toEncryptArray . Length ) ;
return Convert . ToBase64String ( resultArray , zero , resultArray . Length ) ;
}
public static byte [ ] GetKey ( string key )
{
byte [ ] result = new byte [ key . Length ] ;
char [ ] array = key . ToArray ( ) ;
int i = zero ;
for ( int a = zero ; a < array . Length ; a = a + one )
{
string ch = array [ a ] + "" ;
int val = Convert . ToInt32 ( ch , sixteen ) ; result [ a ] = ( byte ) val ;
}
return result ;
}
/* *AES decryption * */
public static string Decrypt ( string toDecrypt , string key )
{
byte [ ] keyArray = GetKey ( key ) ;
byte [ ] toEncryptArray = Convert . FromBase64String ( toDecrypt ) ;
RijndaelManaged rDel = new RijndaelManaged ( ) ; rDel . Key = keyArray ; rDel . Mode = CipherMode . ECB ; rDel . Padding = PaddingMode . PKCS7 ;
ICryptoTransform cTransform = rDel . CreateDecryptor ( ) ;
byte [ ] resultArray = cTransform . TransformFinalBlock ( toEncryptArray , zero , toEncryptArray . Length ) ;
return UTF8Encoding . UTF8 . GetString ( resultArray ) ;
}
[ Test ]
public void demo ( )
{
string res = "Aeskey of console" ;
string ak = "ak" ;
string sk = "sk" ;
string host = " https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token= " + OpenApiFetchToken ( ak , sk ) [ "access_token" ] ;
//Console. WriteLine("url:"+host);
Encoding encoding = Encoding . Default ;
HttpWebRequest request = ( HttpWebRequest ) WebRequest . Create ( host ) ; request . Method = "post" ; request . KeepAlive = true ;
////Base64 encoding of pictures
byte [ ] file = getFileByte ( Picture Path ) ;
string base64 = Encrypt ( file , res ) ;
string str = "AESEncry=true&id_card_side=" + "front" + "&image=" + UrlEncode ( base64 ) ;
byte [ ] buffer = encoding . GetBytes ( str ) ; request . ContentLength = buffer . Length ; request . GetRequestStream ( ) . Write ( buffer , zero , buffer . Length ) ;
HttpWebResponse response = ( HttpWebResponse ) request . GetResponse ( ) ;
StreamReader reader = new StreamReader ( response . GetResponseStream ( ) , Encoding . Default ) ;
string result = reader . ReadToEnd ( ) ; Console . WriteLine ( "ID card identification:" ) ; Console . WriteLine ( result ) ; Console . WriteLine ( Decrypt ) ;
var obj = JsonConvert . DeserializeObject ( result ) as JObject ;
var content = Decrypt ( ( string ) obj [ "result" ] , res ) ; Console . WriteLine ( content ) ;
}
}
}
Return description
{
"log_id" : "2648325511" ,
"result" : Ciphertext
}