summaryrefslogtreecommitdiffstats
path: root/luni/src/main/java/java/security/KeyStore.java
blob: 3d856f70a26173e9eb2dd4474bd211b33562bd6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package java.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import javax.crypto.SecretKey;
import javax.security.auth.DestroyFailedException;
import javax.security.auth.Destroyable;
import javax.security.auth.callback.CallbackHandler;
import libcore.io.IoUtils;
import org.apache.harmony.security.fortress.Engine;

/**
 * {@code KeyStore} is responsible for maintaining cryptographic keys and their
 * owners.
 * <p>
 * The type of the system key store can be changed by setting the {@code
 * 'keystore.type'} property in the file named {@code
 * JAVA_HOME/lib/security/java.security}.
 *
 * @see Certificate
 * @see PrivateKey
 */
public class KeyStore {

    // Store KeyStore SERVICE name
    private static final String SERVICE = "KeyStore";

    // Used to access common engine functionality
    private static final Engine ENGINE = new Engine(SERVICE);

    //  Store KeyStore property name
    private static final String PROPERTYNAME = "keystore.type";

    //  Store default KeyStore type
    private static final String DEFAULT_KEYSTORE_TYPE = "jks";

    // Store KeyStore state (initialized or not)
    private boolean isInit;

    // Store used KeyStoreSpi
    private final KeyStoreSpi implSpi;

    // Store used provider
    private final Provider provider;

    // Store used type
    private final String type;

    /**
     * Constructs a new instance of {@code KeyStore} with the given arguments.
     *
     * @param keyStoreSpi
     *            the concrete key store.
     * @param provider
     *            the provider.
     * @param type
     *            the type of the {@code KeyStore} to be constructed.
     */
    protected KeyStore(KeyStoreSpi keyStoreSpi, Provider provider, String type) {
        this.type = type;
        this.provider = provider;
        this.implSpi = keyStoreSpi;
        isInit = false;
    }

    /**
     * Throws the standard "keystore not initialized" exception.
     */
    private static void throwNotInitialized() throws KeyStoreException {
        throw new KeyStoreException("KeyStore was not initialized");
    }

    /**
     * Returns a new instance of {@code KeyStore} with the specified type.
     *
     * @param type
     *            the type of the returned {@code KeyStore}.
     * @return a new instance of {@code KeyStore} with the specified type.
     * @throws KeyStoreException
     *             if an error occurred during the creation of the new {@code
     *             KeyStore}.
     * @throws NullPointerException if {@code type == null}
     * @see #getDefaultType
     */
    public static KeyStore getInstance(String type) throws KeyStoreException {
        if (type == null) {
            throw new NullPointerException("type == null");
        }
        try {
            Engine.SpiAndProvider sap = ENGINE.getInstance(type, null);
            return new KeyStore((KeyStoreSpi) sap.spi, sap.provider, type);
        } catch (NoSuchAlgorithmException e) {
            throw new KeyStoreException(e);
        }
    }

    /**
     * Returns a new instance of {@code KeyStore} from the specified provider
     * with the given type.
     *
     * @param type
     *            the type of the returned {@code KeyStore}.
     * @param provider
     *            name of the provider of the {@code KeyStore}.
     * @return a new instance of {@code KeyStore} from the specified provider
     *         with the given type.
     * @throws KeyStoreException
     *             if an error occurred during the creation of the new {@code
     *             KeyStore}.
     * @throws NoSuchProviderException
     *             if the specified provider is not available.
     * @throws IllegalArgumentException if {@code provider == null || provider.isEmpty()}
     * @throws NullPointerException
     *             if {@code type} is {@code null} (instead of
     *             NoSuchAlgorithmException) as in 1.4 release
     * @see #getDefaultType
     */
    public static KeyStore getInstance(String type, String provider)
            throws KeyStoreException, NoSuchProviderException {
        if (provider == null || provider.isEmpty()) {
            throw new IllegalArgumentException();
        }
        Provider impProvider = Security.getProvider(provider);
        if (impProvider == null) {
            throw new NoSuchProviderException(provider);
        }
        try {
            return getInstance(type, impProvider);
        } catch (Exception e) {
            throw new KeyStoreException(e);
        }
    }

