Android Retrofit HTTPS 单向认证 双向认证

由于最近要做一个安全性比较高的项目,因此需要用到HTTPS进行双向认证。客户端基于Retrofit + Rxjava+EventBus来实现


基于Retrofit实现HTTPS思路

由于Retrofit是基于OkHttp实现的,因此想通过Retrofit实现HTTPS需要给Retrofit设置一个OkHttp代理对象用于处理HTTPS的握手过程。代理代码如下:

mOkHttpClient = new OkHttpClient.Builder()
        .hostnameVerifier(new UnSafeHostnameVerifier())//添加hostName验证器
        .sslSocketFactory(sslSocketFactory)
        .build();

Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(ScalarsConverterFactory.create())//增加返回值为字符串的支持
        .baseUrl(BASE_URL)//主机地址
        .client(mOkHttpClient)//注意这里要给retrofit 设置okhttpclient
        .build();

private class UnSafeHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;//自行添加判断逻辑,true->Safe,false->unsafe
    }
}


 
   
上面代码可以看到使用Retrofit请求HTTPS主要使用SSLSocketFactory,所以我们只需构建sslSocketFactory。
在我的例子中,我有一个pem文件,它包含一个证书和一个加密的私钥,用于相互SSL身份验证。 因此我的pem文件如下所示:
 
   
-----BEGIN RSA PRIVATE KEY-----
......
 
   
-----END RSA PRIVATE KEY-----
 
   
 
   
-----BEGIN CERTIFICATE-----
......
 
   
-----END CERTIFICATE-----

如果你得到的私钥如上所示,那你还需要使用openssl执行PKCS8编码:
openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt
得到如下私钥
 
   
-----BEGIN PRIVATE KEY-----
......
-----END PRIVATE KEY-----

进入代码正文

创建一个新的java密钥存储并导入私钥和证书:
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, keypass.toCharArray());
ks.store(new FileOutputStream(getExternalFilesDir(null) + "/xxx.keystore"), keypass.toCharArray());
ks.load(new FileInputStream(getExternalFilesDir(null) + "/xxx.keystore"), keypass.toCharArray());

//读取证书文件
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
//转化为字符串
String str = new String(bytes);
//提取出私钥和证书
String[] s = str.replace("-----BEGIN PRIVATE KEY-----\n", "").split("\n-----END PRIVATE KEY-----\n");

//  获取指定目录下的证书
Certificate crt1 = CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream(file));
fileInputStream.close();

byte[] bytes1 = Base64.decode(s[0], Base64.DEFAULT);
//主要代码
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(bytes1);
PrivateKey ff = kf.generatePrivate(keysp);
//证书链
Certificate[] chain = new Certificate[]{crt1};
String mainInformation = ((X509Certificate) crt1).getSubjectX500Principal().getName();
//获取别名
String alias = mainInformation.substring((mainInformation.indexOf("=") + 1), mainInformation.indexOf(","));
//组合,并添加证书到KeyStore
ks.setKeyEntry(alias , ff, keypass.toCharArray(), chain);


 
    
 
    
 
  
 
  
 
  
 
  
 
   
  
            //秘钥管理器
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
            kmf.init(ks, keypass.toCharArray());
            KeyManager[] keyManagers = kmf.getKeyManagers();

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagers, null, null);

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
由于我公司服务器证书是ca认证的所以不需要验证 TrustManagerFactory

如果使用的是p12格式证书则只能把证书当作文件的形式读取:
        try {
            //创建KeyStore

KeyStore keyStore = KeyStore.getInstance("PKCS12");


keyStore .load(getResources().openRawResource(R.raw.certificate_with_key_6), "U3T2C24RW8".toCharArray());

           //秘钥管理器
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
            kmf.init(ks, keypass.toCharArray());
            KeyManager[] keyManagers = kmf.getKeyManagers();

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagers, null, null);

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


        } catch (Exception e) {
            e.printStackTrace();
            Log.e("MainActivity", "-------错误111------" + e.toString());
        }


到此基本代码已完结,欢迎提出意见:

转载请注明出处: http://blog.csdn.net/q714093365/article/details/73123585
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  

你可能感兴趣的:(Android Retrofit HTTPS 单向认证 双向认证)