1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.filter.ssl;
21
22 import java.io.BufferedInputStream;
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.URL;
30 import java.security.KeyStore;
31 import java.security.KeyStoreException;
32 import java.security.NoSuchAlgorithmException;
33 import java.security.NoSuchProviderException;
34 import java.security.cert.CertificateException;
35
36
37
38
39
40
41 public class KeyStoreFactory {
42
43 private String type = "JKS";
44
45 private String provider = null;
46
47 private char[] password = null;
48
49 private byte[] data = null;
50
51
52
53
54
55
56
57 public KeyStore newInstance() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException,
58 CertificateException, IOException {
59 if (data == null) {
60 throw new IllegalStateException("data property is not set.");
61 }
62
63 KeyStore ks;
64 if (provider == null) {
65 ks = KeyStore.getInstance(type);
66 } else {
67 ks = KeyStore.getInstance(type, provider);
68 }
69
70 InputStream is = new ByteArrayInputStream(data);
71 try {
72 ks.load(is, password);
73 } finally {
74 try {
75 is.close();
76 } catch (IOException ignored) {
77
78 }
79 }
80
81 return ks;
82 }
83
84
85
86
87
88
89
90
91
92 public void setType(String type) {
93 if (type == null) {
94 throw new IllegalArgumentException("type");
95 }
96 this.type = type;
97 }
98
99
100
101
102
103
104
105
106 public void setPassword(String password) {
107 if (password != null) {
108 this.password = password.toCharArray();
109 } else {
110 this.password = null;
111 }
112 }
113
114
115
116
117
118
119
120 public void setProvider(String provider) {
121 this.provider = provider;
122 }
123
124
125
126
127
128
129 public void setData(byte[] data) {
130 byte[] copy = new byte[data.length];
131 System.arraycopy(data, 0, copy, 0, data.length);
132 this.data = copy;
133 }
134
135
136
137
138
139
140 private void setData(InputStream dataStream) throws IOException {
141 ByteArrayOutputStream out = new ByteArrayOutputStream();
142 try {
143 for (;;) {
144 int data = dataStream.read();
145 if (data < 0) {
146 break;
147 }
148 out.write(data);
149 }
150 setData(out.toByteArray());
151 } finally {
152 try {
153 dataStream.close();
154 } catch (IOException e) {
155
156 }
157 }
158 }
159
160
161
162
163
164
165 public void setDataFile(File dataFile) throws IOException {
166 setData(new BufferedInputStream(new FileInputStream(dataFile)));
167 }
168
169
170
171
172
173
174 public void setDataUrl(URL dataUrl) throws IOException {
175 setData(dataUrl.openStream());
176 }
177 }