public static void main(String[] args) throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException { ResourceLoader resourceLoader = new DefaultResourceLoader(); InputStream keyStore = resourceLoader.getResource("test.p12").getInputStream(); String keyStorePassword = "111111"; String keyPassword = "111111"; String KeyStoreType= "PKCS12"; String KeyManagerAlgorithm = "SunX509"; String SSLVersion = "SSLv3"; new Test01().getHttpsURLConnection(null, keyStore, keyStorePassword, keyPassword, KeyStoreType, KeyManagerAlgorithm, SSLVersion); }
public HttpURLConnection getHttpsURLConnection(URL url, InputStream keystore, String keyStorePass,String keyPassword, String KeyStoreType ,String KeyManagerAlgorithm, String SSLVersion) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { System.setProperty("javax.net.debug","ssl,handshake,record"); SSLContext sslcontext = SSLContext.getInstance(SSLVersion); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerAlgorithm); KeyStore ks = KeyStore.getInstance(KeyStoreType); ks.load(keystore, keyStorePass.toCharArray()); kmf.init(ks, keyPassword.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); TrustManager[] tm = tmf.getTrustManagers(); sslcontext.init(kmf.getKeyManagers(), tm, null); SSLSocketFactory sslSocketFactory = sslcontext.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); //HttpsURLConnection httpsURLConnection = ( HttpsURLConnection)url.openConnection(); return null; }
最开始拿到p12的时候,给的密码是错的,试了很久,最后判定是p12文件的密码不正确,java
因而经过pem和key从新生成了一个p12文件,密码本身设置后,就成功了。
url
第二种实现方式:.net
KeyStore ks = KeyStore.getInstance("PKCS12"); char[] password = "p12pwd".toCharArray(); Resource resource = resourceLoader.getResource("test.p12"); ks.load(resource.getInputStream(), password); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password); SSLContext ssl = SSLContext.getInstance("TLS"); ssl.init(kmf.getKeyManagers(), null, null); HttpsURLConnection httpsURLConnection = ( HttpsURLConnection)new URL("").openConnection(); httpsURLConnection.setSSLSocketFactory(ssl.getSocketFactory());