001/*
002 * nimbus-jose-jwt
003 *
004 * Copyright 2012-2021, Connect2id Ltd and contributors.
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
007 * this file except in compliance with the License. You may obtain a copy of the
008 * License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software distributed
013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
015 * specific language governing permissions and limitations under the License.
016 */
017
018package com.nimbusds.jose.crypto.impl;
019
020
021import com.nimbusds.jose.*;
022import com.nimbusds.jose.jwk.Curve;
023import com.nimbusds.jose.util.Base64URL;
024
025import javax.crypto.SecretKey;
026import java.util.Collections;
027import java.util.LinkedHashSet;
028import java.util.Set;
029
030
031/**
032 * The base abstract class for Elliptic Curve Diffie-Hellman One-Pass Unified
033 * Model encrypters and decrypters of {@link com.nimbusds.jose.JWEObject JWE
034 * objects}.
035 *
036 * <p>Supports the following key management algorithms:
037 *
038 * <ul>
039 *     <li>{@link JWEAlgorithm#ECDH_1PU}
040 *     <li>{@link JWEAlgorithm#ECDH_1PU_A128KW}
041 *     <li>{@link JWEAlgorithm#ECDH_1PU_A192KW}
042 *     <li>{@link JWEAlgorithm#ECDH_1PU_A256KW}
043 * </ul>
044 *
045 * <p>Supports the following elliptic curves:
046 *
047 * <ul>
048 *     <li>{@link Curve#P_256}
049 *     <li>{@link Curve#P_384}
050 *     <li>{@link Curve#P_521}
051 *     <li>{@link Curve#X25519}
052 * </ul>
053 *
054 * <p>Supports the following content encryption algorithms for Direct key
055 * agreement mode:
056 *
057 * <ul>
058 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256}
059 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384}
060 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512}
061 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128GCM}
062 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192GCM}
063 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256GCM}
064 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED}
065 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED}
066 *     <li>{@link com.nimbusds.jose.EncryptionMethod#XC20P}
067 * </ul>
068 *
069 * <p>Supports the following content encryption algorithms for Key wrapping
070 * mode:
071 *
072 * <ul>
073 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256}
074 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384}
075 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512}
076 * </ul>
077 *
078 * @author Alexander Martynov
079 * @version 2021-08-03
080 */
081public abstract class ECDH1PUCryptoProvider extends BaseJWEProvider {
082
083
084    /**
085     * The supported JWE algorithms by the ECDH crypto provider class.
086     */
087    public static final Set<JWEAlgorithm> SUPPORTED_ALGORITHMS;
088
089
090    /**
091     * The supported encryption methods by the ECDH crypto provider class.
092     */
093    public static final Set<EncryptionMethod> SUPPORTED_ENCRYPTION_METHODS = ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS;
094
095
096    static {
097        Set<JWEAlgorithm> algs = new LinkedHashSet<>();
098        algs.add(JWEAlgorithm.ECDH_1PU);
099        algs.add(JWEAlgorithm.ECDH_1PU_A128KW);
100        algs.add(JWEAlgorithm.ECDH_1PU_A192KW);
101        algs.add(JWEAlgorithm.ECDH_1PU_A256KW);
102        SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs);
103    }
104
105
106    /**
107     * The elliptic curve.
108     */
109    private final Curve curve;
110
111
112    /**
113     * The Concatenation Key Derivation Function (KDF).
114     */
115    private final ConcatKDF concatKDF;
116
117
118    /**
119     * Creates a new Elliptic Curve Diffie-Hellman One-Pass Unified Model
120     * encryption / decryption provider.
121     *
122     * @param curve The elliptic curve. Must be supported and not
123     *              {@code null}.
124     *
125     * @throws JOSEException If the elliptic curve is not supported.
126     */
127    protected ECDH1PUCryptoProvider(final Curve curve)
128        throws JOSEException {
129
130        super(SUPPORTED_ALGORITHMS, ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS);
131
132        Curve definedCurve = curve != null ? curve : new Curve("unknown");
133
134        if (!supportedEllipticCurves().contains(curve)) {
135            throw new JOSEException(AlgorithmSupportMessage.unsupportedEllipticCurve(
136                definedCurve, supportedEllipticCurves()));
137        }
138
139        this.curve = curve;
140
141        concatKDF = new ConcatKDF("SHA-256");
142    }
143
144
145    /**
146     * Returns the Concatenation Key Derivation Function (KDF).
147     *
148     * @return The concat KDF.
149     */
150    protected ConcatKDF getConcatKDF() {
151
152        return concatKDF;
153    }
154
155
156    /**
157     * Returns the names of the supported elliptic curves. These correspond
158     * to the {@code crv} JWK parameter.
159     *
160     * @return The supported elliptic curves.
161     */
162    public abstract Set<Curve> supportedEllipticCurves();
163
164
165    /**
166     * Returns the elliptic curve of the key (JWK designation).
167     *
168     * @return The elliptic curve.
169     */
170    public Curve getCurve() {
171
172        return curve;
173    }
174
175    
176    /**
177     * Encrypts the specified plaintext using the specified shared secret
178     * ("Z"), with an optionally externally supplied content encryption key
179     * (CEK) for {@link ECDH.AlgorithmMode#KW}.
180     */
181    protected JWECryptoParts encryptWithZ(final JWEHeader header,
182                                          final SecretKey Z,
183                                          final byte[] clearText,
184                                          final SecretKey contentEncryptionKey)
185        throws JOSEException {
186
187        final JWEAlgorithm alg = header.getAlgorithm();
188        final ECDH.AlgorithmMode algMode = ECDH1PU.resolveAlgorithmMode(alg);
189        final EncryptionMethod enc = header.getEncryptionMethod();
190
191        final SecretKey cek;
192        final Base64URL encryptedKey; // The CEK encrypted (second JWE part)
193
194        if (algMode.equals(ECDH.AlgorithmMode.DIRECT)) {
195
196            // Derive shared key via concat KDF
197            getConcatKDF().getJCAContext().setProvider(getJCAContext().getMACProvider()); // update before concat
198            cek = ECDH1PU.deriveSharedKey(header, Z, getConcatKDF());
199
200            return ContentCryptoProvider.encrypt(header, clearText, cek, null, getJCAContext());
201        }
202
203        if (algMode.equals(ECDH.AlgorithmMode.KW)) {
204
205            // Key wrapping mode supports only AES_CBC_HMAC_SHA2
206            // See https://datatracker.ietf.org/doc/html/draft-madden-jose-ecdh-1pu-04#section-2.1
207            if (!EncryptionMethod.Family.AES_CBC_HMAC_SHA.contains(enc)) {
208                throw new JOSEException(AlgorithmSupportMessage.unsupportedEncryptionMethod(
209                        header.getEncryptionMethod(),
210                        EncryptionMethod.Family.AES_CBC_HMAC_SHA));
211            }
212
213            if (contentEncryptionKey != null) { // Use externally supplied CEK
214                cek = contentEncryptionKey;
215            } else { // Generate the CEK according to the enc method
216                cek = ContentCryptoProvider.generateCEK(enc, getJCAContext().getSecureRandom());
217            }
218
219            JWECryptoParts encrypted = ContentCryptoProvider.encrypt(header, clearText, cek, null, getJCAContext());
220
221            SecretKey sharedKey = ECDH1PU.deriveSharedKey(header, Z, encrypted.getAuthenticationTag(), getConcatKDF());
222            encryptedKey = Base64URL.encode(AESKW.wrapCEK(cek, sharedKey, getJCAContext().getKeyEncryptionProvider()));
223
224            return new JWECryptoParts(
225                    header,
226                    encryptedKey,
227                    encrypted.getInitializationVector(),
228                    encrypted.getCipherText(),
229                    encrypted.getAuthenticationTag()
230            );
231        }
232
233        throw new JOSEException("Unexpected JWE ECDH algorithm mode: " + algMode);
234    }
235
236    /**
237     * Decrypts the encrypted JWE parts using the specified shared secret ("Z").
238     */
239    protected byte[] decryptWithZ(final JWEHeader header,
240                                  final SecretKey Z,
241                                  final Base64URL encryptedKey,
242                                  final Base64URL iv,
243                                  final Base64URL cipherText,
244                                  final Base64URL authTag)
245        throws JOSEException {
246
247        final JWEAlgorithm alg = header.getAlgorithm();
248        final ECDH.AlgorithmMode algMode = ECDH1PU.resolveAlgorithmMode(alg);
249
250        // Derive shared key via concat KDF
251        getConcatKDF().getJCAContext().setProvider(getJCAContext().getMACProvider()); // update before concat
252
253        JWEHeader updatedHeader = new JWEHeader.Builder(header).
254                iv(iv).
255                authTag(authTag).
256                build();
257
258        final SecretKey cek;
259
260        if (algMode.equals(ECDH.AlgorithmMode.DIRECT)) {
261            cek = ECDH1PU.deriveSharedKey(updatedHeader, Z, getConcatKDF());
262        } else if (algMode.equals(ECDH.AlgorithmMode.KW)) {
263            if (encryptedKey == null) {
264                throw new JOSEException("Missing JWE encrypted key");
265            }
266
267            SecretKey sharedKey = ECDH1PU.deriveSharedKey(updatedHeader, Z, authTag, getConcatKDF());
268            cek = AESKW.unwrapCEK(sharedKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider());
269        } else {
270            throw new JOSEException("Unexpected JWE ECDH algorithm mode: " + algMode);
271        }
272
273        return ContentCryptoProvider.decrypt(header, null, iv, cipherText, authTag, cek, getJCAContext());
274    }
275
276}