当前位置: 首页 > >

java http请求带证书_java ? 带有客户端证书的Android Http请求

发布时间:

我正在尝试使用此代码向具有客户端证书身份验证的服务器发出请求:


try {


/*** CA Certificate ***/


CertificateFactory cf = CertificateFactory.getInstance("X.509");


InputStream caInput = getResources().openRawResource(R.raw.caserver);


Certificate ca = cf.generateCertificate(caInput);


System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());


// Create a KeyStore containing our trusted CAs


String keyStoreType = KeyStore.getDefaultType();


KeyStore keyStore = KeyStore.getInstance(keyStoreType);


keyStore.load(null, null);


keyStore.setCertificateEntry("ca", ca);


System.out.println(keyStoreType);


// Create a TrustManager that trusts the CAs in our KeyStore


String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();


TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);


tmf.init(keyStore);


/*** Client Certificate ***/


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


InputStream certInput12 = getResources().openRawResource(R.raw.p12client);


keyStore12.load(certInput12, "123456key".toCharArray());


// Create a KeyManager that uses our client cert


String algorithm = KeyManagerFactory.getDefaultAlgorithm();


KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);


kmf.init(keyStore12, null);


/*** SSL Connection ***/


// Create an SSLContext that uses our TrustManager and our KeyManager


SSLContext context = SSLContext.getInstance("TLS");


context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);


URL url = new URL("https://myurl/test.json");


HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();


urlConnection.setSSLSocketFactory(context.getSocketFactory());


System.out.println("Weeeeeeeeeee");


InputStream in = urlConnection.getInputStream(); // this throw exception


}


catch (Exception e) {


e.printStackTrace();


}


当执行到达= urlConnection.getInputStream();中的最后一行InputStream时,我获得了下一个异常.


System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.


我花了很多时间来修复此错误,但我找不到任何信息.当我使用带有客户端证书的Web浏览器发出相同的请求时,一切正常.


有帮助吗?提前致谢.


编辑


我按照以下步骤生成证书:


> openssl req -config openssl.cnf -new -x509 -extensions v3_ca -days 3650 -keyout private/caserver.key -out certs/caserver.crt


> openssl req -config openssl.cnf -new -nodes -keyout private/client.key -out client.csr -days 1095


> openssl ca -config openssl.cnf -cert certs/caserver.crt -policy policy_anything -out certs/client.crt -infiles csr/client.csr


> openssl pkcs12 -export -clcerts -in certs/client.crt -inkey private/client.key -out p12client.p12


在我的代码中,我使用caserver.crt和p12client.p12.







相关资源:ZedBoard-自定义IP核实现+PS成功调用【详细步骤+流程介绍+源码】-附件资源



友情链接: 时尚网 总结汇报 幼儿教育 小学教育 初中学习资料网