HTTPS双向认证
生成证书
openssl genrsa -des3 -out server.key 2048
openssl req -new -x509 -key server.key -out ca.crt -days 3650
openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt
1.继承SSLSocketFactory
/**
* Author:JsonLu
* DateTime:2016/5/31 19:46
* Email:jsonlu@qq.com
* Desc:
**/
public class SecureSSLSocketFactory extends SSLSocketFactory { private final SSLContext sslContext = SSLContext.getInstance("TLS"); public SecureSSLSocketFactory(KeyStore keystore, String keystorePassword, KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(keystore, keystorePassword, truststore);
try {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, keystorePassword.toCharArray());
KeyManager[] km = keyManagerFactory.getKeyManagers();
TrustManager[] tm = null;
if (truststore == null) {
tm = new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
} @Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
} };
} else {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(truststore);
tm = trustManagerFactory.getTrustManagers();
}
sslContext.init(km, tm, null);
} catch (Exception e) {
e.printStackTrace();
}
} @Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
} @Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
2.
/**
* Author:JsonLu
* DateTime:2016/5/31 20:02
* Email:jsonlu@qq.com
* Desc:
**/
public class SecureHttpsClient extends DefaultHttpClient { private static KeyStore keyStore,trustStore;
private static String keyStorePwd;
private Context ctx;
private final String KEYSTORE_FILE = "client.p12";
private final String TRUESTSTORE_FILE = "server.p12";
private final String KEYSTORE_PWD = "a123456789";
private final String TRUESTSORE_PWD = "a123456"; public SecureHttpsClient(Context context){
ctx = context;
init(KEYSTORE_FILE,KEYSTORE_PWD,TRUESTSTORE_FILE,TRUESTSORE_PWD);
} public void init(KeyStore keyStore,KeyStore trustStore,String keyStorePwd){
this.keyStore = keyStore;
this.trustStore = trustStore;
this.keyStorePwd = keyStorePwd;
} public void init(String keyStoreFile,String keyStorePwd,String trustStoreFile,String truestStorePwd){
this.keyStore = getKeyStoreByP12(keyStoreFile,keyStorePwd);
this.trustStore = getKeyStoreByP12(trustStoreFile,truestStorePwd);
this.keyStorePwd = keyStorePwd;
} @Override
protected ClientConnectionManager createClientConnectionManager() {
try {
SecureSSLSocketFactory sf = new SecureSSLSocketFactory(keyStore, keyStorePwd, trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return ccm;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public KeyStore getKeyStoreByP12(String p12File, String p12Pwd) {
InputStream p12In = null;
try {
p12In = ctx.getResources().getAssets().open(p12File);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(p12In, p12Pwd.toCharArray());
return keyStore;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (p12In != null) {
p12In.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
3.
/**
* Author:JsonLu
* DateTime:2016/5/31 20:28
* Email:jsonlu@qq.com
* Desc:
**/
public class CallServer { private final String HTTPS_URL = "https://192.168.8.116:8443/"; private DefaultHttpClient getSumpayHttpsClient(Context context) {
SecureHttpsClient client = new SecureHttpsClient(context);
client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,60);
client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,60);
return client;
} public String goHttpsPost(String method,HashMap<String, String> reqParmas, Context context) {
String result = null;
HttpPost post = new HttpPost(HTTPS_URL + method);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Set<String> paramsKeySet = reqParmas.keySet();
Iterator<String> ite = paramsKeySet.iterator();
while (ite.hasNext()) {
String key = ite.next();
nameValuePairs.add(new BasicNameValuePair(key, reqParmas
.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
DefaultHttpClient httpClient = getSumpayHttpsClient(context);
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != 404) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
} else { }
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
post.abort();
}
Log.d("https请求返回数据",result);
return result;
}
}
4.
/**
* Author:JsonLu
* DateTime:2016/5/31 20:33
* Email:jsonlu@qq.com
* Desc:
**/
public class DemoHttps extends Activity{ private CallServer callServer = new CallServer();
private TextView tv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_content = (TextView) findViewById(R.id.content);
} public void onClick(View v){
new Thread(){
@Override
public void run() {
HashMap hashMap = new HashMap<String,String>();
hashMap.put("data","data");
String res = callServer.goHttpsPost("https", hashMap, getBaseContext());
Message msg = new Message();
msg.obj = res;
handler.sendMessage(msg);
}
}.start();
} Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
tv_content.setText((String) msg.obj);
}
};
}
HTTPS双向认证的更多相关文章
- HTTPS 双向认证构建移动设备安全体系
HTTPS 双向认证构建移动设备安全体系 对于一些高安全性要求的企业内项目,我们有时希望能够对客户端进行验证.这个时候我们可以使用Https的双向认证机制来实现这个功能. 单向认证:保证server是 ...
- Tomcat 配置 HTTPS双向认证
Tomcat 配置 HTTPS 双向认证指引说明: � 本文档仅提供 Linux 操作系统下的指引 � 在阅读本指引前请您在 Linux 部署 JDK 和 Tomcatserver为了 Tomcat ...
- httpd设置HTTPS双向认证
去年用tomcat.jboss配置过HTTPS双向认证,那时候主要用的是JDK自带的keytool工具.这次是用httpd + openssl,区别比较大 在网上搜索了很多文章,发现全面介绍的不多,或 ...
- Https双向认证Android客户端配置
Https .cer证书转换为BKS证书 公式https://blog.csdn.net/zww986736788/article/details/81708967 keytool -importce ...
- Android Https双向认证 + GRPC
keywords:android https 双向认证android GRPC https 双向认证 ManagedChannel channel = OkHttpChannelBuilder.for ...
- 双向认证 HTTPS双向认证
[微信支付]微信小程序支付开发者文档 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=4_3 HTTPS双向认证使用说明 ...
- https双向认证訪问管理后台,採用USBKEY进行系统訪问的身份鉴别,KEY的证书长度大于128位,使用USBKEY登录
近期项目需求,须要实现用USBKEY识别用户登录,採用https双向认证訪问管理后台管理界面,期间碰到过一些小问题,写出来给大家參考下. 1:前期准备工作 USBKEY 硬件:我买的是飞天诚信 epa ...
- nodejs之https双向认证
说在前面 之前我们总结了https的相关知识,如果不懂可以看我另一篇文章:白话理解https 有关证书生成可以参考:自签证书生成 正题 今天使用nodejs来实现https双向认证 话不多说,直接进入 ...
- SpringBoot服务间使用自签名证书实现https双向认证
SpringBoot服务间使用自签名证书实现https双向认证 以服务server-one和server-two之间使用RestTemplate以https调用为例 一.生成密钥 需要生成server ...
- Keytool配置 Tomcat的HTTPS双向认证
Keytool配置 Tomcat的HTTPS双向认证 证书生成 keytool 简介 Keytool是一个Java数据证书的管理工具, Keytool将密钥(key)和证书(certificates) ...
随机推荐
- 10条PHP高级技巧
1.使用一个SQL注射备忘单 一个基本的原则就是,永远不要相信用户提交的数据. 另一个规则就是,在你发送或者存储数据时对它进行转义(escape). 可以总结为:filter input, escap ...
- 2D地图随机生成
2D地图随机生成基础绘图 海陆分布
- Oracle问题解决(远程登录失败)
远程机: 安装 Oracle 的计算机: 本地机: 访问远程机 Oracle 的计算机. 一.问题描述 远程机安装 Oracle 成功. 本地机配置 InstantClient 后, PLSql De ...
- [BZOJ 1066] [SCOI2007] 蜥蜴 【最大流】
题目链接:BZOJ - 1066 题目分析 题目限制了高度为 x 的石柱最多可以有 x 只蜥蜴从上面跳起,那么就可以用网络流中的边的容量来限制.我们把每个石柱看作一个点,每个点拆成 i1, i2,从 ...
- LINUX HA:Pacemaker + Corosync初配成功
参考很多文档: http://zhumeng8337797.blog.163.com/blog/static/100768914201218115650522/ 下一步,想想这个PC组和与HAPROX ...
- 2B The least round way
题目大意: 一个n*n的矩阵,从矩阵的左上角开始,每次移动到下面或者右面,移动到右下角结束. 要求走的路径上的所有数字乘起来,乘积得到的值后面的0最少. #include <iostream ...
- 数据结构(线段树):CodeForces 145E Lucky Queries
E. Lucky Queries time limit per test 3 seconds memory limit per test 256 megabytes input standard in ...
- 【数学规律】Vijos P1582 笨笨的L阵游戏
题目链接: https://vijos.org/p/1582 题目大意: 就是o(o<=50)个人在n*m(n,m<=2000)的格子上放L型的东西(有点像俄罗斯方块的L,可对称旋转),问 ...
- Remove Duplicates from Sorted Array II ——LeetCode
Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For exampl ...
- 动态规划——K背包问题
Problem DescriptionNow you are asked to measure a dose of medicine with a balance and a number of we ...