    /**
     * Returns a new instance of {@code KeyStore} from the specified provider
     * with the given type.
     *
     * @param type
     *            the type of the returned {@code KeyStore}.
     * @param provider
     *            the provider of the {@code KeyStore}.
     * @return a new instance of {@code KeyStore} from the specified provider
     *         with the given type.
     * @throws KeyStoreException
     *             if an error occurred during the creation of the new {@code
     *             KeyStore}.
     * @throws IllegalArgumentException
     *             if {@code provider} is {@code null} or the empty string.
     * @throws NullPointerException if {@code type == null} (instead of
     *             NoSuchAlgorithmException) as in 1.4 release
     * @see #getDefaultType
     */
    public static KeyStore getInstance(String type, Provider provider) throws KeyStoreException {
        // check parameters
        if (provider == null) {
            throw new IllegalArgumentException();
        }
        if (type == null) {
            throw new NullPointerException("type == null");
        }
        // return KeyStore instance
        try {
            Object spi = ENGINE.getInstance(type, provider, null);
            return new KeyStore((KeyStoreSpi) spi, provider, type);
        } catch (Exception e) {
            // override exception
            throw new KeyStoreException(e);
        }
    }

    /**
     * Returns the default type for {@code KeyStore} instances.
     *
     * <p>The default is specified in the {@code 'keystore.type'} property in the
     * file named {@code java.security} properties file. If this property
     * is not set, {@code "jks"} will be used.
     *
     * @return the default type for {@code KeyStore} instances
     */
    public static final String getDefaultType() {
        String dt = Security.getProperty(PROPERTYNAME);
        return (dt == null ? DEFAULT_KEYSTORE_TYPE : dt);
    }

    /**
     * Returns the provider associated with this {@code KeyStore}.
     *
     * @return the provider associated with this {@code KeyStore}.
     */
    public final Provider getProvider() {
        return provider;
    }

    /**
     * Returns the type of this {@code KeyStore}.
     *
     * @return the type of this {@code KeyStore}.
     */
    public final String getType() {
        return type;
    }

