1.安装OpenSSL见OpenSSL之自签名证书
2.使用管理员权限运行openssl.exe
3.在窗口输入genrsa -out test/self.key 1024 生成私钥
4.生成证书文件
Req -new -x509 -key test/self.key -out test/self.cer -days 3650 -subj /CN=192.168.1.243
Self.key是第三步中生成的key的名字 , self.cer为生成的证书 3650为证书过期天数 , CN的参数192.168.1.243是主机名
5.生成.pfx的私钥文件
pkcs12 -export -out test/self.pfx -inkey test/self.key -in test/self.cer
需要输入密码 ,在使用私钥的时候使用
1.打开IIS管理器并点击服务器证书
2.导入上面生成的.pfx文件到IIS管理器中
3.添加网站
选择https ,使用443端口 ,选择导入的服务器证书 ,这样安装了self.cer证书的客户端就可以安全访问了.
1.打开android studio , 新建一个app应用程序
2.在gradle配置(此文章使用xtuils3实现https请求)
implementation 'org.xutils:xutils:3.3.36'
3.在Application配置
x.Ext.init(this);
x.Ext.setDebug(BuildConfig.DEBUG);
4.将生成的.cer证书文件放在 assets目录下
5.建立一个get请求
String url = "https://192.168.1.244/quanzi/Test/get";
RequestParams params = new RequestParams(url);
params.addQueryStringParameter("username","quanzi");
params.addQueryStringParameter("password","123456");
params.setSslSocketFactory(getSSLContext().getSocketFactory());
x.http().get(params, new Callback.CommonCallback() {
@Override
public void onSuccess(String result) {
Log.d(TAG,"onSuccess..." + result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
Log.d(TAG,"onError..." + ex);
}
@Override
public void onCancelled(CancelledException cex) {
Log.d(TAG,"onCancelled..." + cex);
}
@Override
public void onFinished() {
Log.d(TAG,"onFinished...");
}
});
6.获取Https证书 ,并验证证书
private static SSLContext getSSLContext(){
SSLContext sslContext = getSSLContext(MyApp.getContext());
if (null == sslContext) {
Log.d(TAG,"证书验证失败...");
return sslContext;
}
Log.d(TAG,"证书验证成功...");
return sslContext;
}
/**
* 获取https的证书
* @param context 上下文
* @return SSL的上下文对象
*/
private static SSLContext getSSLContext(Context context){
CertificateFactory certificateFactory = null;
InputStream inputStream = null;
Certificate cer = null;
KeyStore keystore = null;
TrustManagerFactory trustManagerFactory = null;
try {
certificateFactory = CertificateFactory.getInstance("X.509");
inputStream = context.getAssets().open("myself.cer");//这里导入SSL证书文件
try {
cer = certificateFactory.generateCertificate(inputStream);
} finally {
inputStream.close();
}
//创建一个证书库,并将证书导入证书库
keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null, null); //双向验证时使用
keystore.setCertificateEntry("trust", cer);
// 实例化信任库
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
mSSLContext = SSLContext.getInstance("TLS");
mSSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
return mSSLContext;
} catch (Exception e) {
Log.d(TAG,"证书验证的异常..." + e);
}
return null;
}