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:[email protected]
 * 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:[email protected]
 * 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:[email protected]
 * 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:[email protected]
 * 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);
        }
    };
}

  

时间: 2024-10-14 04:47:44

HTTPS双向认证的相关文章

rails+apache2+passenger+ssl实现https双向认证通信

rails+apache2+passenger+ssl实现https双向认证通信 环境: 系统:Centos7 服务器:apache(httpd) 2.4.6 制作工具:openssl 1.0.1 Rails版本 :4.1.6 准备工作: 安装apache和openssl #yum install  httpd  httpd-devel httpd-tools #yum install openssl 安张mod_ssl #yum install mod_ssl 一.创建根证书 1创建CA私钥

利用tomcat服务器配置https双向认证

首先请保证已经安装好jdk,并且环境变量以及配置好了 第一步.为服务器生成证书: 使用toolkey为tomcat生成证书,假定目标机器的域名为localhost,使用如下命令生成:keytool –genkey –v –aliaslocalhost_server RSA –keystore localhost_server.store  –validity 36500 第二步.为客户端生成证书: 为浏览器生成证书,以便让服务器来验证它.为了能保证证书顺利导入至IE和Firefox,证书格式应该

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

HTTPS 双向认证构建移动设备安全体系 对于一些高安全性要求的企业内项目,我们有时希望能够对客户端进行验证.这个时候我们可以使用Https的双向认证机制来实现这个功能. 单向认证:保证server是真的,通道是安全的(对称密钥):双向认证:保证client和server是真的,通道是安全的(对称密钥): 要实现这么一个完整的安全体系,需要一个CA或者openssl自建CA来管理签发客户端证书.作为项目要求的场景可能是这样的,一个前端网站专门用于签发证书,通过电子邮件发送下载客户端证书邮件到移动

nginx与ios实现https双向认证

服务端配置 nginx关键配置如下: listen 443; server_name localhost; ssl on; ssl_certificate /usr/local/opt/nginx/certificates/server.cer; ssl_certificate_key /usr/local/opt/nginx/certificates/server.key.pem; ssl_client_certificate /usr/local/opt/nginx/certificates

tomcat https双向认证

没啥可写的,直接看这些博文吧... 注:server.xml 双向认证 注意得配:truststoreFile,单向不用 浏览器客户端p12证书,需要添加到服务器的jks文件中. http://www.blogjava.net/stevenjohn/archive/2012/08/22/385989.html http://www.360doc.com/content/10/0401/23/633992_21237818.shtml http://www.blogjava.net/stevenj

Android Https双向认证 + GRPC

keywords:android https 双向认证android GRPC https 双向认证 ManagedChannel channel = OkHttpChannelBuilder.forAddress("xxx",yyy) .overrideAuthority("zzz") .sslSocketFactory(sslFactory) .build(); 1.千万不要像官网案例那样设置setPlaintext(true),这个是设置明文,我们用的是密文

tomcat构建HTTPS双向认证

第一步:为服务器生成证书 # keytool -genkey -alias tomcat -keyalg RSA -keystore /usr/local/ac/web/tomcat.keystore -validity 36500 (参数简要说明:"/etc/tomcat.keystore"含义是将证书文件保存在路径/usr/local/ac/web/下,证书文件名称是tomcat.keystore :"-validity 36500"含义是证书有效期,36500

ASIHTTPRequest实现https双向认证请求

什么是双向认证呢?简而言之,就是服务器端对请求它的客户端要进行身份验证,客户端对自己所请求的服务器也会做身份验证.服务端一旦验证到请求自己的客户端为不可信任的,服务端就拒绝继续通信.客户端如果发现服务端为不可信任的,那么也中止通信. 双向认证的算法理论是RSA,(点击此处了解RSA算法原理). 双向认证具体又是通过安全证书的方式来实现的,安全证书可用openssl或java程序来生成,用于双向认证的安全证书中保存了密钥对,证书颁发机构信 息,签名信息,签名算法,颁发对象,有效期等信息.双向认证中

AFNetWorking https 双向认证

客户端验证服务端证书: 需要http配置路径需要域名 1:先项目中倒入服务端证书 sever.cer, 2.然后设置 AFSecurityPolicy self.manager = [AFHTTPRequestOperationManager manager]; self.manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init]; [self.manager.requestSerializer setValue:@"

https双向认证时证书签发和配置

1.生成CA自签文件 1.1  在openssl-0.9.8h-1-bin\bin进入cmd窗口 或者 cmd窗口路径到openssl-0.9.8h-1-bin\bin下 1.2 ras的秘钥长度:2048 存放ca公钥证书的路径:D:/cert_test/root_ca/ca_cert.pem 证书的有效期(天): 3650 根证书配置文件:D:/jx_cert/conf/gen_ca.conf 根据自己的需要调整配置文件的私钥证书证书存放路径,颁发者名称等 openssl req -x509