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 private String provider = null;
45 private char[] password = null;
46 private byte[] data = null;
47
48
49
50
51
52
53
54 public KeyStore newInstance() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException {
55 if (data == null) {
56 throw new IllegalStateException("data property is not set.");
57 }
58
59 KeyStore ks;
60 if (provider == null) {
61 ks = KeyStore.getInstance(type);
62 } else {
63 ks = KeyStore.getInstance(type, provider);
64 }
65
66 InputStream is = new ByteArrayInputStream(data);
67 try {
68 ks.load(is, password);
69 } finally {
70 try {
71 is.close();
72 } catch (IOException ignored) {
73
74 }
75 }
76
77 return ks;
78 }
79
80
81
82
83
84
85
86
87
88 public void setType(String type) {
89 if (type == null) {
90 throw new NullPointerException("type");
91 }
92 this.type = type;
93 }
94
95
96
97
98
99
100
101
102 public void setPassword(String password) {
103 if (password != null) {
104 this.password = password.toCharArray();
105 } else {
106 this.password = null;
107 }
108 }
109
110
111
112
113
114
115
116 public void setProvider(String provider) {
117 this.provider = provider;
118 }
119
120
121
122
123
124
125 public void setData(byte[] data) {
126 byte[] copy = new byte[data.length];
127 System.arraycopy(data, 0, copy, 0, data.length);
128 this.data = copy;
129 }
130
131
132
133
134
135
136 private void setData(InputStream dataStream) throws IOException {
137 ByteArrayOutputStream out = new ByteArrayOutputStream();
138 try {
139 for (;;) {
140 int data = dataStream.read();
141 if (data < 0) {
142 break;
143 }
144 out.write(data);
145 }
146 setData(out.toByteArray());
147 } finally {
148 try {
149 dataStream.close();
150 } catch (IOException e) {
151
152 }
153 }
154 }
155
156
157
158
159
160
161 public void setDataFile(File dataFile) throws IOException {
162 setData(new BufferedInputStream(new FileInputStream(dataFile)));
163 }
164
165
166
167
168
169
170 public void setDataUrl(URL dataUrl) throws IOException {
171 setData(dataUrl.openStream());
172 }
173 }