-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathXMLCipher.java
More file actions
3703 lines (3260 loc) · 137 KB
/
XMLCipher.java
File metadata and controls
3703 lines (3260 loc) · 137 KB
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
/**
* 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 org.apache.xml.security.encryption;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import javax.xml.transform.TransformerConfigurationException;
import org.apache.xml.security.algorithms.JCEMapper;
import org.apache.xml.security.algorithms.MessageDigestAlgorithm;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
import org.apache.xml.security.encryption.keys.KeyInfoEnc;
import org.apache.xml.security.encryption.params.KeyAgreementParameters;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.encryption.keys.content.AgreementMethodImpl;
import org.apache.xml.security.keys.keyresolver.KeyResolverException;
import org.apache.xml.security.keys.keyresolver.KeyResolverSpi;
import org.apache.xml.security.keys.keyresolver.implementations.EncryptedKeyResolver;
import org.apache.xml.security.signature.XMLSignatureException;
import org.apache.xml.security.stax.ext.XMLSecurityConstants;
import org.apache.xml.security.transforms.InvalidTransformException;
import org.apache.xml.security.transforms.TransformationException;
import org.apache.xml.security.utils.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* <code>XMLCipher</code> encrypts and decrypts the contents of
* <code>Document</code>s, <code>Element</code>s and <code>Element</code>
* contents. It was designed to resemble <code>javax.crypto.Cipher</code> in
* order to facilitate understanding of its functioning.
*
*/
public final class XMLCipher {
private static final Logger LOG = System.getLogger(XMLCipher.class.getName());
/** Triple DES EDE (192 bit key) in CBC mode */
public static final String TRIPLEDES =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_TRIPLEDES;
/** AES 128 Cipher */
public static final String AES_128 =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128;
/** AES 256 Cipher */
public static final String AES_256 =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256;
/** AES 192 Cipher */
public static final String AES_192 =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192;
/** AES 128 GCM Cipher */
public static final String AES_128_GCM =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM;
/** AES 192 GCM Cipher */
public static final String AES_192_GCM =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM;
/** AES 256 GCM Cipher */
public static final String AES_256_GCM =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM;
/** SEED 128 Cipher */
public static final String SEED_128 =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_SEED128;
/** CAMELLIA 128 Cipher */
public static final String CAMELLIA_128 =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_CAMELLIA128;
/** CAMELLIA 192 Cipher */
public static final String CAMELLIA_192 =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_CAMELLIA192;
/** CAMELLIA 256 Cipher */
public static final String CAMELLIA_256 =
EncryptionConstants.ALGO_ID_BLOCKCIPHER_CAMELLIA256;
/** RSA 1.5 Cipher */
public static final String RSA_v1dot5 =
EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15;
/** RSA OAEP Cipher */
public static final String RSA_OAEP =
EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP;
/** RSA OAEP Cipher */
public static final String RSA_OAEP_11 =
EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP_11;
/** DIFFIE_HELLMAN Cipher */
public static final String DIFFIE_HELLMAN =
EncryptionConstants.ALGO_ID_KEYAGREEMENT_DH;
/**
* DIFFIE_HELLMAN ES Cipher for Elliptic curve and X keys
*/
public static final String DIFFIE_HELLMAN_EC =
EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES;
/** Triple DES EDE (192 bit key) in CBC mode KEYWRAP*/
public static final String TRIPLEDES_KeyWrap =
EncryptionConstants.ALGO_ID_KEYWRAP_TRIPLEDES;
/** AES 128 Cipher KeyWrap */
public static final String AES_128_KeyWrap =
EncryptionConstants.ALGO_ID_KEYWRAP_AES128;
/** AES 256 Cipher KeyWrap */
public static final String AES_256_KeyWrap =
EncryptionConstants.ALGO_ID_KEYWRAP_AES256;
/** AES 192 Cipher KeyWrap */
public static final String AES_192_KeyWrap =
EncryptionConstants.ALGO_ID_KEYWRAP_AES192;
/** CAMELLIA 128 Cipher KeyWrap */
public static final String CAMELLIA_128_KeyWrap =
EncryptionConstants.ALGO_ID_KEYWRAP_CAMELLIA128;
/** CAMELLIA 192 Cipher KeyWrap */
public static final String CAMELLIA_192_KeyWrap =
EncryptionConstants.ALGO_ID_KEYWRAP_CAMELLIA192;
/** CAMELLIA 256 Cipher KeyWrap */
public static final String CAMELLIA_256_KeyWrap =
EncryptionConstants.ALGO_ID_KEYWRAP_CAMELLIA256;
/** SEED 128 Cipher KeyWrap */
public static final String SEED_128_KeyWrap =
EncryptionConstants.ALGO_ID_KEYWRAP_SEED128;
/** SHA1 Cipher */
public static final String SHA1 =
Constants.ALGO_ID_DIGEST_SHA1;
/** SHA256 Cipher */
public static final String SHA256 =
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256;
/** SHA512 Cipher */
public static final String SHA512 =
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512;
/** RIPEMD Cipher */
public static final String RIPEMD_160 =
MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160;
/** XML Signature NS */
public static final String XML_DSIG =
Constants.SignatureSpecNS;
/** N14C_XML */
public static final String N14C_XML =
Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
/** N14C_XML with comments*/
public static final String N14C_XML_WITH_COMMENTS =
Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
/** N14C_XML exclusive */
public static final String EXCL_XML_N14C =
Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
/** N14C_XML exclusive with comments*/
public static final String EXCL_XML_N14C_WITH_COMMENTS =
Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
/** N14C_PHYSICAL preserve the physical representation*/
public static final String PHYSICAL_XML_N14C =
Canonicalizer.ALGO_ID_C14N_PHYSICAL;
/** Base64 encoding */
public static final String BASE64_ENCODING =
org.apache.xml.security.transforms.Transforms.TRANSFORM_BASE64_DECODE;
/** ENCRYPT Mode */
public static final int ENCRYPT_MODE = Cipher.ENCRYPT_MODE;
/** DECRYPT Mode */
public static final int DECRYPT_MODE = Cipher.DECRYPT_MODE;
/** UNWRAP Mode */
public static final int UNWRAP_MODE = Cipher.UNWRAP_MODE;
/** WRAP Mode */
public static final int WRAP_MODE = Cipher.WRAP_MODE;
private static final String ENC_ALGORITHMS = TRIPLEDES + "\n" +
AES_128 + "\n" + AES_256 + "\n" + AES_192 + "\n" + RSA_v1dot5 + "\n" +
RSA_OAEP + "\n" + RSA_OAEP_11 + "\n" + TRIPLEDES_KeyWrap + "\n" +
AES_128_KeyWrap + "\n" + AES_256_KeyWrap + "\n" + AES_192_KeyWrap + "\n" +
AES_128_GCM + "\n" + AES_192_GCM + "\n" + AES_256_GCM + "\n" + SEED_128 + "\n" +
CAMELLIA_128 + "\n" + CAMELLIA_192 + "\n" + CAMELLIA_256 + "\n" +
CAMELLIA_128_KeyWrap + "\n" + CAMELLIA_192_KeyWrap + "\n" + CAMELLIA_256_KeyWrap + "\n" +
SEED_128_KeyWrap + "\n";
private static final Set<String> SUPPORTED_ALGORITHMS;
private static final boolean HAVE_FUNCTIONAL_IDENTITY_TRANSFORMER = haveFunctionalIdentityTransformer();
/** Cipher created during initialisation that is used for encryption */
private Cipher contextCipher;
/** Mode that the XMLCipher object is operating in */
private int cipherMode = Integer.MIN_VALUE;
/** URI of algorithm that is being used for cryptographic operation */
private final String algorithm;
/** Cryptographic provider requested by caller */
private final String requestedJCEProvider;
/** Used for creation of DOM nodes in WRAP and ENCRYPT modes */
private Document contextDocument;
/** Instance of factory used to create XML Encryption objects */
private final Factory factory;
/** Serializer class for going to/from UTF-8 */
private final Serializer serializer;
/** Local copy of user's key */
private Key key;
/** Local copy of the kek (used to decrypt EncryptedKeys during a
* DECRYPT_MODE operation */
private Key kek;
// The EncryptedKey being built (part of a WRAP operation) or read
// (part of an UNWRAP operation)
private EncryptedKey ek;
// The EncryptedData being built (part of a WRAP operation) or read
// (part of an UNWRAP operation)
private EncryptedData ed;
private boolean secureValidation = true;
private String digestAlg;
/** List of internal KeyResolvers for DECRYPT and UNWRAP modes. */
private List<KeyResolverSpi> internalKeyResolvers;
static {
Set<String> encryptionAlgorithms = new HashSet<>();
encryptionAlgorithms.add(TRIPLEDES);
encryptionAlgorithms.add(AES_128);
encryptionAlgorithms.add(AES_256);
encryptionAlgorithms.add(AES_192);
encryptionAlgorithms.add(AES_128_GCM);
encryptionAlgorithms.add(AES_192_GCM);
encryptionAlgorithms.add(AES_256_GCM);
encryptionAlgorithms.add(SEED_128);
encryptionAlgorithms.add(CAMELLIA_128);
encryptionAlgorithms.add(CAMELLIA_192);
encryptionAlgorithms.add(CAMELLIA_256);
encryptionAlgorithms.add(RSA_v1dot5);
encryptionAlgorithms.add(RSA_OAEP);
encryptionAlgorithms.add(RSA_OAEP_11);
encryptionAlgorithms.add(TRIPLEDES_KeyWrap);
encryptionAlgorithms.add(AES_128_KeyWrap);
encryptionAlgorithms.add(AES_256_KeyWrap);
encryptionAlgorithms.add(AES_192_KeyWrap);
encryptionAlgorithms.add(CAMELLIA_128_KeyWrap);
encryptionAlgorithms.add(CAMELLIA_192_KeyWrap);
encryptionAlgorithms.add(CAMELLIA_256_KeyWrap);
encryptionAlgorithms.add(SEED_128_KeyWrap);
SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(encryptionAlgorithms);
}
/**
* Creates a new <code>XMLCipher</code>.
*
* @param transformation the name of the transformation, e.g.,
* <code>XMLCipher.TRIPLEDES</code>. If null the XMLCipher can only
* be used for decrypt or unwrap operations where the encryption method
* is defined in the <code>EncryptionMethod</code> element.
* @param provider the JCE provider that supplies the transformation,
* if null use the default provider.
* @param digestMethod An optional digestMethod to use.
* @param serializer A Serializer instance to use
*/
private XMLCipher(
String transformation,
String provider,
String digestMethod,
Serializer serializer
) throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Constructing XMLCipher...");
factory = new Factory();
algorithm = transformation;
requestedJCEProvider = provider;
digestAlg = digestMethod;
this.serializer = serializer;
if (transformation != null) {
contextCipher = constructCipher(transformation, digestMethod);
}
}
private static Serializer createSerializer(boolean secureValidation) throws XMLEncryptionException {
return createSerializer(null, secureValidation);
}
private static Serializer createSerializer(String canonAlg, boolean secureValidation) throws XMLEncryptionException {
String c14nAlg = canonAlg != null ? canonAlg : Canonicalizer.ALGO_ID_C14N_PHYSICAL;
try {
if (HAVE_FUNCTIONAL_IDENTITY_TRANSFORMER) {
return new TransformSerializer(c14nAlg, secureValidation);
}
return new DocumentSerializer(c14nAlg, secureValidation);
} catch (InvalidCanonicalizerException | TransformerConfigurationException e) {
throw new XMLEncryptionException(e);
}
}
/**
* Checks to ensure that the supplied algorithm is valid.
*
* @param algorithm the algorithm to check.
* @return true if the algorithm is valid, otherwise false.
* @since 1.0.
*/
private static boolean isValidEncryptionAlgorithm(String algorithm) {
return SUPPORTED_ALGORITHMS.contains(algorithm);
}
/**
* Validate the transformation argument of getInstance or getProviderInstance
*
* @param transformation the name of the transformation, e.g.,
* <code>XMLCipher.TRIPLEDES</code> which is shorthand for
* "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"
*/
private static void validateTransformation(String transformation) {
if (null == transformation) {
throw new NullPointerException("Transformation unexpectedly null...");
}
if (!isValidEncryptionAlgorithm(transformation)) {
LOG.log(Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS);
}
}
/**
* Returns an <code>XMLCipher</code> that implements the specified
* transformation and operates on the specified context document.
* <p>
* If the default provider package supplies an implementation of the
* requested transformation, an instance of Cipher containing that
* implementation is returned. If the transformation is not available in
* the default provider package, other provider packages are searched.
* <p>
* <b>NOTE<sub>1</sub>:</b> The transformation name does not follow the same
* pattern as that outlined in the Java Cryptography Extension Reference
* Guide but rather that specified by the XML Encryption Syntax and
* Processing document. The rational behind this is to make it easier for a
* novice at writing Java Encryption software to use the library.
* <p>
* <b>NOTE<sub>2</sub>:</b> <code>getInstance()</code> does not follow the
* same pattern regarding exceptional conditions as that used in
* <code>javax.crypto.Cipher</code>. Instead, it only throws an
* <code>XMLEncryptionException</code> which wraps an underlying exception.
* The stack trace from the exception should be self explanatory.
*
* @param transformation the name of the transformation, e.g.,
* <code>XMLCipher.TRIPLEDES</code> which is shorthand for
* "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"
* @throws XMLEncryptionException
* @return the XMLCipher
* @see javax.crypto.Cipher#getInstance(java.lang.String)
*/
public static XMLCipher getInstance(String transformation) throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with transformation");
validateTransformation(transformation);
return new XMLCipher(transformation, null, null, createSerializer(true));
}
/**
* Returns an <code>XMLCipher</code> that implements the specified
* transformation, operates on the specified context document and serializes
* the document with the specified serializer before it
* encrypts the document.
* <p>
*
* @param serializer A custom Serializer instance
* @param transformation the name of the transformation
* @return the XMLCipher
* @throws XMLEncryptionException
*/
public static XMLCipher getInstance(Serializer serializer, String transformation) throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with transformation");
validateTransformation(transformation);
return new XMLCipher(transformation, null, null, serializer);
}
/**
* Returns an <code>XMLCipher</code> that implements the specified
* transformation, operates on the specified context document and serializes
* the document with the specified canonicalization algorithm before it
* encrypts the document.
* <p>
*
* @param transformation the name of the transformation
* @param canon the name of the c14n algorithm, if <code>null</code> use
* standard serializer
* @return the XMLCipher
* @throws XMLEncryptionException
*/
public static XMLCipher getInstance(String transformation, String canon)
throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with transformation and c14n algorithm");
validateTransformation(transformation);
return new XMLCipher(transformation, null, null, createSerializer(canon, true));
}
/**
* Returns an <code>XMLCipher</code> that implements the specified
* transformation, operates on the specified context document and serializes
* the document with the specified canonicalization algorithm before it
* encrypts the document.
* <p>
*
* @param transformation the name of the transformation
* @param canon the name of the c14n algorithm, if <code>null</code> use
* standard serializer
* @param digestMethod An optional digestMethod to use
* @return the XMLCipher
* @throws XMLEncryptionException
*/
public static XMLCipher getInstance(String transformation, String canon, String digestMethod)
throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with transformation and c14n algorithm");
validateTransformation(transformation);
return new XMLCipher(transformation, null, digestMethod, createSerializer(canon, true));
}
/**
* Returns an <code>XMLCipher</code> that implements the specified
* transformation and operates on the specified context document.
*
* @param transformation the name of the transformation
* @param provider the JCE provider that supplies the transformation
* @return the XMLCipher
* @throws XMLEncryptionException
*/
public static XMLCipher getProviderInstance(String transformation, String provider)
throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with transformation and provider");
if (null == provider) {
throw new NullPointerException("Provider unexpectedly null..");
}
validateTransformation(transformation);
return new XMLCipher(transformation, provider, null, createSerializer(true));
}
/**
* Returns an <code>XMLCipher</code> that implements the specified
* transformation, operates on the specified context document and serializes
* the document with the specified canonicalization algorithm before it
* encrypts the document.
* <p>
*
* @param transformation the name of the transformation
* @param provider the JCE provider that supplies the transformation
* @param canon the name of the c14n algorithm, if <code>null</code> use standard
* serializer
* @return the XMLCipher
* @throws XMLEncryptionException
*/
public static XMLCipher getProviderInstance(
String transformation, String provider, String canon
) throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with transformation, provider and c14n algorithm");
if (null == provider) {
throw new NullPointerException("Provider unexpectedly null..");
}
validateTransformation(transformation);
return new XMLCipher(transformation, provider, null, createSerializer(canon, true));
}
/**
* Returns an <code>XMLCipher</code> that implements the specified
* transformation, operates on the specified context document and serializes
* the document with the specified canonicalization algorithm before it
* encrypts the document.
* <p>
*
* @param transformation the name of the transformation
* @param provider the JCE provider that supplies the transformation
* @param canon the name of the c14n algorithm, if <code>null</code> use standard
* serializer
* @param digestMethod An optional digestMethod to use
* @return the XMLCipher
* @throws XMLEncryptionException
*/
public static XMLCipher getProviderInstance(
String transformation, String provider, String canon, String digestMethod
) throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with transformation, provider and c14n algorithm");
if (null == provider) {
throw new NullPointerException("Provider unexpectedly null..");
}
validateTransformation(transformation);
return new XMLCipher(transformation, provider, digestMethod, createSerializer(canon, true));
}
/**
* Returns an <code>XMLCipher</code> that implements the specified
* transformation, operates on the specified context document and serializes
* the document with the specified Serializer before it encrypts the document.
* <p>
*
* @param serializer A custom serializer instance to use
* @param transformation the name of the transformation
* @param provider the JCE provider that supplies the transformation
* @param digestMethod An optional digestMethod to use
* @return the XMLCipher
* @throws XMLEncryptionException
*/
public static XMLCipher getProviderInstance(
Serializer serializer, String transformation, String provider, String digestMethod
) throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with transformation, provider and c14n algorithm");
if (null == provider) {
throw new NullPointerException("Provider unexpectedly null..");
}
validateTransformation(transformation);
return new XMLCipher(transformation, provider, digestMethod, serializer);
}
/**
* Returns an <code>XMLCipher</code> that implements no specific
* transformation, and can therefore only be used for decrypt or
* unwrap operations where the encryption method is defined in the
* <code>EncryptionMethod</code> element.
*
* @return The XMLCipher
* @throws XMLEncryptionException
*/
public static XMLCipher getInstance() throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with no arguments");
return new XMLCipher(null, null, null, createSerializer(true));
}
/**
* Returns an <code>XMLCipher</code> that implements no specific
* transformation, and can therefore only be used for decrypt or
* unwrap operations where the encryption method is defined in the
* <code>EncryptionMethod</code> element.
*
* Allows the caller to specify a provider that will be used for
* cryptographic operations.
*
* @param provider the JCE provider that supplies the transformation
* @return the XMLCipher
* @throws XMLEncryptionException
*/
public static XMLCipher getProviderInstance(String provider) throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Getting XMLCipher with provider");
return new XMLCipher(null, provider, null, createSerializer(true));
}
/**
* Initializes this cipher with a key.
* <p>
* The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending on the
* value of opmode.
*
* For WRAP and ENCRYPT modes, this also initialises the internal
* EncryptedKey or EncryptedData (with a CipherValue)
* structure that will be used during the ensuing operations. This
* can be obtained (in order to modify KeyInfo elements etc. prior to
* finalising the encryption) by calling
* {@link #getEncryptedData} or {@link #getEncryptedKey}.
*
* @param opmode the operation mode of this cipher (this is one of the
* following: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE or UNWRAP_MODE)
* @param key
* @see javax.crypto.Cipher#init(int, java.security.Key)
* @throws XMLEncryptionException
*/
public void init(int opmode, Key key) throws XMLEncryptionException {
LOG.log(Level.DEBUG, "Initializing XMLCipher...");
ek = null;
ed = null;
switch (opmode) {
case ENCRYPT_MODE :
LOG.log(Level.DEBUG, "opmode = ENCRYPT_MODE");
ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET");
break;
case DECRYPT_MODE :
LOG.log(Level.DEBUG, "opmode = DECRYPT_MODE");
break;
case WRAP_MODE :
LOG.log(Level.DEBUG, "opmode = WRAP_MODE");
ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET");
break;
case UNWRAP_MODE :
LOG.log(Level.DEBUG, "opmode = UNWRAP_MODE");
break;
default :
LOG.log(Level.ERROR, "Mode unexpectedly invalid");
throw new XMLEncryptionException("Invalid mode in init");
}
cipherMode = opmode;
this.key = key;
}
/**
* Set whether secure validation is enabled or not. The default is false.
*/
public void setSecureValidation(boolean secureValidation) {
this.secureValidation = secureValidation;
}
/**
* This method is used to add a custom {@link KeyResolverSpi} to an XMLCipher.
* These KeyResolvers are used in KeyInfo objects in DECRYPT and
* UNWRAP modes.
*
* @param keyResolver
*/
public void registerInternalKeyResolver(KeyResolverSpi keyResolver) {
if (internalKeyResolvers == null) {
internalKeyResolvers = new ArrayList<>();
}
internalKeyResolvers.add(keyResolver);
}
/**
* Get the EncryptedData being built
* <p>
* Returns the EncryptedData being built during an ENCRYPT operation.
* This can then be used by applications to add KeyInfo elements and
* set other parameters.
*
* @return The EncryptedData being built
*/
public EncryptedData getEncryptedData() {
// Sanity checks
LOG.log(Level.DEBUG, "Returning EncryptedData");
return ed;
}
/**
* Get the EncryptedData being build
*
* Returns the EncryptedData being built during an ENCRYPT operation.
* This can then be used by applications to add KeyInfo elements and
* set other parameters.
*
* @return The EncryptedData being built
*/
public EncryptedKey getEncryptedKey() {
// Sanity checks
LOG.log(Level.DEBUG, "Returning EncryptedKey");
return ek;
}
/**
* Set a Key Encryption Key.
* <p>
* The Key Encryption Key (KEK) is used for encrypting/decrypting
* EncryptedKey elements. By setting this separately, the XMLCipher
* class can know whether a key applies to the data part or wrapped key
* part of an encrypted object.
*
* @param kek The key to use for de/encrypting key data
*/
public void setKEK(Key kek) {
this.kek = kek;
}
/**
* Martial an EncryptedData
*
* Takes an EncryptedData object and returns a DOM Element that
* represents the appropriate <code>EncryptedData</code>
* <p>
* <b>Note:</b> This should only be used in cases where the context
* document has been passed in via a call to doFinal.
*
* @param encryptedData EncryptedData object to martial
* @return the DOM <code>Element</code> representing the passed in
* object
*/
public Element martial(EncryptedData encryptedData) {
return factory.toElement(encryptedData);
}
/**
* Martial an EncryptedData
*
* Takes an EncryptedData object and returns a DOM Element that
* represents the appropriate <code>EncryptedData</code>
*
* @param context The document that will own the returned nodes
* @param encryptedData EncryptedData object to martial
* @return the DOM <code>Element</code> representing the passed in
* object
*/
public Element martial(Document context, EncryptedData encryptedData) {
contextDocument = context;
return factory.toElement(encryptedData);
}
/**
* Martial an EncryptedKey
*
* Takes an EncryptedKey object and returns a DOM Element that
* represents the appropriate <code>EncryptedKey</code>
*
* <p>
* <b>Note:</b> This should only be used in cases where the context
* document has been passed in via a call to doFinal.
*
* @param encryptedKey EncryptedKey object to martial
* @return the DOM <code>Element</code> representing the passed in
* object
*/
public Element martial(EncryptedKey encryptedKey) {
return factory.toElement(encryptedKey);
}
/**
* Martial an EncryptedKey
*
* Takes an EncryptedKey object and returns a DOM Element that
* represents the appropriate <code>EncryptedKey</code>
*
* @param context The document that will own the created nodes
* @param encryptedKey EncryptedKey object to martial
* @return the DOM <code>Element</code> representing the passed in
* object
*/
public Element martial(Document context, EncryptedKey encryptedKey) {
contextDocument = context;
return factory.toElement(encryptedKey);
}
/**
* Martial a ReferenceList
*
* Takes a ReferenceList object and returns a DOM Element that
* represents the appropriate <code>ReferenceList</code>
*
* <p>
* <b>Note:</b> This should only be used in cases where the context
* document has been passed in via a call to doFinal.
*
* @param referenceList ReferenceList object to martial
* @return the DOM <code>Element</code> representing the passed in
* object
*/
public Element martial(ReferenceList referenceList) {
return factory.toElement(referenceList);
}
/**
* Martial a ReferenceList
*
* Takes a ReferenceList object and returns a DOM Element that
* represents the appropriate <code>ReferenceList</code>
*
* @param context The document that will own the created nodes
* @param referenceList ReferenceList object to martial
* @return the DOM <code>Element</code> representing the passed in
* object
*/
public Element martial(Document context, ReferenceList referenceList) {
contextDocument = context;
return factory.toElement(referenceList);
}
/**
* Encrypts an <code>Element</code> and replaces it with its encrypted
* counterpart in the context <code>Document</code>, that is, the
* <code>Document</code> specified when one calls
* {@link #getInstance(String) getInstance}.
*
* @param element the <code>Element</code> to encrypt.
* @return the context <code>Document</code> with the encrypted
* <code>Element</code> having replaced the source <code>Element</code>.
* @throws Exception
*/
private Document encryptElement(Element element) throws Exception{
LOG.log(Level.DEBUG, "Encrypting element...");
if (null == element) {
throw new XMLEncryptionException("empty", "Element unexpectedly null...");
}
if (cipherMode != ENCRYPT_MODE) {
throw new XMLEncryptionException("empty", "XMLCipher unexpectedly not in ENCRYPT_MODE...");
}
if (algorithm == null) {
throw new XMLEncryptionException("empty", "XMLCipher instance without transformation specified");
}
encryptData(contextDocument, element, false);
Element encryptedElement = factory.toElement(ed);
Node sourceParent = element.getParentNode();
sourceParent.replaceChild(encryptedElement, element);
return contextDocument;
}
/**
* Encrypts a <code>NodeList</code> (the contents of an
* <code>Element</code>) and replaces its parent <code>Element</code>'s
* content with this the resulting <code>EncryptedType</code> within the
* context <code>Document</code>, that is, the <code>Document</code>
* specified when one calls
* {@link #getInstance(String) getInstance}.
*
* @param element the <code>NodeList</code> to encrypt.
* @return the context <code>Document</code> with the encrypted
* <code>NodeList</code> having replaced the content of the source
* <code>Element</code>.
* @throws Exception
*/
private Document encryptElementContent(Element element) throws /* XMLEncryption */Exception {
LOG.log(Level.DEBUG, "Encrypting element content...");
if (null == element) {
throw new XMLEncryptionException("empty", "Element unexpectedly null...");
}
if (cipherMode != ENCRYPT_MODE) {
throw new XMLEncryptionException("empty", "XMLCipher unexpectedly not in ENCRYPT_MODE...");
}
if (algorithm == null) {
throw new XMLEncryptionException("empty", "XMLCipher instance without transformation specified");
}
encryptData(contextDocument, element, true);
Element encryptedElement = factory.toElement(ed);
removeContent(element);
element.appendChild(encryptedElement);
return contextDocument;
}
/**
* Process a DOM <code>Document</code> node. The processing depends on the
* initialization parameters of {@link #init(int, Key) init()}.
*
* @param context the context <code>Document</code>.
* @param source the <code>Document</code> to be encrypted or decrypted.
* @return the processed <code>Document</code>.
* @throws Exception to indicate any exceptional conditions.
*/
public Document doFinal(Document context, Document source) throws /* XMLEncryption */Exception {
LOG.log(Level.DEBUG, "Processing source document...");
if (null == source) {
throw new XMLEncryptionException("empty", "Source document unexpectedly null...");
}
return doFinal(context, source.getDocumentElement());
}
/**
* Process a DOM <code>Element</code> node. The processing depends on the
* initialization parameters of {@link #init(int, Key) init()}.
*
* @param context the context <code>Document</code>.
* @param element the <code>Element</code> to be encrypted.
* @return the processed <code>Document</code>.
* @throws Exception to indicate any exceptional conditions.
*/
public Document doFinal(Document context, Element element) throws /* XMLEncryption */Exception {
LOG.log(Level.DEBUG, "Processing source element...");
if (null == context) {
throw new XMLEncryptionException("empty", "Context document unexpectedly null...");
}
if (null == element) {
throw new XMLEncryptionException("empty", "Source element unexpectedly null...");
}
contextDocument = context;
Document result = null;
switch (cipherMode) {
case DECRYPT_MODE:
result = decryptElement(element);
break;
case ENCRYPT_MODE:
result = encryptElement(element);
break;
case UNWRAP_MODE:
case WRAP_MODE:
break;
default:
throw new XMLEncryptionException(new IllegalStateException());
}
return result;
}
/**
* Process the contents of a DOM <code>Element</code> node. The processing
* depends on the initialization parameters of
* {@link #init(int, Key) init()}.
*
* @param context the context <code>Document</code>.
* @param element the <code>Element</code> which contents is to be
* encrypted.
* @param content
* @return the processed <code>Document</code>.
* @throws Exception to indicate any exceptional conditions.
*/
public Document doFinal(Document context, Element element, boolean content)
throws /* XMLEncryption*/ Exception {
LOG.log(Level.DEBUG, "Processing source element...");
if (null == context) {
throw new XMLEncryptionException("empty", "Context document unexpectedly null...");
}
if (null == element) {
throw new XMLEncryptionException("empty", "Source element unexpectedly null...");
}
contextDocument = context;
Document result = null;
switch (cipherMode) {
case DECRYPT_MODE:
if (content) {
result = decryptElementContent(element);
} else {
result = decryptElement(element);
}
break;
case ENCRYPT_MODE:
if (content) {
result = encryptElementContent(element);
} else {