身份证识别接口(使用appkey和secret)

使用阿里身份证识别接口(使用appkey和secret)

推荐你看一下七牛的文档<编程模型 - 七牛开发者中心>, 明确提出需要一个业务服务器来生成各种token.

同时总结了几个关键的原则:

  • 整个架构中需要一个业务服务器组件。
  • 无论如何,访问密钥(AK/SK)均不得包含在客户端的分发包中(如二进制代码、配置文件或网页中)。
  • SecretKey不得在任何场景中的公网上传输,更不得传输到客户端。
  • 业务服务器端应维持一个用于管理资源元数据的数据库和一个用于管理最终用户账号信息的数据库。
  • 原则上客户端和七牛云存储之间的交互只有上传和下载,不应使用任何其他的API。


作者:aaashun
链接:https://www.zhihu.com/question/24034365/answer/147662419
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

[java] view plain copy
  1. package reco;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.IOException;  
  5. import org.apache.commons.codec.binary.Base64;  
  6. import org.json.JSONObject;  
  7. import org.json.JSONArray;  
  8. import org.json.JSONException;  
  9. public class IDcard {  
  10.     /* 
  11.      * 获取参数的json对象 
  12.      */  
  13.     public static JSONObject getParam(int type, JSONObject dataValue) {  
  14.         JSONObject obj = new JSONObject();  
  15.         try {  
  16.             obj.put("dataType", type);  
  17.             obj.put("dataValue", dataValue);  
  18.         } catch (JSONException e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.         return obj;  
  22.     }  
  23.     /* 
  24.      * 获取参数的json对象 
  25.      */  
  26.     public static JSONObject getParam(int type, String dataValue) {  
  27.         JSONObject obj = new JSONObject();  
  28.         try {  
  29.             obj.put("dataType", type);  
  30.             obj.put("dataValue", dataValue);  
  31.         } catch (JSONException e) {  
  32.             e.printStackTrace();  
  33.         }  
  34.         return obj;  
  35.     }  
  36.     public static void main(String[] args) {  
  37.         String imgFile = "E:/cxf/develop-workspace-new/upadmin/temp/1490854550779.jpg";  
  38.         String serviceURL = "https://dm-51.data.aliyun.com";  
  39.         String akID = "你的appkey";  
  40.         String akSecret = "你的secret";  
  41.         // 对图像进行base64编码  
  42.         String imgBase64 = "";  
  43.         try {  
  44.             File file = new File(imgFile);  
  45.             byte[] content = new byte[(int) file.length()];  
  46.             FileInputStream finputstream = new FileInputStream(file);  
  47.             finputstream.read(content);  
  48.             finputstream.close();  
  49.             imgBase64 = new String(Base64.encodeBase64(content));  
  50.         } catch (IOException e) {  
  51.             e.printStackTrace();  
  52.             return;  
  53.         }  
  54.         // 拼装请求body的json字符串  
  55.         JSONObject requestObj = new JSONObject();  
  56.         try {  
  57.             JSONObject configObj = new JSONObject();  
  58.             JSONObject obj = new JSONObject();  
  59.             JSONArray inputArray = new JSONArray();  
  60.             configObj.put("side""face");  
  61.             obj.put("image", getParam(50, imgBase64));  
  62.             obj.put("configure", getParam(50, configObj.toString()));  
  63.             inputArray.put(obj);  
  64.             requestObj.put("inputs", inputArray);  
  65.         } catch (JSONException e) {  
  66.             e.printStackTrace();  
  67.         }  
  68.         String body = requestObj.toString();  
  69.         String bodys = "{\"inputs\": [{\"image\": {\"dataType\": 50,\"dataValue\": \""+123+"\"},\"configure\": {\"dataType\": 50,\"dataValue\": \"{\\\"side\\\":\\\"face\\\",}\"}}]}";  
  70.         //Sender代码参考 https://help.aliyun.com/document_detail/shujia/OCR/ocr-api/sender.html  
  71.         String result = Sender.sendPost(serviceURL, bodys, akID, akSecret);  
  72.         System.out.println(result);  
  73.         // 解析请求结果  
  74.         try {  
  75.             JSONObject resultObj = new JSONObject(result);  
  76.             JSONArray outputArray = resultObj.getJSONArray("outputs");  
  77.             String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); // 取出结果json字符串  
  78.             JSONObject out = new JSONObject(output);  
  79.             if (out.getBoolean("success")) {  
  80.                 String addr = out.getString("address"); // 获取地址  
  81.                 String name = out.getString("name"); // 获取名字  
  82.                 String num = out.getString("num"); // 获取身份证号  
  83.                 System.out.printf(" name : %s \n num : %s\n address : %s\n", name, num, addr);  
  84.             } else {  
  85.                 System.out.println("predict error");  
  86.             }  
  87.         } catch (JSONException e) {  
  88.             e.printStackTrace();  
  89.         }  
  90.         }  
  91. }  

