https证书认证-java

1.首先要确认是双向认证还是单向认证,如果是只需要对服务端的单向认证,则只需要用到根证书,应该就是这里的ca.crt。如果是双向认证,三个都需要用到。如果是java代码作为客户端连接

2.单向认证是客户端根据ca根证书验证服务端提供的服务端证书和私钥

public static String httpGET(String url, String pemPath, String keypath) {// 加载证书try {SSLConnectionSocketFactory sslsf =getSocketFactoryPEM(pemPath, keypath);httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (Exception e) {logger.error(e);}String result = null;HttpGet httpGet = new HttpGet(url);// 得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
//        httpGet.addHeader("Content-Type", "text/xml");// 根据默认超时限制初始化requestConfigrequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();// 设置请求器的配置httpGet.setConfig(requestConfig);try {HttpResponse response = null;try {response = httpClient.execute(httpGet);} catch (IOException e) {e.printStackTrace();}HttpEntity entity = response.getEntity();try {result = EntityUtils.toString(entity, "UTF-8");} catch (IOException e) {e.printStackTrace();logger.error(e);}} finally {httpGet.abort();}return result;}
protected static SSLConnectionSocketFactory getSocketFactoryPEM(String pemPath,String keypath) throws Exception {byte[] pem = fileToBytes(pemPath);byte[] pemKey = fileToBytes(keypath);byte[] certBytes = parseDERFromPEM(pem, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");byte[] keyBytes = parseDERFromPEM(pemKey, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");X509Certificate cert = generateCertificateFromDER(certBytes);RSAPrivateKey key  = generatePrivateKeyFromDER(keyBytes);KeyStore keystore = KeyStore.getInstance("JKS");keystore.load(null);keystore.setCertificateEntry("cert-alias", cert);keystore.setKeyEntry("key-alias", key, "123".toCharArray(), new Certificate[] {cert});KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");kmf.init(keystore, "123".toCharArray());KeyManager[] km = kmf.getKeyManagers();SSLContext context = SSLContext.getInstance("TLS");context.init(km, null, null);SSLConnectionSocketFactory sslsf =new SSLConnectionSocketFactory(context,null, null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);return sslsf;
}public static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) {String data = new String(pem);String[] tokens = data.split(beginDelimiter);tokens = tokens[1].split(endDelimiter);return DatatypeConverter.parseBase64Binary(tokens[0]);
}public static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory factory = KeyFactory.getInstance("RSA");return (RSAPrivateKey)factory.generatePrivate(spec);
}public static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {CertificateFactory factory = CertificateFactory.getInstance("X.509");return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(certBytes));
}
public static byte[] fileToBytes(String filePath) {byte[] buffer = null;File file = new File(filePath);FileInputStream fis = null;ByteArrayOutputStream bos = null;try {fis = new FileInputStream(file);bos = new ByteArrayOutputStream();byte[] b = new byte[1024];int n;while ((n = fis.read(b)) != -1) {bos.write(b, 0, n);}buffer = bos.toByteArray();} catch (FileNotFoundException ex) {ex.printStackTrace();} catch (IOException ex) {ex.printStackTrace();} finally {try {if (null != bos) {bos.close();}} catch (IOException ex) {} finally{try {if(null!=fis){fis.close();}} catch (IOException ex) {ex.printStackTrace();}}}return buffer;
}

 

 

 

 

本文链接:https://my.lmcjl.com/post/1616.html

展开阅读全文

4 评论

留下您的评论.