information community file
Technical capability
Voice technology
Character recognition
Face and Human Body
Image technology
Language and knowledge
video technique

ID card identification

Interface description

It supports structured identification of all eight fields on the front and back of the second-generation resident ID card, including name, gender, nationality, date of birth, address, ID card number, issuing authority, and validity period, and the identification accuracy rate exceeds 99%; At the same time, it supports the detection of the front picture of the ID card, and returns the base64 code and location information of the picture slice.

At the same time, it supports image quality and risk detection of ID card pictures uploaded by users to check whether there are quality problems such as reverse, blurring, underexposure, overexposure, etc. It can identify whether the picture is a copy or temporary ID card, whether it has been photographed or edited, whether there are incomplete corners, and whether the avatar or key fields are blocked.

Value added capability details
Cutting ability Head image detection and slicing: return the base64 encoding and location information of the head image slice
ID card detection and slicing: return the base64 code and location information of the ID card (remove the redundant background around the ID card, and automatically correct the shooting angle)
Quality inspection Fuzzy detection of ID card image
Reflective or overexposed key fields of ID card
ID card picture is dark or underexposed
ID card frame/four corners incomplete alarm
ID card avatar or key field is blocked/mosaic alarm
Risk detection ID card copy alarm
Temporary ID card alarm
ID card remake alarm
ID card PS editing alarm
Illegal ID card number alarm
Alarm of inconsistency between ID card number, birth date and gender information

For video tutorials, see ID card recognition API call tutorial (video version)

Online debugging

You can visit Sample Code Center Debug the interface in , you can perform signature verification, view the request content and return results of online calls, and automatically generate sample code.

Request Description

Request Example

HTTP method: POST

Request URL: https://aip.baidubce.com/rest/2.0/ocr/v1/idcard

URL parameter:

parameter value
access_token Access_token obtained through API Key and Secret Key, refer to“ Access Token acquisition

The headers are as follows:

parameter value
Content-Type application/x-www-form-urlencoded

Place the request parameters in the body. The details of the parameters are as follows:

Request Parameters

parameter Required type Optional value range explain
image Or url string - The image data is urlencoded after base64 encoding, and the encoding terminal (data: image/jpeg; base64,) needs to be removed
It is required that the size of base64 encoding and urlencode should not exceed 8M, the shortest side should be at least 15px, and the longest side should be at most 8192px. It supports jpg/jpeg/png/bmp format
url And image string - The image is a complete URL. The URL length does not exceed 1024 bytes. The size of the image corresponding to the URL after base64 encoding does not exceed 8M. The shortest side is at least 15px, and the longest side is at most 8192px. It supports the jpg/jpeg/png/bmp format. When the image field exists, the url field is invalid
Please close the URL anti-theft chain
id_card_side yes string front/back -Front: The photo side of the ID card
-Back: The side of the ID card with the national emblem
Automatically detect the front and back of the ID card. If the specified direction of the parameter transfer is opposite to the picture, normal recognition is supported. The returned parameter image_status field is "reversed_side"
detect_ps no string true/false Whether or not to detect the uploaded ID card is PS. It is not detected by default. Optional values:
-True: Detect
-False: Do not detect
detect_risk no string true/false Whether to enable the detection function of ID card risk type (ID card copy, temporary ID card, ID card remake, modified ID card). It is not enabled by default, that is, false.
-True: enabled. Please check the return parameter risk_type;
-False: Do not open
detect_quality no string true/false Whether to enable the detection function of ID card quality type (clear and fuzzy, incomplete border/four corners, blocked avatar or key fields/mosaic). It is not enabled by default, that is, false.
-True: enabled. Please check the return parameter card_quality;
-False: Do not open
detect_photo no string true/false Whether to detect the content of the avatar. It is not detected by default. Optional value: true - detects the avatar and returns the base64 encoding and location information of the avatar
detect_card no string true/false Whether to check the ID card for clipping. It is not checked by default. Optional value: true - detects the ID card and returns the base64 code and location information of the license
detect_direction no string true/false Whether to detect the direction of the uploaded ID card image. It is not detected by default. Optional values:
-True: Detect
-False: Do not detect

Request Code Example

Prompt 1 : Before using the sample code, remember to replace the sample token, image address or Base64 information.

Prompt 2 : Some languages depend on classes or libraries. Please check the download address in the code comment.

 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

Return parameters