[java] view plain copy
  1. package reco;  
  2. import java.io.BufferedReader;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.io.PrintWriter;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.URL;  
  9. import java.net.URLConnection;  
  10. import java.security.MessageDigest;  
  11. import java.text.SimpleDateFormat;  
  12. import java.util.Date;  
  13. import java.util.Locale;  
  14. import javax.crypto.spec.SecretKeySpec;  
  15. import sun.misc.BASE64Encoder;  
  16. import javax.crypto.Mac;  
  17. public class Sender {  
  18.     /* 
  19.      * 计算MD5+BASE64 
  20.      */  
  21.     public static String MD5Base64(String s) {  
  22.         if (s == null)  
  23.             return null;  
  24.         String encodeStr = "";  
  25.         byte[] utfBytes = s.getBytes();  
  26.         MessageDigest mdTemp;  
  27.         try {  
  28.             mdTemp = MessageDigest.getInstance("MD5");  
  29.             mdTemp.update(utfBytes);  
  30.             byte[] md5Bytes = mdTemp.digest();  
  31.             BASE64Encoder b64Encoder = new BASE64Encoder();  
  32.             encodeStr = b64Encoder.encode(md5Bytes);  
  33.         } catch (Exception e) {  
  34.             throw new Error("Failed to generate MD5 : " + e.getMessage());  
  35.         }  
  36.         return encodeStr;  
  37.     }  
  38.     /* 
  39.      * 计算 HMAC-SHA1 
  40.      */  
  41.     public static String HMACSha1(String data, String key) {  
  42.         String result;  
  43.         try {  
  44.             // System.out.println("data: " + data);  
  45.             // System.out.println("key: " + key);  
  46.             SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");  
  47.             Mac mac = Mac.getInstance("HmacSHA1");  
  48.             mac.init(signingKey);  
  49.             byte[] rawHmac = mac.doFinal(data.getBytes());  
  50.             result = (new BASE64Encoder()).encode(rawHmac);  
  51.         } catch (Exception e) {  
  52.             throw new Error("Failed to generate HMAC : " + e.getMessage());  
  53.         }  
  54.         return result;  
  55.     }  
  56.     /* 
  57.      * 等同于javaScript中的 new Date().toUTCString(); 
  58.      */  
  59.     public static String toGMTString(Date date) {  
  60.         SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);  
  61.         df.setTimeZone(new java.util.SimpleTimeZone(0"GMT"));  
  62.         return df.format(date);  
  63.     }  
  64.     /* 
  65.      * 发送POST请求 
  66.      */  
  67.     public static String sendPost(String url, String body, String ak_id, String ak_secret) {  
  68.         PrintWriter out = null;  
  69.         BufferedReader in = null;  
  70.         String result = "";  
  71.         try {  
  72.             URL realUrl = new URL(url);  
  73.             /* 
  74.              * http header 参数 
  75.              */  
  76.             String method = "POST";  
  77.             String accept = "json";  
  78.             String content_type = "application/json";  
  79.             String path = realUrl.getFile();  
  80.             String date = toGMTString(new Date());  
  81.             // 1.对body做MD5+BASE64加密  
  82.             String bodyMd5 = MD5Base64(body);  
  83.             String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"  
  84.                     + path;  
  85.             // 2.计算 HMAC-SHA1  
  86.             String signature = HMACSha1(stringToSign, ak_secret);  
  87.             // 3.得到 authorization header  
  88.             String authHeader = "Dataplus " + ak_id + ":" + signature;  
  89.             // 打开和URL之间的连接  
  90.             URLConnection conn = realUrl.openConnection();  
  91.             // 设置通用的请求属性  
  92.             conn.setRequestProperty("accept", accept);  
  93.             conn.setRequestProperty("content-type", content_type);  
  94.             conn.setRequestProperty("date", date);  
  95.             conn.setRequestProperty("Authorization", authHeader);  
  96.             conn.setRequestProperty("Accept-Charset""UTF-8");  
  97.             // 发送POST请求必须设置如下两行  
  98.             conn.setDoOutput(true);  
  99.             conn.setDoInput(true);  
  100.             // 获取URLConnection对象对应的输出流  
  101.             out = new PrintWriter(conn.getOutputStream());  
  102.             // 发送请求参数  
  103.             out.print(body);  
  104.             // flush输出流的缓冲  
  105.             out.flush();  
  106.             // 定义BufferedReader输入流来读取URL的响应  
  107.             InputStream is;  
  108.             HttpURLConnection httpconn = (HttpURLConnection) conn;  
  109.             if (httpconn.getResponseCode() == 200) {  
  110.                 is = httpconn.getInputStream();  
  111.             } else {  
  112.                 is = httpconn.getErrorStream();  
  113.             }  
  114.             InputStreamReader sr = new InputStreamReader(is,"utf-8");  
  115.             in = new BufferedReader(sr);  
  116.             String line;  
  117.             while ((line = in.readLine()) != null) {  
  118.                 result += line;  
  119.             }  
  120.         } catch (Exception e) {  
  121.             System.out.println("发送 POST 请求出现异常!" + e);  
  122.             e.printStackTrace();  
  123.         }  
  124.         // 使用finally块来关闭输出流、输入流  
  125.         finally {  
  126.             try {  
  127.                 if (out != null) {  
  128.                     out.close();  
  129.                 }  
  130.                 if (in != null) {  
  131.                     in.close();  
  132.                 }  
  133.             } catch (IOException ex) {  
  134.                 ex.printStackTrace();  
  135.             }  
  136.         }  
  137.         return result;  
  138.     }  
  139. }  
