-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathXMLCipherUtil.java
More file actions
375 lines (346 loc) · 19 KB
/
Copy pathXMLCipherUtil.java
File metadata and controls
375 lines (346 loc) · 19 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
/**
* 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 org.apache.xml.security.algorithms.JCEMapper;
import org.apache.xml.security.encryption.keys.content.derivedKey.ConcatKDFParamsImpl;
import org.apache.xml.security.encryption.keys.content.derivedKey.HKDFParamsImpl;
import org.apache.xml.security.encryption.keys.content.derivedKey.KDFParams;
import org.apache.xml.security.encryption.keys.content.derivedKey.KeyDerivationMethodImpl;
import org.apache.xml.security.encryption.params.ConcatKDFParams;
import org.apache.xml.security.encryption.params.HKDFParams;
import org.apache.xml.security.encryption.params.KeyAgreementParameters;
import org.apache.xml.security.encryption.params.KeyDerivationParameters;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.utils.Constants;
import org.apache.xml.security.utils.EncryptionConstants;
import org.apache.xml.security.utils.KeyUtils;
import org.w3c.dom.Document;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.util.Base64;
public final class XMLCipherUtil {
private static final Logger LOG = System.getLogger(XMLCipherUtil.class.getName());
private static final boolean gcmUseIvParameterSpec =
AccessController.doPrivileged((PrivilegedAction<Boolean>)
() -> Boolean.getBoolean("org.apache.xml.security.cipher.gcm.useIvParameterSpec"));
/**
* Build an <code>AlgorithmParameterSpec</code> instance used to initialize a <code>Cipher</code> instance
* for block cipher encryption and decryption.
*
* @param algorithm the XML encryption algorithm URI
* @param iv the initialization vector
* @return the newly constructed AlgorithmParameterSpec instance, appropriate for the
* specified algorithm
*/
public static AlgorithmParameterSpec constructBlockCipherParameters(String algorithm, byte[] iv) {
if (EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM.equals(algorithm)
|| EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM.equals(algorithm)
|| EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM.equals(algorithm)) {
return constructBlockCipherParametersForGCMAlgorithm(algorithm, iv);
} else {
LOG.log(Level.DEBUG, "Saw non-AES-GCM mode block cipher, returning IvParameterSpec: {0}", algorithm);
return new IvParameterSpec(iv);
}
}
public static AlgorithmParameterSpec constructBlockCipherParameters(boolean gcmAlgorithm, byte[] iv) {
if (gcmAlgorithm) {
return constructBlockCipherParametersForGCMAlgorithm("AES/GCM/NoPadding", iv);
} else {
LOG.log(Level.DEBUG, "Saw non-AES-GCM mode block cipher, returning IvParameterSpec");
return new IvParameterSpec(iv);
}
}
private static AlgorithmParameterSpec constructBlockCipherParametersForGCMAlgorithm(String algorithm, byte[] iv) {
if (gcmUseIvParameterSpec) {
// This override allows to support Java 1.7+ with (usually older versions of) third-party security
// providers which support or even require GCM via IvParameterSpec rather than GCMParameterSpec,
// e.g. BouncyCastle <= 1.49 (really <= 1.50 due to a semi-related bug).
LOG.log(Level.DEBUG, "Saw AES-GCM block cipher, using IvParameterSpec due to system property override: {0}", algorithm);
return new IvParameterSpec(iv);
}
LOG.log(Level.DEBUG, "Saw AES-GCM block cipher, attempting to create GCMParameterSpec: {0}", algorithm);
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, iv);
LOG.log(Level.DEBUG, "Successfully created GCMParameterSpec");
return gcmSpec;
}
/**
* Method buildOAEPParameters from given parameters and returns OAEPParameterSpec. If encryptionAlgorithmURI is
* not RSA_OAEP or RSA_OAEP_11, null is returned.
*
* @param encryptionAlgorithmURI the encryption algorithm URI (RSA_OAEP or RSA_OAEP_11)
* @param digestAlgorithmURI the digest algorithm URI
* @param mgfAlgorithmURI the MGF algorithm URI if encryptionAlgorithmURI is RSA_OAEP_11, otherwise parameter is ignored
* @param oaepParams the OAEP parameters bytes
* @return OAEPParameterSpec or null if encryptionAlgorithmURI is not RSA_OAEP or RSA_OAEP_11
*/
public static OAEPParameterSpec constructOAEPParameters(
String encryptionAlgorithmURI,
String digestAlgorithmURI,
String mgfAlgorithmURI,
byte[] oaepParams
) {
if (XMLCipher.RSA_OAEP.equals(encryptionAlgorithmURI)
|| XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithmURI)) {
String jceDigestAlgorithm = "SHA-1";
if (digestAlgorithmURI != null) {
jceDigestAlgorithm = JCEMapper.translateURItoJCEID(digestAlgorithmURI);
}
PSource.PSpecified pSource = oaepParams == null ?
PSource.PSpecified.DEFAULT : new PSource.PSpecified(oaepParams);
MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
if (XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithmURI)) {
mgfParameterSpec = constructMGF1Parameter(mgfAlgorithmURI);
}
return new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource);
}
return null;
}
/**
* Create MGF1ParameterSpec for the given algorithm URI
*
* @param mgh1AlgorithmURI the algorithm URI. If null or empty, SHA-1 is used as default MGF1 digest algorithm.
* @return the MGF1ParameterSpec for the given algorithm URI
*/
public static MGF1ParameterSpec constructMGF1Parameter(String mgh1AlgorithmURI) {
LOG.log(Level.DEBUG, "Creating MGF1ParameterSpec for [{0}]", mgh1AlgorithmURI);
if (mgh1AlgorithmURI == null || mgh1AlgorithmURI.isEmpty()) {
LOG.log(Level.WARNING, "MGF1 algorithm URI is null or empty. Using SHA-1 as default.");
return new MGF1ParameterSpec("SHA-1");
}
switch (mgh1AlgorithmURI) {
case EncryptionConstants.MGF1_SHA1:
return new MGF1ParameterSpec("SHA-1");
case EncryptionConstants.MGF1_SHA224:
return new MGF1ParameterSpec("SHA-224");
case EncryptionConstants.MGF1_SHA256:
return new MGF1ParameterSpec("SHA-256");
case EncryptionConstants.MGF1_SHA384:
return new MGF1ParameterSpec("SHA-384");
case EncryptionConstants.MGF1_SHA512:
return new MGF1ParameterSpec("SHA-512");
default:
LOG.log(Level.WARNING, "Unsupported MGF algorithm: [{0}] Using SHA-1 as default.", mgh1AlgorithmURI);
return new MGF1ParameterSpec("SHA-1");
}
}
/**
* Get the MGF1 algorithm URI for the given MGF1ParameterSpec
*
* @param parameterSpec the MGF1ParameterSpec
* @return the MGF1 algorithm URI for the given MGF1ParameterSpec
*/
public static String getMgf1URIForParameter(MGF1ParameterSpec parameterSpec) {
String digestAlgorithm = parameterSpec.getDigestAlgorithm();
LOG.log(Level.DEBUG, "Get MGF1 URI for digest algorithm [{0}]", digestAlgorithm);
switch (digestAlgorithm) {
case "SHA-1":
return EncryptionConstants.MGF1_SHA1;
case "SHA-224":
return EncryptionConstants.MGF1_SHA224;
case "SHA-256":
return EncryptionConstants.MGF1_SHA256;
case "SHA-384":
return EncryptionConstants.MGF1_SHA384;
case "SHA-512":
return EncryptionConstants.MGF1_SHA512;
default:
LOG.log(Level.WARNING, "Unknown hash algorithm: [{0}] for MGF1", digestAlgorithm);
return EncryptionConstants.MGF1_SHA1;
}
}
/**
* Construct an KeyAgreementParameterSpec object from the given parameters
*
* @param keyWrapAlgoURI key wrap algorithm
* @param agreementMethod agreement method
* @param keyAgreementPrivateKey private key to derive the shared secret in case of Diffie-Hellman key agreements
*/
public static KeyAgreementParameters constructRecipientKeyAgreementParameters(String keyWrapAlgoURI,
AgreementMethod agreementMethod,
PrivateKey keyAgreementPrivateKey
) throws XMLSecurityException {
String agreementAlgorithmURI = agreementMethod.getAlgorithm();
int keyLength = KeyUtils.getAESKeyBitSizeForWrapAlgorithm(keyWrapAlgoURI);
KeyDerivationMethod keyDerivationMethod = agreementMethod.getKeyDerivationMethod();
if (keyDerivationMethod == null) {
throw new XMLEncryptionException("Key Derivation Algorithm is not specified");
}
KeyDerivationParameters kdp = constructKeyDerivationParameter(keyDerivationMethod, keyLength);
return constructAgreementParameters(
agreementAlgorithmURI, KeyAgreementParameters.ActorType.RECIPIENT, kdp,
keyAgreementPrivateKey, agreementMethod.getOriginatorKeyInfo().getPublicKey());
}
/**
* Construct an KeyAgreementParameterSpec object from the given parameters
*
* @param agreementAlgorithmURI agreement algorithm URI
* @param actorType the actor type (originator or recipient)
* @param keyDerivationParameter key derivation parameters (e.g. ConcatKDFParams for ConcatKDF key derivation)
* @param keyAgreementPrivateKey private key to derive the shared secret in case of Diffie-Hellman key agreements
* @param keyAgreementPublicKey public key to derive the shared secret in case of Diffie-Hellman key agreements
*/
public static KeyAgreementParameters constructAgreementParameters(String agreementAlgorithmURI,
KeyAgreementParameters.ActorType actorType,
KeyDerivationParameters keyDerivationParameter,
PrivateKey keyAgreementPrivateKey,
PublicKey keyAgreementPublicKey) {
KeyAgreementParameters ecdhKeyAgreementParameters = new KeyAgreementParameters(
actorType,
agreementAlgorithmURI, keyDerivationParameter);
if (actorType == KeyAgreementParameters.ActorType.RECIPIENT) {
ecdhKeyAgreementParameters.setRecipientPrivateKey(keyAgreementPrivateKey);
ecdhKeyAgreementParameters.setOriginatorPublicKey(keyAgreementPublicKey);
} else {
ecdhKeyAgreementParameters.setOriginatorPrivateKey(keyAgreementPrivateKey);
ecdhKeyAgreementParameters.setRecipientPublicKey(keyAgreementPublicKey);
}
return ecdhKeyAgreementParameters;
}
/**
* Construct a KeyDerivationParameter object from the given keyDerivationMethod data
* and keyBitLength.
*
* @param keyDerivationMethod element with the key derivation method data
* @param keyBitLength expected derived key length in bits
* @return KeyDerivationParameters data
* @throws XMLEncryptionException if KDFParams cannot be created or the
* KDF URI is not supported or the key derivation parameters are invalid
*/
public static KeyDerivationParameters constructKeyDerivationParameter(KeyDerivationMethod keyDerivationMethod,
int keyBitLength) throws XMLEncryptionException {
String keyDerivationAlgorithm = keyDerivationMethod.getAlgorithm();
KDFParams kdfParams;
try {
kdfParams = keyDerivationMethod.getKDFParams();
} catch (XMLSecurityException e) {
throw new XMLEncryptionException(e);
}
if (EncryptionConstants.ALGO_ID_KEYDERIVATION_CONCATKDF.equals(keyDerivationAlgorithm)) {
if (!(kdfParams instanceof ConcatKDFParamsImpl)) {
throw new XMLEncryptionException("KeyDerivation.InvalidParametersType", keyDerivationAlgorithm, ConcatKDFParamsImpl.class.getName());
}
ConcatKDFParamsImpl concatKDFParams = (ConcatKDFParamsImpl) kdfParams;
return ConcatKDFParams.createBuilder(keyBitLength, concatKDFParams.getDigestMethod())
.algorithmID(concatKDFParams.getAlgorithmId())
.partyUInfo(concatKDFParams.getPartyUInfo())
.partyVInfo(concatKDFParams.getPartyVInfo())
.suppPubInfo(concatKDFParams.getSuppPubInfo())
.suppPrivInfo(concatKDFParams.getSuppPrivInfo())
.build();
} else if (EncryptionConstants.ALGO_ID_KEYDERIVATION_HKDF.equals(keyDerivationAlgorithm)) {
if (!(kdfParams instanceof HKDFParamsImpl)) {
throw new XMLEncryptionException("KeyDerivation.InvalidParametersType", keyDerivationAlgorithm, HKDFParamsImpl.class.getName());
}
HKDFParamsImpl hKDFParams = (HKDFParamsImpl) kdfParams;
return HKDFParams.createBuilder(keyBitLength, hKDFParams.getPRFAlgorithm())
.salt(decodeBase64Parameter(hKDFParams.getSalt(), Constants._TAG_SALT))
.info(decodeBase64Parameter(hKDFParams.getInfo(), EncryptionConstants._TAG_INFO))
.build();
}
throw new XMLEncryptionException("unknownAlgorithm", keyDerivationAlgorithm);
}
/**
* Base64-decodes an optional key derivation parameter read from the message. Malformed
* base64 is reported as an {@link XMLEncryptionException} rather than escaping as the
* {@link IllegalArgumentException} thrown by {@link Base64.Decoder#decode(String)}.
*/
private static byte[] decodeBase64Parameter(String value, String parameterName) throws XMLEncryptionException {
if (value == null) {
return null;
}
try {
return Base64.getDecoder().decode(value);
} catch (IllegalArgumentException e) {
throw new XMLEncryptionException(e, "KeyDerivation.InvalidParameter", new Object[]{parameterName});
}
}
/**
* Construct a {@code KeyDerivationMethod} DOM element from the given {@link KeyDerivationParameters}.
* The inverse of {@link #constructKeyDerivationParameter(KeyDerivationMethod, int)}. Supports the same
* two key derivation functions as the ECDH-ES/X25519/X448 key-agreement path: ConcatKDF and HKDF.
*
* @param doc the {@link Document} in which the {@code KeyDerivationMethod} element will be created
* @param keyDerivationParameter the key derivation parameters (e.g. {@link HKDFParams} or {@link ConcatKDFParams})
* @return the constructed {@code KeyDerivationMethod}
* @throws XMLEncryptionException if the key derivation algorithm is not supported
*/
public static KeyDerivationMethod constructKeyDerivationMethod(Document doc, KeyDerivationParameters keyDerivationParameter)
throws XMLEncryptionException {
KeyDerivationMethodImpl keyDerivationMethod = new KeyDerivationMethodImpl(doc);
keyDerivationMethod.setAlgorithm(keyDerivationParameter.getAlgorithm());
KDFParams kdfParams;
if (keyDerivationParameter instanceof ConcatKDFParams) {
ConcatKDFParams kdfParameters = (ConcatKDFParams) keyDerivationParameter;
ConcatKDFParamsImpl concatKDFParams = new ConcatKDFParamsImpl(doc);
concatKDFParams.setDigestMethod(kdfParameters.getDigestAlgorithm());
concatKDFParams.setAlgorithmId(kdfParameters.getAlgorithmID());
concatKDFParams.setPartyUInfo(kdfParameters.getPartyUInfo());
concatKDFParams.setPartyVInfo(kdfParameters.getPartyVInfo());
concatKDFParams.setSuppPubInfo(kdfParameters.getSuppPubInfo());
concatKDFParams.setSuppPrivInfo(kdfParameters.getSuppPrivInfo());
kdfParams = concatKDFParams;
} else if (keyDerivationParameter instanceof HKDFParams) {
HKDFParams kdfParameters = (HKDFParams) keyDerivationParameter;
HKDFParamsImpl hkdfParams = new HKDFParamsImpl(doc);
hkdfParams.setPRFAlgorithm(kdfParameters.getHmacHashAlgorithm());
Base64.Encoder base64Encoder = Base64.getEncoder();
if (kdfParameters.getSalt() != null) {
hkdfParams.setSalt(base64Encoder.encodeToString(kdfParameters.getSalt()));
}
if (kdfParameters.getInfo() != null) {
hkdfParams.setInfo(base64Encoder.encodeToString(kdfParameters.getInfo()));
}
hkdfParams.setKeyLength(kdfParameters.getKeyBitLength() / 8);
kdfParams = hkdfParams;
} else {
throw new XMLEncryptionException("KeyDerivation.UnsupportedAlgorithm",
keyDerivationParameter.getAlgorithm(), keyDerivationParameter.getClass().getName());
}
keyDerivationMethod.setKDFParams(kdfParams);
return keyDerivationMethod;
}
/**
* Method hexStringToByteArray converts hex string to byte array.
*
* @param hexString the hex string to convert
* @return the byte array of the input param, empty array if the hex string is empty, or null if input param is null
*/
public static byte[] hexStringToByteArray(String hexString) {
if (hexString == null){
return null;
}
if (hexString.isEmpty()) {
return new byte[0];
}
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i+1), 16));
}
return data;
}
}