码迷,mamicode.com
首页 > 其他好文 > 详细

SSL单向验证

时间:2014-12-01 19:23:31      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:ssl单向

SSL单向验证为拦截网络通道层数据被截取,所以在客户端被调用的时候点击信任即可,程序调用同样


1、生成证书

keytool -genkey -v -alias jifubao -keyalg RSA -keystore D:\jifubao.keystore -validity 36500


2、配置tomcat(最好放在tomcat里的conf下边)

 <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"

               maxThreads="150" scheme="https" secure="true" 

  keystoreFile="conf/jifubao.keystore"  keystorePass="123456" 

               clientAuth="false" sslProtocol="TLS" />


3、浏览器访问

直接访问https即可


4、程序访问:

package com.elephant.car.common;


import java.io.*;

import java.net.*;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.*;


/**

 * https调用测试

 * ssl单项使用

 * @author xuanxy

 *

 */

public class TrustSSL {

private static class TrustAnyTrustManager implements X509TrustManager {


public void checkClientTrusted(X509Certificate[] chain, String authType)

throws CertificateException {

}


public void checkServerTrusted(X509Certificate[] chain, String authType)

throws CertificateException {

}


public X509Certificate[] getAcceptedIssuers() {

return new X509Certificate[] {};

}

}


private static class TrustAnyHostnameVerifier implements HostnameVerifier {

public boolean verify(String hostname, SSLSession session) {

return true;

}

}


public static void main(String[] args) throws Exception {

InputStream in = null;

OutputStream out = null;

byte[] buffer = new byte[4096];

String str_return = "";

try {

SSLContext sc = SSLContext.getInstance("SSL");

sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },

new java.security.SecureRandom());

URL console = new URL(

"https://192.168.1.154:8443/jifubao/user/login.json?phone_num=13212324322&password=123456&device_id=4444444&os_ver=ios22&os_name=iphone2&os_type=ios");

HttpsURLConnection conn = (HttpsURLConnection) console

.openConnection();

conn.setSSLSocketFactory(sc.getSocketFactory());

conn.setHostnameVerifier(new TrustAnyHostnameVerifier());

conn.connect();

InputStream is = conn.getInputStream();

DataInputStream indata = new DataInputStream(is);

String ret = "";


while (ret != null) {

ret = indata.readLine();

if (ret != null && !ret.trim().equals("")) {

str_return = str_return

+ new String(ret.getBytes("ISO-8859-1"), "GBK");

}

}

conn.disconnect();

} catch (ConnectException e) {

System.out.println("ConnectException");

System.out.println(e);

throw e;


} catch (IOException e) {

System.out.println("IOException");

System.out.println(e);

throw e;


} finally {

try {

in.close();

} catch (Exception e) {

}

try {

out.close();

} catch (Exception e) {

}

}

System.out.println(str_return);

}

}


SSL单向验证

标签:ssl单向

原文地址:http://xuanxy.blog.51cto.com/2357481/1585171

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!