field Required type explain
log_id yes uint64 Unique log ID for problem location
words_result yes array[] Positioning and recognition result array
words_result_num yes uint32 The number of recognition results, representing the number of words_result elements
direction no int32 The image direction is returned when the input parameter detect_direction=true.
-- 1: Undefined,
-0: Forward,
-1: 90 degrees counterclockwise,
-2: 180 degrees counterclockwise,
-3: 270 degrees counterclockwise
image_status yes string Normal - Normal recognition
Reversed_side - ID card upside down
Non_idcard - The uploaded image does not contain an ID card
Blurred - ID card is ambiguous
Other_type_card - Other types of licenses
Over_exposure - reflection or overexposure of key fields of ID card
Over_dark - ID card underexposed (low brightness)
Unknown - Unknown status
card_ps no string When the input parameter detect_ps=true, this field is returned to determine whether the ID card is PS. The return value is:
-0: Normal,
- 1:PS,
-- 1: Invalid
risk_type no string When the input parameter detect_risk=true, this field is returned to identify the ID card Risk type :
Normal normal ID card;
Copy - copy;
Temporary temporary ID card;
Screen remake;
Unknown - Other unknowns
edit_tool no string If the parameter detect_risk=true, this field is returned. If it is detected that the ID card has been edited, this field specifies the name of the editing software, such as Adobe Photoshop CC 2014 (Macintosh). If it has not been edited, the return value does not have this parameter
card_quality no object When the input parameter detect_quality=true, this field is returned to identify the ID card quality type
+ IsClear yes string Whether the quality type is clear
+ IsClear_propobility yes string The probability corresponding to the "Clarity" quality type. The value is between 0-1. The higher the value, the better the image quality. Default threshold (Only the recommended value. It is recommended to set a judgment threshold based on the specific probability value returned from the image according to the actual business scenario.): When IsClear_propractility exceeds 0.5, the corresponding IsClear returns 1. If it is lower than 0.5, the corresponding IsClear returns 0
+ IsComplete yes string Quality type, whether the border/four corners are complete
+ IsComplete_propobility yes string The probability corresponding to the quality type "whether the border/four corners are complete". The value is between 0-1. The higher the value, the better the image quality. Default threshold (Only the recommended value. It is recommended to set a judgment threshold based on the specific probability value returned from the image according to the actual business scenario.): When IsClear_property exceeds 0.5, the corresponding IsComplete returns 1. If it is lower than 0.5, the corresponding IsComplete returns 0
+ IsNoCover yes string Quality type, whether the avatar and key fields are unobstructed/mosaic
+ IsNoCover_propobility yes string The probability corresponding to the quality type of "whether the avatar and key field are unobstructed/mosaic" is between 0-1. The higher the value, the better the image quality. Default threshold (It is only a recommended value, and it is recommended to set a judgment threshold based on the specific probability value returned from the image according to the actual business scenario.): When IsNoCover_propacity exceeds 0.3, the corresponding IsNoCover returns 1, and if it is lower than 0.3, 0 is returned
photo no string When the request parameter detect_photo=true, it returns the base64 code of the head image slice (no editing terminal, which needs to be handled by yourself)
photo_location no object When the request parameter detect_photo=true, the position information of the avatar is returned (coordinate 0 is the upper left corner)
card_image no string When the request parameter detect_card=true, it returns the base64 code of the ID card clipping map (without editing terminal, it needs to be handled by itself)
card_location no object When the request parameter detect_card=true, it returns the location information of the ID card clipping image (coordinate 0 is the upper left corner)
idcard_number_type yes int It is used to verify whether the ID card number, gender and birth are consistent. The output results and their corresponding relationships are as follows:
- 1: All fields on the front of ID card are empty
0: The ID card number is illegal. In this case, the ID card number will not be returned
1: ID card number is consistent with gender and birth information
2: ID card number, gender and birth information are inconsistent
3: Inconsistency between ID card number and birth information
4: Inconsistency between ID card number and gender information
+ location yes array[] Position array (coordinate 0 point is the upper left corner)
++ left yes uint32 The horizontal coordinate of the top left vertex of the rectangle representing the positioning position
++ top yes uint32 The vertical coordinate of the top left vertex of the rectangle representing the positioning position
++ width yes uint32 The width of the rectangle representing the positioning position
++ height yes uint32 The height of the rectangle representing the positioning position
+ words no string Identification result string

Return example (ID card face)

 {
     "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
 }

Return example (national emblem of ID card)

 {
     "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

You can choose to use AES encryption to request the ID card identification interface, which supports the transmission of encrypted ID card pictures and identification results. The schematic diagram is as follows:

 image.png

  1. Get your AES Key in Baidu Cloud Console "Character Recognition - Application List - Management"
  2. Use AES Key to encrypt the image to be recognized
  3. Pass the encrypted image into the interface, and set the request parameter AESEncryption to true
  4. The interface returns the encrypted identification result, decrypts it using the AES Key, and obtains the clear text identification result

The use of AES encryption does not affect the quality detection, risk detection and other capabilities supported by the ID card identification interface, nor does it affect the identification effect.

Request Description

Request Example

HTTP method: POST

Request URL: https://aip.baidubce.com/rest/2.0/ocr/v1/idcard

URL parameter:

parameter value
access_token Access_token obtained through API Key and Secret Key, refer to“ Access Token acquisition

The headers are as follows:

parameter value
Content-Type application/x-www-form-urlencoded

Place the request parameters in the body. The details of the parameters are as follows:

Request Parameters

parameter Required type Optional value range explain
image yes string - The image data encrypted by AES should be urlencode after base64 encoding. The size of the encrypted image after base64 encoding should not exceed 4M, the shortest side should be at least 15px, and the longest side should be at most 4096px. It supports jpg/jpeg/png/bmp format
AESEncry yes string true/false Please pass true when using AES encryption
id_card_side yes string front/back -Front: The photo side of the ID card
-Back: The side of the ID card with the national emblem
Automatically detect the front and back of the ID card. If the specified direction of the parameter transfer is opposite to the picture, normal recognition is supported. The returned parameter image_status field is "reversed_side"
detect_direction no string - The new version of this parameter does not need to be transferred, and supports automatic detection of image rotation angle
detect_risk no string true/false Whether to enable the ID card risk type (ID card copy, temporary ID card, ID card remake, modified ID card) function, which is not enabled by default, that is, false.
-True: enabled. Please check the return parameter risk_type;
-False: Do not open
detect_photo no string true/false Whether to detect the content of the avatar. It is not detected by default. Optional value: true - detects the avatar and returns the base64 encoding and location information of the avatar

Request Code Example

Prompt 1 : Before using the sample code, remember to replace the sample token, image address or Base64 information.

Prompt 2 : Some languages depend on classes or libraries. Please check the download address in the code comment.

 # -*- 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

Return to Example

 {
     "log_id" : "2648325511" ,
     "result" : Ciphertext
 }

Please base 64 decode the result ciphertext to get the byte stream, and then perform AES decryption to get the clear text of the recognition result.

Previous
Universal Scene Text Recognition
Next
ID card mixed paste identification