Java調(diào)用阿里身份證實(shí)現(xiàn)驗(yàn)證接口
0、使用阿里云,需要獲取相應(yīng)的信息
appcode,這個(gè)需要注冊(cè)阿里云然后找到Appcode,將其放入代碼中即可,這里調(diào)用的第三方接口是身份證驗(yàn)證二要素(姓名+身份證)
注意:阿里云提供的這個(gè)身份證驗(yàn)證是有時(shí)間限制的,有效期應(yīng)該是1年,自行查看
1、導(dǎo)入依賴
<!-- 身份證識(shí)別-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>9.3.7.v20160115</version>
</dependency>2、HttpUtils
package com.ww.yaodao.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}3、編寫代碼
該代碼是業(yè)務(wù)層也就是Service層,Controller層直接調(diào)用該方法即可
RegisterVO 為前端傳遞過來(lái)的數(shù)據(jù),該數(shù)據(jù)存放在該RegisterVO 對(duì)象中,這里需要的是真實(shí)姓名和身份證號(hào)也就是下面代碼中的idNo和name
@Override
public int addOneUser(RegisterVO registerVO) {
/*
* 重要提示如下:
* HttpUtils請(qǐng)從
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
* 下載
*
* 相應(yīng)的依賴請(qǐng)參照
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
*/
String host = "https://idenauthen.market.alicloudapi.com";
String path = "/idenAuthentication";
String method = "POST";
String appcode = "第0步中獲取的appcode";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中間是英文空格)為Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
//根據(jù)API的要求,定義相對(duì)應(yīng)的Content-Type
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("idNo", registerVO.getIdentifyCard());
bodys.put("name", registerVO.getUsername());
try {
HttpResponse response =
HttpUtils.doPost(host, path, method, headers, querys, bodys);
if (response.getEntity() != null) {
// 使用md5對(duì)密碼、身份證進(jìn)行加密
registerVO.setPassword(PasswordUtils.generate(registerVO.getPassword()));
registerVO.setIdentifyCard(PasswordUtils.generate(registerVO.getIdentifyCard()));
// 糊涂工具類進(jìn)行拷貝
UserDO userDO = BeanUtil.copyProperties(registerVO, UserDO.class);
userDO.setUtype(1);
userDO.setAid(1);
userDO.setPassword(md5Utils.getEncryptedPwd(registerVO.getPassword()));
int insert = registerMapper.insert(userDO);
return insert;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}4、附:加密驗(yàn)證工具類
package com.ww.yaodao.util;
import org.apache.commons.codec.binary.Hex;
import java.security.MessageDigest;
import java.util.Random;
/**
* MD5加鹽加密
*/
public class PasswordUtils {
/**
* @param password : 密碼明文
* 生成含有隨機(jī)鹽的密碼
*/
public static String generate(String password) {
Random r = new Random();
//sb鹽值 16位
StringBuilder sb = new StringBuilder(16);
sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
int len = sb.length();
if (len < 16) { //不夠16位,前面補(bǔ)0
for (int i = 0; i < 16 - len; i++) {
sb.append("0");
}
}
String salt = sb.toString();
//密碼明文 + 鹽值 使用md5加密
password = md5Hex(password + salt); //32位的16進(jìn)制
// byte[] hashedBytes = md5Hex(password+salt);
char[] cs = new char[48];
//往密文插入鹽值
for (int i = 0; i < 48; i += 3) {
cs[i] = password.charAt(i / 3 * 2); //0
char c = salt.charAt(i / 3); //0
cs[i + 1] = c; //cs[1] = 鹽值1
cs[i + 2] = password.charAt(i / 3 * 2 + 1);
}
return new String(cs);
}
/**
* 校驗(yàn)密碼是否正確
* @param password: 明文
* @param md5: 數(shù)據(jù)庫(kù)密文
* bae5e3208a3c700e3db642b6631e95b9
*/
public static boolean verify(String password, String md5) {
char[] cs1 = new char[32];
char[] cs2 = new char[16];
for (int i = 0; i < 48; i += 3) {
cs1[i / 3 * 2] = md5.charAt(i);
cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
cs2[i / 3] = md5.charAt(i + 1);
}
String salt = new String(cs2);
// (明文+鹽值) 密文 與密文比較
return md5Hex(password + salt).equals(new String(cs1));
}
/**
* 獲取十六進(jìn)制字符串形式的MD5摘要
*/
public static String md5Hex(String src) {
try {
//得到消息摘要對(duì)象
MessageDigest md5 = MessageDigest.getInstance("MD5");
//通過md5算法, 把src字符串, 加密成128位二進(jìn)制
byte[] bs = md5.digest(src.getBytes());
//把128位二進(jìn)制轉(zhuǎn)換為16進(jìn)賬
return new String(new Hex().encode(bs));
} catch (Exception e) {
return null;
}
}
}到此這篇關(guān)于Java調(diào)用阿里身份證實(shí)現(xiàn)驗(yàn)證接口的文章就介紹到這了,更多相關(guān)Java驗(yàn)證接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決SpringBoot加載application.properties配置文件的坑
這篇文章主要介紹了SpringBoot加載application.properties配置文件的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
application.yml的格式寫法和pom.xml讀取配置插件方式
這篇文章主要介紹了application.yml的格式寫法和pom.xml讀取配置插件方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
shiro實(shí)現(xiàn)單點(diǎn)登錄(一個(gè)用戶同一時(shí)刻只能在一個(gè)地方登錄)
這篇文章主要介紹了shiro實(shí)現(xiàn)單點(diǎn)登錄(一個(gè)用戶同一時(shí)刻只能在一個(gè)地方登錄)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起學(xué)習(xí)吧2016-08-08
java?LockSupport實(shí)現(xiàn)原理示例解析
這篇文章主要為大家介紹了java?LockSupport實(shí)現(xiàn)原理示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
深入學(xué)習(xí)java內(nèi)存化和函數(shù)式協(xié)同
這篇文章主要介紹了深入學(xué)習(xí)java內(nèi)存化和函數(shù)式協(xié)同,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下2019-06-06
Spring boot 整合 Okhttp3 并封裝請(qǐng)求工具實(shí)例 詳解
OkHttp作為一款成熟、穩(wěn)定、易用的HTTP客戶端庫(kù),擁有較高的性能和多樣化的功能,已被廣泛應(yīng)用于移動(dòng)應(yīng)用開發(fā)、Web服務(wù)端開發(fā)等領(lǐng)域,這篇文章主要介紹了Spring boot 整合 Okhttp3 并封裝請(qǐng)求工具,需要的朋友可以參考下2023-08-08
關(guān)于LinkedList集合對(duì)元素進(jìn)行增查刪操作
LinkedList集合內(nèi)部包含有兩個(gè)Node類型的first和last屬性維護(hù)一個(gè)雙向循環(huán)鏈表,在鏈表中的每一個(gè)元素都使用引用的方式來(lái)記住它的前一個(gè)元素和后一個(gè)元素,從而可以將所有的元素彼此連接起來(lái),需要的朋友可以參考下2023-04-04