    /**
     * Returns the key with the given alias, using the password to recover the
     * key from the store.
     *
     * @param alias
     *            the alias for the entry.
     * @param password
     *            the password used to recover the key.
     * @return the key with the specified alias, or {@code null} if the
     *         specified alias is not bound to an entry.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     * @throws NoSuchAlgorithmException
     *             if the algorithm for recovering the key is not available.
     * @throws UnrecoverableKeyException
     *             if the key can not be recovered.
     */
    public final Key getKey(String alias, char[] password)
            throws KeyStoreException, NoSuchAlgorithmException,
            UnrecoverableKeyException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineGetKey(alias, password);
    }

    /**
     * Returns the certificate chain for the entry with the given alias.
     *
     * @param alias
     *            the alias for the entry.
     * @return the certificate chain for the entry with the given alias, or
     *         {@code null} if the specified alias is not bound to an entry.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final Certificate[] getCertificateChain(String alias) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineGetCertificateChain(alias);
    }

    /**
     * Returns the trusted certificate for the entry with the given alias.
     *
     * @param alias
     *            the alias for the entry.
     * @return the trusted certificate for the entry with the given alias, or
     *         {@code null} if the specified alias is not bound to an entry.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final Certificate getCertificate(String alias) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineGetCertificate(alias);
    }

    /**
     * Returns the creation date of the entry with the given alias.
     *
     * @param alias
     *            the alias for the entry.
     * @return the creation date, or {@code null} if the specified alias is not
     *         bound to an entry.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final Date getCreationDate(String alias) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineGetCreationDate(alias);
    }

    /**
     * Associates the given alias with the key, password and certificate chain.
     * <p>
     * If the specified alias already exists, it will be reassigned.
     *
     * @param alias
     *            the alias for the key.
     * @param key
     *            the key.
     * @param password
     *            the password.
     * @param chain
     *            the certificate chain.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     * @throws IllegalArgumentException
     *             if {@code key} is a {@code PrivateKey} and {@code chain} does
     *             not contain any certificates.
     * @throws NullPointerException
     *             if {@code alias} is {@code null}.
     */
    public final void setKeyEntry(String alias, Key key, char[] password,
            Certificate[] chain) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }

        // Certificate chain is required for PrivateKey
        if (key != null && key instanceof PrivateKey && (chain == null || chain.length == 0)) {
            throw new IllegalArgumentException("Certificate chain is not defined for Private key");
        }
        implSpi.engineSetKeyEntry(alias, key, password, chain);
    }

    /**
     * Associates the given alias with a key and a certificate chain.
     * <p>
     * If the specified alias already exists, it will be reassigned.
     * <p>
     * If this {@code KeyStore} is of type {@code "jks"}, {@code key} must be
     * encoded conform to the PKS#8 standard as an
     * {@link javax.crypto.EncryptedPrivateKeyInfo}.
     *
     * @param alias
     *            the alias for the key.
     * @param key
     *            the key in an encoded format.
     * @param chain
     *            the certificate chain.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized or if {@code key}
     *             is null.
     * @throws IllegalArgumentException
     *             if {@code key} is a {@code PrivateKey} and {@code chain}
     *             does.
     * @throws NullPointerException
     *             if {@code alias} is {@code null}.
     */
    public final void setKeyEntry(String alias, byte[] key, Certificate[] chain)
            throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        implSpi.engineSetKeyEntry(alias, key, chain);
    }

    /**
     * Associates the given alias with a certificate.
     * <p>
     * If the specified alias already exists, it will be reassigned.
     *
     * @param alias
     *            the alias for the certificate.
     * @param cert
     *            the certificate.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized, or an existing
     *             alias is not associated to an entry containing a trusted
     *             certificate, or this method fails for any other reason.
     * @throws NullPointerException
     *             if {@code alias} is {@code null}.
     */
    public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        implSpi.engineSetCertificateEntry(alias, cert);
    }

    /**
     * Deletes the entry identified with the given alias from this {@code
     * KeyStore}.
     *
     * @param alias
     *            the alias for the entry.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized, or if the entry
     *             can not be deleted.
     */
    public final void deleteEntry(String alias) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        implSpi.engineDeleteEntry(alias);
    }

    /**
     * Returns an {@code Enumeration} over all alias names stored in this
     * {@code KeyStore}.
     *
     * @return an {@code Enumeration} over all alias names stored in this
     *         {@code KeyStore}.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final Enumeration<String> aliases() throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineAliases();
    }

    /**
     * Indicates whether the given alias is present in this {@code KeyStore}.
     *
     * @param alias
     *            the alias of an entry.
     * @return {@code true} if the alias exists, {@code false} otherwise.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final boolean containsAlias(String alias) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineContainsAlias(alias);
    }

    /**
     * Returns the number of entries stored in this {@code KeyStore}.
     *
     * @return the number of entries stored in this {@code KeyStore}.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final int size() throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineSize();
    }

    /**
     * Indicates whether the specified alias is associated with either a
     * {@link PrivateKeyEntry} or a {@link SecretKeyEntry}.
     *
     * @param alias
     *            the alias of an entry.
     * @return {@code true} if the given alias is associated with a key entry.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final boolean isKeyEntry(String alias) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineIsKeyEntry(alias);
    }

    /**
     * Indicates whether the specified alias is associated with a
     * {@link TrustedCertificateEntry}.
     *
     * @param alias
     *            the alias of an entry.
     * @return {@code true} if the given alias is associated with a certificate
     *         entry.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final boolean isCertificateEntry(String alias) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineIsCertificateEntry(alias);
    }

    /**
     * Returns the alias associated with the first entry whose certificate
     * matches the specified certificate.
     *
     * @param cert
     *            the certificate to find the associated entry's alias for.
     * @return the alias or {@code null} if no entry with the specified
     *         certificate can be found.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final String getCertificateAlias(Certificate cert) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineGetCertificateAlias(cert);
    }

    /**
     * Writes this {@code KeyStore} to the specified {@code OutputStream}. The
     * data written to the {@code OutputStream} is protected by the specified
     * password.
     *
     * @param stream
     *            the {@code OutputStream} to write the store's data to.
     * @param password
     *            the password to protect the data.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     * @throws IOException
     *             if a problem occurred while writing to the stream.
     * @throws NoSuchAlgorithmException
     *             if the required algorithm is not available.
     * @throws CertificateException
     *             if an exception occurred while storing the certificates of
     *             this {@code KeyStore}.
     */
    public final void store(OutputStream stream, char[] password)
            throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
        if (!isInit) {
            throwNotInitialized();
        }

        //Just delegate stream and password to implSpi
        implSpi.engineStore(stream, password);
    }

    /**
     * Stores this {@code KeyStore} using the specified {@code
     * LoadStoreParameter}.
     *
     * @param param
     *            the {@code LoadStoreParameter} that specifies how to store
     *            this {@code KeyStore}, maybe {@code null}.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     * @throws IOException
     *             if a problem occurred while writing to the stream.
     * @throws NoSuchAlgorithmException
     *             if the required algorithm is not available.
     * @throws CertificateException
     *             if an exception occurred while storing the certificates of
     *             this {@code KeyStore}.
     * @throws IllegalArgumentException
     *             if the given {@link LoadStoreParameter} is not recognized.
     */
    public final void store(LoadStoreParameter param) throws KeyStoreException,
            IOException, NoSuchAlgorithmException, CertificateException {
        if (!isInit) {
            throwNotInitialized();
        }
        implSpi.engineStore(param);
    }

    /**
     * Initializes this {@code KeyStore} from the provided {@code InputStream}.
     * Pass {@code null} as the {@code stream} argument to initialize an empty
     * {@code KeyStore} or to initialize a {@code KeyStore} which does not rely
     * on an {@code InputStream}. This {@code KeyStore} utilizes the given
     * password to verify the stored data.
     *
     * @param stream
     *            the {@code InputStream} to load this {@code KeyStore}'s data
     *            from or {@code null}.
     * @param password
     *            the password to verify the stored data, maybe {@code null}.
     * @throws IOException
     *             if a problem occurred while reading from the stream.
     * @throws NoSuchAlgorithmException
     *             if the required algorithm is not available.
     * @throws CertificateException
     *             if an exception occurred while loading the certificates of
     *             this {@code KeyStore}.
     */
    public final void load(InputStream stream, char[] password)
            throws IOException, NoSuchAlgorithmException, CertificateException {
        implSpi.engineLoad(stream, password);
        isInit = true;
    }

    /**
     * Loads this {@code KeyStore} using the specified {@code
     * LoadStoreParameter}.
     *
     * @param param
     *            the {@code LoadStoreParameter} that specifies how to load this
     *            {@code KeyStore}, maybe {@code null}.
     * @throws IOException
     *             if a problem occurred while reading from the stream.
     * @throws NoSuchAlgorithmException
     *             if the required algorithm is not available.
     * @throws CertificateException
     *             if an exception occurred while loading the certificates of
     *             this {@code KeyStore}.
     * @throws IllegalArgumentException
     *             if the given {@link LoadStoreParameter} is not recognized.
     */
    public final void load(LoadStoreParameter param) throws IOException,
            NoSuchAlgorithmException, CertificateException {
        implSpi.engineLoad(param);
        isInit = true;
    }

    /**
     * Returns the {@code Entry} with the given alias, using the specified
     * {@code ProtectionParameter}.
     *
     * @param alias
     *            the alias of the requested entry.
     * @param param
     *            the {@code ProtectionParameter} used to protect the requested
     *            entry, maybe {@code null}.
     * @return he {@code Entry} with the given alias, using the specified
     *         {@code ProtectionParameter}.
     * @throws NoSuchAlgorithmException
     *             if the required algorithm is not available.
     * @throws UnrecoverableEntryException
     *             if the entry can not be recovered.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     * @throws NullPointerException
     *             if {@code alias} is {@code null}.
     */
    public final Entry getEntry(String alias, ProtectionParameter param)
            throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException {
        if (alias == null) {
            throw new NullPointerException("alias == null");
        }
        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineGetEntry(alias, param);
    }

    /**
     * Stores the given {@code Entry} in this {@code KeyStore} and associates
     * the entry with the given {@code alias}. The entry is protected by the
     * specified {@code ProtectionParameter}.
     * <p>
     * If the specified alias already exists, it will be reassigned.
     *
     * @param alias
     *            the alias for the entry.
     * @param entry
     *            the entry to store.
     * @param param
     *            the {@code ProtectionParameter} to protect the entry.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     * @throws NullPointerException
     *             if {@code alias} is {@code null} or {@code entry} is {@code
     *             null}.
     */
    public final void setEntry(String alias, Entry entry,
            ProtectionParameter param) throws KeyStoreException {
        if (!isInit) {
            throwNotInitialized();
        }
        if (alias == null) {
            throw new NullPointerException("alias == null");
        }
        if (entry == null) {
            throw new NullPointerException("entry == null");
        }
        implSpi.engineSetEntry(alias, entry, param);
    }

    /**
     * Indicates whether the entry for the given alias is assignable to the
     * provided {@code Class}.
     *
     * @param alias
     *            the alias for the entry.
     * @param entryClass
     *            the type of the entry.
     * @return {@code true} if the {@code Entry} for the alias is assignable to
     *         the specified {@code entryClass}.
     * @throws KeyStoreException
     *             if this {@code KeyStore} is not initialized.
     */
    public final boolean entryInstanceOf(String alias,
            Class<? extends KeyStore.Entry> entryClass)
            throws KeyStoreException {
        if (alias == null) {
            throw new NullPointerException("alias == null");
        }
        if (entryClass == null) {
            throw new NullPointerException("entryClass == null");
        }

        if (!isInit) {
            throwNotInitialized();
        }
        return implSpi.engineEntryInstanceOf(alias, entryClass);
    }

    /**
     * {@code Builder} is used to construct new instances of {@code KeyStore}.
     */
    public abstract static class Builder {
        /**
         * Constructs a new instance of {@code Builder}.
         */
        protected Builder() {
        }

        /**
         * Returns the {@code KeyStore} created by this {@code Builder}.
         *
         * @return the {@code KeyStore} created by this {@code Builder}.
         * @throws KeyStoreException
         *             if an error occurred during construction.
         */
        public abstract KeyStore getKeyStore() throws KeyStoreException;

        /**
         * Returns the {@code ProtectionParameter} to be used when a {@code
         * Entry} with the specified alias is requested. Before this method is
         * invoked, {@link #getKeyStore()} must be called.
         *
         * @param alias
         *            the alias for the entry.
         * @return the {@code ProtectionParameter} to be used when a {@code
         *         Entry} with the specified alias is requested.
         * @throws KeyStoreException
         *             if an error occurred during the lookup for the protection
         *             parameter.
         * @throws IllegalStateException
         *             if {@link #getKeyStore()} is not called prior the
         *             invocation of this method.
         * @throws NullPointerException
         *             if {@code alias} is {@code null}.
         */
        public abstract ProtectionParameter getProtectionParameter(String alias)
                throws KeyStoreException;

        /**
         * Returns a new {@code Builder} that holds the given {@code KeyStore}
         * and the given {@code ProtectionParameter}.
         *
         * @param keyStore
         *            the {@code KeyStore} to be held.
         * @param protectionParameter
         *            the {@code ProtectionParameter} to be held.
         * @return a new instance of {@code Builder} that holds the specified
         *         {@code KeyStore} and the specified {@code
         *         ProtectionParameter}.
         * @throws NullPointerException
         *             if {@code keyStore} or {@code protectionParameter} is
         *             {@code null}.
         * @throws IllegalArgumentException
         *             if the given {@code KeyStore} is not initialized.
         */
        public static Builder newInstance(KeyStore keyStore,
                ProtectionParameter protectionParameter) {
            if (keyStore == null) {
                throw new NullPointerException("keyStore == null");
            }
            if (protectionParameter == null) {
                throw new NullPointerException("protectionParameter == null");
            }
            if (!keyStore.isInit) {
                throw new IllegalArgumentException("KeyStore was not initialized");
            }
            return new BuilderImpl(keyStore, protectionParameter, null, null, null);
        }

        /**
         * Returns a new {@code Builder} that creates a new {@code KeyStore}
         * based on the provided arguments.
         * <p>
         * If {@code provider} is {@code null}, all installed providers are
         * searched, otherwise the key store from the specified provider is
         * used.
         *
         * @param type
         *            the type of the {@code KeyStore} to be constructed.
         * @param provider
         *            the provider of the {@code KeyStore} to be constructed,
         *            maybe {@code null}.
         * @param file
         *            the {@code File} that contains the data for the {@code
         *            KeyStore}.
         * @param protectionParameter
         *            the {@code ProtectionParameter} used to protect the stored
         *            keys.
         * @return a new {@code Builder} that creates a new {@code KeyStore}
         *         based on the provided arguments.
         * @throws NullPointerException
         *             if {@code type, protectionParameter} or {@code file} is
         *             {@code null}.
         * @throws IllegalArgumentException
         *             {@code protectionParameter} not an instance of either
         *             {@code PasswordProtection} or {@code
         *             CallbackHandlerProtection}, {@code file} is not a file or
         *             does not exist at all.
         */
        public static Builder newInstance(String type, Provider provider,
                File file, ProtectionParameter protectionParameter) {
            // check null parameters
            if (type == null) {
                throw new NullPointerException("type == null");
            }
            if (protectionParameter == null) {
                throw new NullPointerException("protectionParameter == null");
            }
            if (file == null) {
                throw new NullPointerException("file == null");
            }
            // protection parameter should be PasswordProtection or
            // CallbackHandlerProtection
            if (!(protectionParameter instanceof PasswordProtection)
                    && !(protectionParameter instanceof CallbackHandlerProtection)) {
                throw new IllegalArgumentException("protectionParameter is neither "
                        + "PasswordProtection nor CallbackHandlerProtection instance");
            }
            // check file parameter
            if (!file.exists()) {
                throw new IllegalArgumentException("File does not exist: " + file.getName());
            }
            if (!file.isFile()) {
                throw new IllegalArgumentException("Not a regular file: " + file.getName());
            }
            // create new instance
            return new BuilderImpl(null, protectionParameter, file, type, provider);
        }

        /**
         * Returns a new {@code Builder} that creates a new {@code KeyStore}
         * based on the provided arguments.
         * <p>
         * If {@code provider} is {@code null}, all installed providers are
         * searched, otherwise the key store from the specified provider is
         * used.
         *
         * @param type
         *            the type of the {@code KeyStore} to be constructed.
         * @param provider
         *            the provider of the {@code KeyStore} to be constructed,
         *            maybe {@code null}.
         * @param protectionParameter
         *            the {@code ProtectionParameter} used to protect the stored
         *            keys.
         * @return a new {@code Builder} that creates a new {@code KeyStore}
         *         based on the provided arguments.
         * @throws NullPointerException
         *             if {@code type} or {@code protectionParameter} is {@code
         *             null}.
         * @throws IllegalArgumentException
         *             {@code protectionParameter} not an instance of either
         *             {@code PasswordProtection} or {@code
         *             CallbackHandlerProtection}, {@code file} is not a file or
         *             does not exist at all.
         */
        public static Builder newInstance(String type, Provider provider,
                ProtectionParameter protectionParameter) {
            if (type == null) {
                throw new NullPointerException("type == null");
            }
            if (protectionParameter == null) {
                throw new NullPointerException("protectionParameter == null");
            }
            return new BuilderImpl(null, protectionParameter, null, type, provider);
        }

        /*
         * This class is implementation of abstract class KeyStore.Builder
         *
         * @author Vera Petrashkova
         *
         */
        private static class BuilderImpl extends Builder {
            // Store used KeyStore
            private KeyStore keyStore;

            // Store used ProtectionParameter
            private ProtectionParameter protParameter;

            // Store used KeyStore type
            private final String typeForKeyStore;

            // Store used KeyStore provider
            private final Provider providerForKeyStore;

            // Store used file for KeyStore loading
            private final File fileForLoad;

            // Store getKeyStore method was invoked or not for KeyStoreBuilder
            private boolean isGetKeyStore = false;

            // Store last Exception in getKeyStore()
            private KeyStoreException lastException;

            /**
             * Constructor BuilderImpl initializes private fields: keyStore,
             * protParameter, typeForKeyStore providerForKeyStore fileForLoad,
             * isGetKeyStore
             */
            BuilderImpl(KeyStore ks, ProtectionParameter pp, File file,
                        String type, Provider provider) {
                keyStore = ks;
                protParameter = pp;
                fileForLoad = file;
                typeForKeyStore = type;
                providerForKeyStore = provider;
                isGetKeyStore = false;
                lastException = null;
            }

            /**
             * Implementation of abstract getKeyStore() method If
             * KeyStoreBuilder encapsulates KeyStore object then this object is
             * returned
             *
             * If KeyStoreBuilder encapsulates KeyStore type and provider then
             * KeyStore is created using these parameters. If KeyStoreBuilder
             * encapsulates file and ProtectionParameter then KeyStore data are
             * loaded from FileInputStream that is created on file. If file is
             * not defined then KeyStore object is initialized with null
             * InputStream and null password.
             *
             * Result KeyStore object is returned.
             */
            @Override
            public synchronized KeyStore getKeyStore() throws KeyStoreException {
                // If KeyStore was created but in final block some exception was
                // thrown
                // then it was stored in lastException variable and will be
                // thrown
                // all subsequent calls of this method.
                if (lastException != null) {
                    throw lastException;
                }
                if (keyStore != null) {
                    isGetKeyStore = true;
                    return keyStore;
                }

                try {
                    // get KeyStore instance using type or type and provider
                    final KeyStore ks = (providerForKeyStore == null ? KeyStore
                            .getInstance(typeForKeyStore) : KeyStore
                            .getInstance(typeForKeyStore, providerForKeyStore));
                    // protection parameter should be PasswordProtection
                    // or CallbackHandlerProtection
                    final char[] passwd;
                    if (protParameter instanceof PasswordProtection) {
                        passwd = ((PasswordProtection) protParameter)
                                .getPassword();
                    } else if (protParameter instanceof CallbackHandlerProtection) {
                        passwd = KeyStoreSpi
                                .getPasswordFromCallBack(protParameter);
                    } else {
                        throw new KeyStoreException("protectionParameter is neither "
                                + "PasswordProtection nor CallbackHandlerProtection instance");
                    }

                    // load KeyStore from file
                    if (fileForLoad != null) {
                        FileInputStream fis = null;
                        try {
                            fis = new FileInputStream(fileForLoad);
                            ks.load(fis, passwd);
                        } finally {
                            IoUtils.closeQuietly(fis);
                        }
                    } else {
                        ks.load(new TmpLSParameter(protParameter));
                    }

                    isGetKeyStore = true;
                    return ks;
                } catch (KeyStoreException e) {
                    // Store exception
                    throw lastException = e;
                } catch (Exception e) {
                    // Override exception
                    throw lastException = new KeyStoreException(e);
                }
            }

            /**
             * This is implementation of abstract method
             * getProtectionParameter(String alias)
             *
             * Return: ProtectionParameter to get Entry which was saved in
             * KeyStore with defined alias
             */
            @Override
            public synchronized ProtectionParameter getProtectionParameter(
                    String alias) throws KeyStoreException {
                if (alias == null) {
                    throw new NullPointerException("alias == null");
                }
                if (!isGetKeyStore) {
                    throw new IllegalStateException("getKeyStore() was not invoked");
                }
                return protParameter;
            }
        }

        /*
         * Implementation of LoadStoreParameter interface
         */
        private static class TmpLSParameter implements LoadStoreParameter {

            // Store used protection parameter
            private final ProtectionParameter protPar;

            /**
             * Creates TmpLoadStoreParameter object
             * @param protPar protection parameter
             */
            public TmpLSParameter(ProtectionParameter protPar) {
                this.protPar = protPar;
            }

            /**
             * This method returns protection parameter
             */
            public ProtectionParameter getProtectionParameter() {
                return protPar;
            }
        }
    }

    /**
     * {@code CallbackHandlerProtection} is a {@code ProtectionParameter} that
     * encapsulates a {@link CallbackHandler}.
     */
    public static class CallbackHandlerProtection implements
            ProtectionParameter {
        // Store CallbackHandler
        private final CallbackHandler callbackHandler;

        /**
         * Constructs a new instance of {@code CallbackHandlerProtection} with
         * the {@code CallbackHandler}.
         *
         * @param handler
         *            the {@code CallbackHandler}.
         * @throws NullPointerException
         *             if {@code handler} is {@code null}.
         */
        public CallbackHandlerProtection(CallbackHandler handler) {
            if (handler == null) {
                throw new NullPointerException("handler == null");
            }
            this.callbackHandler = handler;
        }

        /**
         * Returns the {@code CallbackHandler}.
         *
         * @return the {@code CallbackHandler}.
         */
        public CallbackHandler getCallbackHandler() {
            return callbackHandler;
        }
    }

    /**
     * {@code Entry} is the common marker interface for a {@code KeyStore}
     * entry.
     */
    public static interface Entry {
    }

    /**
     * {@code LoadStoreParameter} represents a parameter that specifies how a
     * {@code KeyStore} can be loaded and stored.
     *
     * @see KeyStore#load(LoadStoreParameter)
     * @see KeyStore#store(LoadStoreParameter)
     */
    public static interface LoadStoreParameter {
        /**
         * Returns the {@code ProtectionParameter} which is used to protect data
         * in the {@code KeyStore}.
         *
         * @return the {@code ProtectionParameter} which is used to protect data
         *         in the {@code KeyStore}, maybe {@code null}.
         */
        public ProtectionParameter getProtectionParameter();
    }

    /**
     * {@code PasswordProtection} is a {@code ProtectionParameter} that protects
     * a {@code KeyStore} using a password.
     */
    public static class PasswordProtection implements ProtectionParameter,
            Destroyable {

        // Store password
        private char[] password;

        private boolean isDestroyed = false;

        /**
         * Constructs a new instance of {@code PasswordProtection} with a
         * password. A copy of the password is stored in the new {@code
         * PasswordProtection} object.
         *
         * @param password
         *            the password, maybe {@code null}.
         */
        public PasswordProtection(char[] password) {
            if (password != null) {
                this.password = password.clone();
            }
        }

        /**
         * Returns the password.
         *
         * @return the password.
         * @throws IllegalStateException
         *             if the password has been destroyed.
         */
        public synchronized char[] getPassword() {
            if (isDestroyed) {
                throw new IllegalStateException("Password was destroyed");
            }
            return password;
        }

        /**
         * Destroys / invalidates the password.
         *
         * @throws DestroyFailedException
         *             if the password could not be invalidated.
         */
        public synchronized void destroy() throws DestroyFailedException {
            isDestroyed = true;
            if (password != null) {
                Arrays.fill(password, '\u0000');
                password = null;
            }
        }

        /**
         * Indicates whether the password is invalidated.
         *
         * @return {@code true} if the password is invalidated, {@code false}
         *         otherwise.
         */
        public synchronized boolean isDestroyed() {
            return isDestroyed;
        }
    }

    /**
     * {@code ProtectionParameter} is a marker interface for protection
     * parameters. A protection parameter is used to protect the content of a
     * {@code KeyStore}.
     */
    public static interface ProtectionParameter {
    }

    /**
     * {@code PrivateKeyEntry} represents a {@code KeyStore} entry that
     * holds a private key.
     */
    public static final class PrivateKeyEntry implements Entry {
        // Store Certificate chain
        private Certificate[] chain;

        // Store PrivateKey
        private PrivateKey privateKey;

        /**
         * Constructs a new instance of {@code PrivateKeyEntry} with the given
         * {@code PrivateKey} and the provided certificate chain.
         *
         * @param privateKey
         *            the private key.
         * @param chain
         *            the ordered certificate chain with the certificate
         *            corresponding to the private key at index 0.
         * @throws NullPointerException
         *             if {@code privateKey} or {@code chain} is {@code null}.
         * @throws IllegalArgumentException
         *             if {@code chain.length == 0}, the algorithm of the
         *             private key does not match the algorithm of the public
         *             key of the first certificate or the certificates are not
         *             all of the same type.
         */
        public PrivateKeyEntry(PrivateKey privateKey, Certificate[] chain) {
            if (privateKey == null) {
                throw new NullPointerException("privateKey == null");
            }
            if (chain == null) {
                throw new NullPointerException("chain == null");
            }

            if (chain.length == 0) {
                throw new IllegalArgumentException("chain.length == 0");
            }
            // Match algorithm of private key and algorithm of public key from
            // the end certificate
            String s = chain[0].getType();
            if (!(chain[0].getPublicKey().getAlgorithm()).equals(privateKey.getAlgorithm())) {
                throw new IllegalArgumentException("Algorithm of private key does not match "
                        + "algorithm of public key in end certificate of entry "
                        + "(with index number: 0)");
            }
            // Match certificate types
            for (int i = 1; i < chain.length; i++) {
                if (!s.equals(chain[i].getType())) {
                    throw new IllegalArgumentException("Certificates from the given chain have "
                                                       + "different types");
                }
            }
            // clone chain - this.chain = (Certificate[])chain.clone();
            boolean isAllX509Certificates = true;
            // assert chain length > 0
            for (Certificate cert: chain) {
                if (!(cert instanceof X509Certificate)) {
                    isAllX509Certificates = false;
                    break;
                }
            }

            if(isAllX509Certificates){
                this.chain = new X509Certificate[chain.length];
            } else {
                this.chain = new Certificate[chain.length];
            }
            System.arraycopy(chain, 0, this.chain, 0, chain.length);
            this.privateKey = privateKey;
        }

        /**
         * Returns the private key.
         *
         * @return the private key.
         */
        public PrivateKey getPrivateKey() {
            return privateKey;
        }

        /**
         * Returns the certificate chain.
         *
         * @return the certificate chain.
         */
        public Certificate[] getCertificateChain() {
            return chain.clone();
        }

        /**
         * Returns the certificate corresponding to the private key.
         *
         * @return the certificate corresponding to the private key.
         */
        public Certificate getCertificate() {
            return chain[0];
        }

        /**
         * Returns a string containing a concise, human-readable description of
         * this {@code PrivateKeyEntry}.
         *
         * @return a printable representation for this {@code PrivateKeyEntry}.
         */
        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder(
                    "PrivateKeyEntry: number of elements in certificate chain is ");
            sb.append(Integer.toString(chain.length));
            sb.append("\n");
            for (int i = 0; i < chain.length; i++) {
                sb.append(chain[i].toString());
                sb.append("\n");
            }
            return sb.toString();
        }
    }

    /**
     * {@code SecretKeyEntry} represents a {@code KeyStore} entry that
     * holds a secret key.
     */
    public static final class SecretKeyEntry implements Entry {

        // Store SecretKey
        private final SecretKey secretKey;

        /**
         * Constructs a new instance of {@code SecretKeyEntry} with the given
         * {@code SecretKey}.
         *
         * @param secretKey
         *            the secret key.
         * @throws NullPointerException
         *             if {@code secretKey} is {@code null}.
         */
        public SecretKeyEntry(SecretKey secretKey) {
            if (secretKey == null) {
                throw new NullPointerException("secretKey == null");
            }
            this.secretKey = secretKey;
        }

        /**
         * Returns the secret key.
         *
         * @return the secret key.
         */
        public SecretKey getSecretKey() {
            return secretKey;
        }

        /**
         * Returns a string containing a concise, human-readable description of
         * this {@code SecretKeyEntry}.
         *
         * @return a printable representation for this {@code
         *         SecretKeyEntry}.
         */
        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder("SecretKeyEntry: algorithm - ");
            sb.append(secretKey.getAlgorithm());
            return sb.toString();
        }
    }

    /**
     * {@code TrustedCertificateEntry} represents a {@code KeyStore} entry that
     * holds a trusted certificate.
     */
    public static final class TrustedCertificateEntry implements Entry {

        // Store trusted Certificate
        private final Certificate trustCertificate;

        /**
         * Constructs a new instance of {@code TrustedCertificateEntry} with the
         * given {@code Certificate}.
         *
         * @param trustCertificate
         *            the trusted certificate.
         * @throws NullPointerException
         *             if {@code trustCertificate} is {@code null}.
         */
        public TrustedCertificateEntry(Certificate trustCertificate) {
            if (trustCertificate == null) {
                throw new NullPointerException("trustCertificate == null");
            }
            this.trustCertificate = trustCertificate;
        }

        /**
         * Returns the trusted certificate.
         *
         * @return the trusted certificate.
         */
        public Certificate getTrustedCertificate() {
            return trustCertificate;
        }

        /**
         * Returns a string containing a concise, human-readable description of
         * this {@code TrustedCertificateEntry}.
         *
         * @return a printable representation for this {@code
         *         TrustedCertificateEntry}.
         */
        @Override
        public String toString() {
            return "Trusted certificate entry:\n" + trustCertificate;
        }
    }
}