[java] view plain copy
  1. package reco;  
  2. import java.io.UnsupportedEncodingException;  
  3. import java.net.URLEncoder;  
  4. import java.security.KeyManagementException;  
  5. import java.security.NoSuchAlgorithmException;  
  6. import java.security.cert.X509Certificate;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10.   
  11. import javax.net.ssl.SSLContext;  
  12. import javax.net.ssl.TrustManager;  
  13. import javax.net.ssl.X509TrustManager;  
  14.   
  15. import org.apache.commons.lang.StringUtils;  
  16. import org.apache.http.HttpResponse;  
  17. import org.apache.http.NameValuePair;  
  18. import org.apache.http.client.HttpClient;  
  19. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  20. import org.apache.http.client.methods.HttpDelete;  
  21. import org.apache.http.client.methods.HttpGet;  
  22. import org.apache.http.client.methods.HttpPost;  
  23. import org.apache.http.client.methods.HttpPut;  
  24. import org.apache.http.conn.ClientConnectionManager;  
  25. import org.apache.http.conn.scheme.Scheme;  
  26. import org.apache.http.conn.scheme.SchemeRegistry;  
  27. import org.apache.http.conn.ssl.SSLSocketFactory;  
  28. import org.apache.http.entity.ByteArrayEntity;  
  29. import org.apache.http.entity.StringEntity;  
  30. import org.apache.http.impl.client.DefaultHttpClient;  
  31. import org.apache.http.message.BasicNameValuePair;  
  32.   
  33. public class HttpUtils {  
  34.       
  35.     /** 
  36.      * get 
  37.      *  
  38.      * @param host 
  39.      * @param path 
  40.      * @param method 
  41.      * @param headers 
  42.      * @param querys 
  43.      * @return 
  44.      * @throws Exception 
  45.      */  
  46.     public static HttpResponse doGet(String host, String path, String method,   
  47.             Map<String, String> headers,   
  48.             Map<String, String> querys)  
  49.             throws Exception {        
  50.         HttpClient httpClient = wrapClient(host);  
  51.   
  52.         HttpGet request = new HttpGet(buildUrl(host, path, querys));  
  53.         for (Map.Entry<String, String> e : headers.entrySet()) {  
  54.             request.addHeader(e.getKey(), e.getValue());  
  55.         }  
  56.           
  57.         return httpClient.execute(request);  
  58.     }  
  59.       
  60.     /** 
  61.      * post form 
  62.      *  
  63.      * @param host 
  64.      * @param path 
  65.      * @param method 
  66.      * @param headers 
  67.      * @param querys 
  68.      * @param bodys 
  69.      * @return 
  70.      * @throws Exception 
  71.      */  
  72.     public static HttpResponse doPost(String host, String path, String method,   
  73.             Map<String, String> headers,   
  74.             Map<String, String> querys,   
  75.             Map<String, String> bodys)  
  76.             throws Exception {        
  77.         HttpClient httpClient = wrapClient(host);  
  78.   
  79.         HttpPost request = new HttpPost(buildUrl(host, path, querys));  
  80.         for (Map.Entry<String, String> e : headers.entrySet()) {  
  81.             request.addHeader(e.getKey(), e.getValue());  
  82.         }  
  83.   
  84.         if (bodys != null) {  
  85.             List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();  
  86.   
  87.             for (String key : bodys.keySet()) {  
  88.                 nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));  
  89.             }  
  90.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");  
  91.             formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");  
  92.             request.setEntity(formEntity);  
  93.         }  
  94.   
  95.         return httpClient.execute(request);  
  96.     }     
  97.       
  98.     /** 
  99.      * Post String 
  100.      *  
  101.      * @param host 
  102.      * @param path 
  103.      * @param method 
  104.      * @param headers 
  105.      * @param querys 
  106.      * @param body 
  107.      * @return 
  108.      * @throws Exception 
  109.      */  
  110.     public static HttpResponse doPost(String host, String path, String method,   
  111.             Map<String, String> headers,   
  112.             Map<String, String> querys,   
  113.             String body)  
  114.             throws Exception {        
  115.         HttpClient httpClient = wrapClient(host);  
  116.   
  117.         HttpPost request = new HttpPost(buildUrl(host, path, querys));  
  118.         for (Map.Entry<String, String> e : headers.entrySet()) {  
  119.             request.addHeader(e.getKey(), e.getValue());  
  120.         }  
  121.   
  122.         if (StringUtils.isNotBlank(body)) {  
  123.             request.setEntity(new StringEntity(body, "utf-8"));  
  124.         }  
  125.   
  126.         return httpClient.execute(request);  
  127.     }  
  128.       
  129.     /** 
  130.      * Post stream 
  131.      *  
  132.      * @param host 
  133.      * @param path 
  134.      * @param method 
  135.      * @param headers 
  136.      * @param querys 
  137.      * @param body 
  138.      * @return 
  139.      * @throws Exception 
  140.      */  
  141.     public static HttpResponse doPost(String host, String path, String method,   
  142.             Map<String, String> headers,   
  143.             Map<String, String> querys,   
  144.             byte[] body)  
  145.             throws Exception {        
  146.         HttpClient httpClient = wrapClient(host);  
  147.   
  148.         HttpPost request = new HttpPost(buildUrl(host, path, querys));  
  149.         for (Map.Entry<String, String> e : headers.entrySet()) {  
  150.             request.addHeader(e.getKey(), e.getValue());  
  151.         }  
  152.   
  153.         if (body != null) {  
  154.             request.setEntity(new ByteArrayEntity(body));  
  155.         }  
  156.   
  157.         return httpClient.execute(request);  
  158.     }  
  159.       
  160.     /** 
  161.      * Put String 
  162.      * @param host 
  163.      * @param path 
  164.      * @param method 
  165.      * @param headers 
  166.      * @param querys 
  167.      * @param body 
  168.      * @return 
  169.      * @throws Exception 
  170.      */  
  171.     public static HttpResponse doPut(String host, String path, String method,   
  172.             Map<String, String> headers,   
  173.             Map<String, String> querys,   
  174.             String body)  
  175.             throws Exception {        
  176.         HttpClient httpClient = wrapClient(host);  
  177.   
  178.         HttpPut request = new HttpPut(buildUrl(host, path, querys));  
  179.         for (Map.Entry<String, String> e : headers.entrySet()) {  
  180.             request.addHeader(e.getKey(), e.getValue());  
  181.         }  
  182.   
  183.         if (StringUtils.isNotBlank(body)) {  
  184.             request.setEntity(new StringEntity(body, "utf-8"));  
  185.         }  
  186.   
  187.         return httpClient.execute(request);  
  188.     }  
  189.       
  190.     /** 
  191.      * Put stream 
  192.      * @param host 
  193.      * @param path 
  194.      * @param method 
  195.      * @param headers 
  196.      * @param querys 
  197.      * @param body 
  198.      * @return 
  199.      * @throws Exception 
  200.      */  
  201.     public static HttpResponse doPut(String host, String path, String method,   
  202.             Map<String, String> headers,   
  203.             Map<String, String> querys,   
  204.             byte[] body)  
  205.             throws Exception {        
  206.         HttpClient httpClient = wrapClient(host);  
  207.   
  208.         HttpPut request = new HttpPut(buildUrl(host, path, querys));  
  209.         for (Map.Entry<String, String> e : headers.entrySet()) {  
  210.             request.addHeader(e.getKey(), e.getValue());  
  211.         }  
  212.   
  213.         if (body != null) {  
  214.             request.setEntity(new ByteArrayEntity(body));  
  215.         }  
  216.   
  217.         return httpClient.execute(request);  
  218.     }  
  219.       
  220.     /** 
  221.      * Delete 
  222.      *   
  223.      * @param host 
  224.      * @param path 
  225.      * @param method 
  226.      * @param headers 
  227.      * @param querys 
  228.      * @return 
  229.      * @throws Exception 
  230.      */  
  231.     public static HttpResponse doDelete(String host, String path, String method,   
  232.             Map<String, String> headers,   
  233.             Map<String, String> querys)  
  234.             throws Exception {        
  235.         HttpClient httpClient = wrapClient(host);  
  236.   
  237.         HttpDelete request = new HttpDelete(buildUrl(host, path, querys));  
  238.         for (Map.Entry<String, String> e : headers.entrySet()) {  
  239.             request.addHeader(e.getKey(), e.getValue());  
  240.         }  
  241.           
  242.         return httpClient.execute(request);  
  243.     }  
  244.       
  245.     private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {  
  246.         StringBuilder sbUrl = new StringBuilder();  
  247.         sbUrl.append(host);  
  248.         if (!StringUtils.isBlank(path)) {  
  249.             sbUrl.append(path);  
  250.         }  
  251.         if (null != querys) {  
  252.             StringBuilder sbQuery = new StringBuilder();  
  253.             for (Map.Entry<String, String> query : querys.entrySet()) {  
  254.                 if (0 < sbQuery.length()) {  
  255.                     sbQuery.append("&");  
  256.                 }  
  257.                 if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {  
  258.                     sbQuery.append(query.getValue());  
  259.                 }  
  260.                 if (!StringUtils.isBlank(query.getKey())) {  
  261.                     sbQuery.append(query.getKey());  
  262.                     if (!StringUtils.isBlank(query.getValue())) {  
  263.                         sbQuery.append("=");  
  264.                         sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));  
  265.                     }                     
  266.                 }  
  267.             }  
  268.             if (0 < sbQuery.length()) {  
  269.                 sbUrl.append("?").append(sbQuery);  
  270.             }  
  271.         }  
  272.           
  273.         return sbUrl.toString();  
  274.     }  
  275.       
  276.     private static HttpClient wrapClient(String host) {  
  277.         HttpClient httpClient = new DefaultHttpClient();  
  278.         if (host.startsWith("https://")) {  
  279.             sslClient(httpClient);  
  280.         }  
  281.           
  282.         return httpClient;  
  283.     }  
  284.       
  285.     private static void sslClient(HttpClient httpClient) {  
  286.         try {  
  287.             SSLContext ctx = SSLContext.getInstance("TLS");  
  288.             X509TrustManager tm = new X509TrustManager() {  
  289.                 public X509Certificate[] getAcceptedIssuers() {  
  290.                     return null;  
  291.                 }  
  292.                 public void checkClientTrusted(X509Certificate[] xcs, String str) {  
  293.                       
  294.                 }  
  295.                 public void checkServerTrusted(X509Certificate[] xcs, String str) {  
  296.                       
  297.                 }  
  298.             };  
  299.             ctx.init(nullnew TrustManager[] { tm }, null);  
  300.             SSLSocketFactory ssf = new SSLSocketFactory(ctx);  
  301.             ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  302.             ClientConnectionManager ccm = httpClient.getConnectionManager();  
  303.             SchemeRegistry registry = ccm.getSchemeRegistry();  
  304.             registry.register(new Scheme("https"443, ssf));  
  305.         } catch (KeyManagementException ex) {  
  306.             throw new RuntimeException(ex);  
  307.         } catch (NoSuchAlgorithmException ex) {  
  308.             throw new RuntimeException(ex);  
  309.         }  
  310.     }  
  311. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值