生成证书

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双向认证的更多相关文章

  1. HTTPS 双向认证构建移动设备安全体系

    HTTPS 双向认证构建移动设备安全体系 对于一些高安全性要求的企业内项目,我们有时希望能够对客户端进行验证.这个时候我们可以使用Https的双向认证机制来实现这个功能. 单向认证:保证server是 ...

  2. Tomcat 配置 HTTPS双向认证

    Tomcat 配置 HTTPS 双向认证指引说明: � 本文档仅提供 Linux 操作系统下的指引 � 在阅读本指引前请您在 Linux 部署 JDK 和 Tomcatserver为了 Tomcat ...

  3. httpd设置HTTPS双向认证

    去年用tomcat.jboss配置过HTTPS双向认证,那时候主要用的是JDK自带的keytool工具.这次是用httpd + openssl,区别比较大 在网上搜索了很多文章,发现全面介绍的不多,或 ...

  4. Https双向认证Android客户端配置

    Https .cer证书转换为BKS证书 公式https://blog.csdn.net/zww986736788/article/details/81708967 keytool -importce ...

  5. Android Https双向认证 + GRPC

    keywords:android https 双向认证android GRPC https 双向认证 ManagedChannel channel = OkHttpChannelBuilder.for ...

  6. 双向认证 HTTPS双向认证

    [微信支付]微信小程序支付开发者文档 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=4_3 HTTPS双向认证使用说明 ...

  7. https双向认证訪问管理后台,採用USBKEY进行系统訪问的身份鉴别,KEY的证书长度大于128位,使用USBKEY登录

    近期项目需求,须要实现用USBKEY识别用户登录,採用https双向认证訪问管理后台管理界面,期间碰到过一些小问题,写出来给大家參考下. 1:前期准备工作 USBKEY 硬件:我买的是飞天诚信 epa ...

  8. nodejs之https双向认证

    说在前面 之前我们总结了https的相关知识,如果不懂可以看我另一篇文章:白话理解https 有关证书生成可以参考:自签证书生成 正题 今天使用nodejs来实现https双向认证 话不多说,直接进入 ...

  9. SpringBoot服务间使用自签名证书实现https双向认证

    SpringBoot服务间使用自签名证书实现https双向认证 以服务server-one和server-two之间使用RestTemplate以https调用为例 一.生成密钥 需要生成server ...

  10. Keytool配置 Tomcat的HTTPS双向认证

    Keytool配置 Tomcat的HTTPS双向认证 证书生成 keytool 简介 Keytool是一个Java数据证书的管理工具, Keytool将密钥(key)和证书(certificates) ...

随机推荐

  1. linux常用命令(4)rm命令

    rm是一个危险的命令,使用的时候要特别当心,尤其对于新手,否则整个系统就会毁在这个命令(比如在/(根目录)下执行rm * -rf).所以,我们在执行rm之前最好先确认一下在哪个目录,到底要删除什么东西 ...

  2. BZOJ 3570 动物园

    Description 近日,园长发现动物园中好吃懒做的动物越来越多了.例如企鹅,只会卖萌向游客要吃的.为了整治动物园的不良风气,让动物们凭自己的真才实学向游客要吃的,园长决定开设算法班,让动物们学习 ...

  3. SHELL要发送HTML这类邮件的话,还得靠msmtp 和 mutt

    参考蛮多的.. http://storysky.blog.51cto.com/628458/293005 http://www.wilf.cn/post/centos-mutt-msmtp-setup ...

  4. python operator模块

    官网:https://docs.python.org/3.4/library/operator.html http://pymotw.com/2/operator/

  5. linux系统开机过程描述

    本文描述linux系统开机过程,属于个人理解范畴,如果文中表述有误请大家批评指正! 计算机开机之后,首先要加载BIOS(基本输入输出系统)信息,BIOS包含了很多重要的信息,包括CPU信息,设备启动顺 ...

  6. 【Fiddler】手机抓包

    Fiddler (四) 实现手机的抓包 手机配置了后,Fiddler不开起来就什么也连接不了

  7. 一键安装mysql5.6

    #!/bin/bash # @Name:install_mysql.sh # @Author:Eivllom # @Create -- # @Modify -- app_soft="/app ...

  8. 【扩展欧几里得】BAPC2014 I Interesting Integers (Codeforces GYM 100526)

    题目链接: http://codeforces.com/gym/100526 http://acm.hunnu.edu.cn/online/?action=problem&type=show& ...

  9. prim模板题

    题目链接:http://acm.hrbeu.edu.cn/index.php?act=problem&id=1223 #include <cstdio> #include < ...

  10. 金牌分析师助力 鲁泰A图谋再造一个“鲁泰”?_财经_中国网

    金牌分析师助力 鲁泰A图谋再造一个"鲁泰"?_财经_中国网 金牌分析师助力 鲁泰A图谋再造一个"鲁泰"?