Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/security/KeyStore/TestKeyStoreBasic.java
41149 views
1
/*
2
* Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
import java.io.BufferedInputStream;
25
import java.io.ByteArrayInputStream;
26
import java.io.ByteArrayOutputStream;
27
import java.io.IOException;
28
import java.io.InputStream;
29
import java.security.KeyFactory;
30
import java.security.KeyStore;
31
import java.security.KeyStoreException;
32
import java.security.NoSuchProviderException;
33
import java.security.PrivateKey;
34
import java.security.UnrecoverableKeyException;
35
import java.security.cert.Certificate;
36
import java.security.cert.CertificateFactory;
37
import java.security.spec.KeySpec;
38
import java.security.spec.PKCS8EncodedKeySpec;
39
import java.util.Base64;
40
41
/*
42
* @test
43
* @bug 8048621 8133090 8167371 8236671
44
* @summary Test basic operations with keystores (jks, jceks, pkcs12)
45
* @author Yu-Ching Valerie PENG
46
*/
47
public class TestKeyStoreBasic {
48
49
private static final String PRIVATE_KEY_PKCS8_BASE64 = ""
50
+ "MIIE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E+V0wd0JvCHEdpAz3mksyvDFhU4Bgs6xzf2pSul5muhsx3hHcvvPezz5Bnxs"
64
+ "faJlzkxfwotyGmvWN15GA/pyfsZjsbbTpwkCgYAO6NnbysQCIV8SnegCKqfatt9N/O5m7LLhRxQb"
65
+ "p2bwrlA4cZ34rWkw/w9x3LK7A6wkfgUPnJkswxPSLXJTG05l6M4rPfCwIKr1Qopojp9QSMr569NQ"
66
+ "4YeLOOc7heIIzbFQHpU6I5Rncv2Q2sn9W+ZsqJKIuvX34FjQNiZ406EzMQKBgHSxOGS61D84DuZK"
67
+ "2Ps1awhC3kB4eHzJRms3vflDPWoJJ+pSKwpKrzUTPHXiPBqyhtYkPGszVeiE6CAr9sv3YZnFVaBs"
68
+ "6hyQUJsob+uE/w/gGvXe8VsFDx0bJOodYfhrCbTHBHWqE81nBcocpxayxsayfAzqWB3KKd0YLrMR"
69
+ "K2PZAoGAcZa8915R2m0KZ6HVJUt/JDR85jCbN71kcVDFY2XSFkOJvOdFoHNfRckfLzjq9Y2MSSTV"
70
+ "+QDWbDo2doUQCejJUTaN8nP79tfyir24X5uVPvQaeVoGTKYb+LfUqK0F60lStmjuddIGSZH55y3v"
71
+ "+9XjmxbVERtd1lqgQg3VlmKlEXY=";
72
73
/*
74
* Certificate:
75
* Data:
76
* Version: 3 (0x2)
77
* Serial Number: 7 (0x7)
78
* Signature Algorithm: sha512WithRSAEncryption
79
* Issuer: CN=Root
80
* Validity
81
* Not Before: Sep 1 18:03:59 2015 GMT
82
* Not After : Jan 17 18:03:59 2043 GMT
83
* Subject: CN=EE
84
*/
85
private static final String CERTIFICATE = ""
86
+ "-----BEGIN CERTIFICATE-----\n"
87
+ "MIIDHTCCAgWgAwIBAgIBBzANBgkqhkiG9w0BAQ0FADAPMQ0wCwYDVQQDDARSb290\n"
88
+ "MB4XDTE1MDkwMTE4MDM1OVoXDTQzMDExNzE4MDM1OVowDTELMAkGA1UEAwwCRUUw\n"
89
+ "ggEiMA0GCSqGSIb3DQEB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ERTIFICATE-----\n";
105
106
private static final char[] PASSWD2 = new char[] {
107
'b', 'o', 'r', 'e', 'd'
108
};
109
private static final char[] PASSWDK = "cannot be null"
110
.toCharArray();
111
private static final String[] KS_Type = {
112
"jks", "jceks", "pkcs12", "PKCS11KeyStore"
113
};
114
private static final String[] PROVIDERS = {
115
"SUN", "SunJCE", "SunJSSE"
116
};
117
private static final String ALIAS_HEAD = "test";
118
119
private static final String CRYPTO_ALG = "PBEWithHmacSHA256AndAES_128";
120
121
public static void main(String args[]) throws Exception {
122
TestKeyStoreBasic jstest = new TestKeyStoreBasic();
123
jstest.run();
124
}
125
126
public void run() throws Exception {
127
for (String provider : PROVIDERS) {
128
runTest(provider);
129
System.out.println("Test with provider " + provider + " passed");
130
}
131
}
132
133
public void runTest(String provider) throws Exception {
134
135
// load private key
136
// all keystore types should support private keys
137
KeySpec spec = new PKCS8EncodedKeySpec(
138
Base64.getMimeDecoder().decode(PRIVATE_KEY_PKCS8_BASE64));
139
PrivateKey privateKey = KeyFactory.getInstance("RSA")
140
.generatePrivate(spec);
141
142
// load x509 certificate
143
Certificate cert;
144
try (InputStream is = new BufferedInputStream(
145
new ByteArrayInputStream(CERTIFICATE.getBytes()))) {
146
cert = CertificateFactory.getInstance("X.509")
147
.generateCertificate(is);
148
}
149
150
int numEntries = 5;
151
String type = null;
152
for (int i = 0; i < PROVIDERS.length; i++) {
153
if (provider.compareTo(PROVIDERS[i]) == 0) {
154
type = KS_Type[i];
155
break;
156
}
157
}
158
159
System.out.printf("Test %s provider and %s keystore%n", provider, type);
160
KeyStore ks = KeyStore.getInstance(type, provider);
161
KeyStore ks2 = KeyStore.getInstance(type, ks.getProvider().getName());
162
163
// create an empty key store
164
ks.load(null, null);
165
166
// unit test - test with null password
167
try {
168
ks.setKeyEntry(ALIAS_HEAD, privateKey, null,
169
new Certificate[] { cert });
170
} catch (KeyStoreException e) {
171
if (!e.getMessage().contains("password can\'t be null")) {
172
throw new RuntimeException("Unexpected message:" + e.getMessage());
173
}
174
// expected
175
}
176
177
// store the secret keys
178
for (int j = 0; j < numEntries; j++) {
179
ks.setKeyEntry(ALIAS_HEAD + j, privateKey, PASSWDK,
180
new Certificate[] { cert });
181
}
182
183
// initialize the 2nd key store object with the 1st one
184
ByteArrayOutputStream baos = new ByteArrayOutputStream();
185
ks.store(baos, PASSWDK);
186
byte[] bArr = baos.toByteArray();
187
ByteArrayInputStream bais = new ByteArrayInputStream(bArr);
188
ks2.load(bais, null);
189
190
// check 2nd key store type
191
checkType(ks2, type);
192
// check the existing aliases for the 2nd key store
193
checkAlias(ks2, numEntries);
194
195
// compare the creation date of the 2 key stores for all aliases
196
compareCreationDate(ks, ks2, numEntries);
197
// remove the last entry from the 2nd key store
198
numEntries--;
199
ks2.deleteEntry(ALIAS_HEAD + numEntries);
200
201
// re-initialize the 1st key store with the 2nd key store
202
baos.reset();
203
ks2.store(baos, PASSWD2);
204
bais = new ByteArrayInputStream(baos.toByteArray());
205
try {
206
// expect an exception since the password is incorrect
207
ks.load(bais, PASSWDK);
208
throw new RuntimeException(
209
"ERROR: passed the loading with incorrect password");
210
} catch (IOException ex) {
211
System.out.println("Expected exception: " + ex);
212
if (!causedBy(ex, UnrecoverableKeyException.class)) {
213
ex.printStackTrace(System.out);
214
throw new RuntimeException("Unexpected cause");
215
}
216
System.out.println("Expected cause: "
217
+ UnrecoverableKeyException.class.getName());
218
219
bais.reset();
220
ks.load(bais, PASSWD2);
221
bais.reset();
222
ks.load(bais, null);
223
}
224
225
// check key store type
226
checkType(ks, type);
227
228
// check the existing aliases
229
checkAlias(ks, numEntries);
230
231
// compare the creation date of the 2 key stores for all aliases
232
compareCreationDate(ks, ks2, numEntries);
233
234
// check setEntry/getEntry with a password protection algorithm
235
if ("PKCS12".equalsIgnoreCase(ks.getType())) {
236
System.out.println(
237
"Skipping the setEntry/getEntry check for PKCS12 keystore...");
238
return;
239
}
240
String alias = ALIAS_HEAD + ALIAS_HEAD;
241
KeyStore.PasswordProtection pw =
242
new KeyStore.PasswordProtection(PASSWD2, CRYPTO_ALG, null);
243
KeyStore.PrivateKeyEntry entry =
244
new KeyStore.PrivateKeyEntry(privateKey, new Certificate[]{ cert });
245
checkSetEntry(ks, alias, pw, entry);
246
ks.setEntry(alias, entry, new KeyStore.PasswordProtection(PASSWD2));
247
checkGetEntry(ks, alias, pw);
248
}
249
250
// check setEntry with a password protection algorithm
251
private void checkSetEntry(KeyStore ks, String alias,
252
KeyStore.PasswordProtection pw, KeyStore.Entry entry) throws Exception {
253
try {
254
ks.setEntry(alias, entry, pw);
255
throw new Exception(
256
"ERROR: expected KeyStore.setEntry to throw an exception");
257
} catch (KeyStoreException e) {
258
// ignore the expected exception
259
}
260
}
261
262
// check getEntry with a password protection algorithm
263
private void checkGetEntry(KeyStore ks, String alias,
264
KeyStore.PasswordProtection pw) throws Exception {
265
try {
266
ks.getEntry(alias, pw);
267
throw new Exception(
268
"ERROR: expected KeyStore.getEntry to throw an exception");
269
} catch (KeyStoreException e) {
270
// ignore the expected exception
271
}
272
}
273
274
// check key store type
275
private void checkType(KeyStore obj, String type) {
276
if (!obj.getType().equals(type)) {
277
throw new RuntimeException("ERROR: wrong key store type");
278
}
279
}
280
281
// check the existing aliases
282
private void checkAlias(KeyStore obj, int range) throws KeyStoreException {
283
for (int k = 0; k < range; k++) {
284
if (!obj.containsAlias(ALIAS_HEAD + k)) {
285
throw new RuntimeException("ERROR: alias (" + k
286
+ ") should exist");
287
}
288
}
289
}
290
291
// compare the creation dates - true if all the same
292
private void compareCreationDate(KeyStore o1, KeyStore o2, int range)
293
throws KeyStoreException {
294
String alias;
295
for (int k = 0; k < range; k++) {
296
alias = ALIAS_HEAD + k;
297
if (!o1.getCreationDate(alias).equals(o2.getCreationDate(alias))) {
298
throw new RuntimeException("ERROR: entry creation time (" + k
299
+ ") differs");
300
}
301
}
302
}
303
304
// checks if an exception was caused by specified exception class
305
private static boolean causedBy(Exception e, Class klass) {
306
Throwable cause = e;
307
while ((cause = cause.getCause()) != null) {
308
if (cause.getClass().equals(klass)) {
309
return true;
310
}
311
}
312
return false;
313
}
314
315
}
316
317