1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package com.persagy.iottransfer.communication.util;
- import javax.net.ssl.KeyManagerFactory;
- import javax.net.ssl.SSLContext;
- import javax.net.ssl.TrustManagerFactory;
- import java.io.ByteArrayInputStream;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.security.KeyStore;
- public final class MySslContextFactory {
- public static SSLContext getContext(String PROTOCOL, String KeyStoreType, String algorithm, String path_km,
- String path_tm, String password_km, String password_tm) throws Exception {
- InputStream is_km = null;
- InputStream is_tm = null;
- if (path_km != null) {
- is_km = new FileInputStream(path_km);
- }
- if (path_tm != null) {
- is_tm = new FileInputStream(path_tm);
- }
- SSLContext SSLContext = getContext(PROTOCOL, KeyStoreType, algorithm, is_km, is_tm, password_km, password_tm);
- return SSLContext;
- }
- public static SSLContext getContext(String PROTOCOL, String KeyStoreType, String algorithm, byte[] bytes_km,
- byte[] bytes_tm, String password_km, String password_tm) throws Exception {
- ByteArrayInputStream in = null;
- ByteArrayInputStream tIN = null;
- if (bytes_km != null) {
- in = new ByteArrayInputStream(bytes_km);
- }
- if (bytes_tm != null) {
- tIN = new ByteArrayInputStream(bytes_tm);
- }
- SSLContext SSLContext = getContext(PROTOCOL, KeyStoreType, algorithm, in, tIN, password_km, password_tm);
- return SSLContext;
- }
- private static SSLContext getContext(String PROTOCOL, String KeyStoreType, String algorithm, InputStream is_km,
- InputStream is_tm, String password_km, String password_tm) throws Exception {
- SSLContext context;
- try {
- // ��Կ������
- KeyManagerFactory kmf = null;
- if (is_km != null) {
- KeyStore ks = KeyStore.getInstance(KeyStoreType);
- ks.load(is_km, password_km.toCharArray());
- kmf = KeyManagerFactory.getInstance(algorithm);
- kmf.init(ks, password_km.toCharArray());
- }
- // ���ο�
- TrustManagerFactory tf = null;
- if (is_tm != null) {
- KeyStore tks = KeyStore.getInstance(KeyStoreType);
- tks.load(is_tm, password_tm.toCharArray());
- tf = TrustManagerFactory.getInstance(algorithm);
- tf.init(tks);
- }
- context = SSLContext.getInstance(PROTOCOL);
- // ��ʼ����������
- context.init(kmf == null ? null : kmf.getKeyManagers(), tf == null ? null : tf.getTrustManagers(), null);
- } catch (Exception e) {
- throw new Error("Failed to initialize the SSLContext", e);
- } finally {
- if (is_km != null) {
- try {
- is_km.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- is_km = null;
- }
- if (is_tm != null) {
- try {
- is_tm.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- is_tm = null;
- }
- }
- return context;
- }
- }
|