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;
019
020
021import com.nimbusds.jose.*;
022import com.nimbusds.jose.crypto.impl.*;
023import com.nimbusds.jose.jwk.Curve;
024import com.nimbusds.jose.jwk.OctetKeyPair;
025import com.nimbusds.jose.util.Base64URL;
026import com.nimbusds.jose.util.Pair;
027import net.jcip.annotations.ThreadSafe;
028
029import javax.crypto.SecretKey;
030import java.util.*;
031
032
033/**
034 * Elliptic Curve Diffie-Hellman Multi-recipient decrypter of
035 * {@link JWEObjectJSON JWE objects} for curves using EC JWK
036 * keys. Expects a private EC key (with a P-256, P-384 or P-521 curve).
037 *
038 * <p>Public Key Authenticated Encryption for JOSE
039 * <a href="https://datatracker.ietf.org/doc/html/draft-madden-jose-ecdh-1pu-04">ECDH-1PU</a>
040 * for more information.
041 *
042 * <p>This class is thread-safe.
043 *
044 * <p>Supports the following key management algorithms:
045 *
046 * <ul>
047 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES}
048 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A128KW}
049 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A192KW}
050 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A256KW}
051 * </ul>
052 *
053 * <p>Supports the following elliptic curve:
054 *
055 * <ul>
056 *     <li>{@link com.nimbusds.jose.jwk.Curve#X25519} (Curve25519)
057 * </ul>
058 *
059 * <p>Supports the following content encryption algorithms:
060 *
061 * <ul>
062 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256}
063 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384}
064 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512}
065 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128GCM}
066 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192GCM}
067 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256GCM}
068 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED}
069 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED}
070 *     <li>{@link com.nimbusds.jose.EncryptionMethod#XC20P}
071 * </ul>
072 *
073 * @author Alexander Martynov
074 * @version 2021-08-18
075 */
076@ThreadSafe
077public class X25519DecrypterMulti extends ECDHCryptoProvider implements JWEDecrypterMulti, CriticalHeaderParamsAware {
078
079
080    /**
081     * The supported EC JWK curves by the ECDH crypto provider class.
082     */
083    public static final Set<Curve> SUPPORTED_ELLIPTIC_CURVES;
084
085
086    static {
087        Set<Curve> curves = new LinkedHashSet<>();
088        curves.add(Curve.X25519);
089        SUPPORTED_ELLIPTIC_CURVES = Collections.unmodifiableSet(curves);
090    }
091
092    /**
093     * The critical header policy.
094     */
095    private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral();
096
097    /**
098     * The list of private recipient's keys.
099     */
100    private final List<Pair<UnprotectedHeader, OctetKeyPair>>recipients;
101
102    /**
103     * Creates a curve x25519 Elliptic Curve Diffie-Hellman Multi-recipient decrypter.
104     *
105     * @param recipients     The list of private recipient's keys.
106     *
107     * @throws JOSEException If the key subtype is not supported.
108     */
109    public X25519DecrypterMulti(final List<Pair<UnprotectedHeader, OctetKeyPair>>recipients)
110            throws JOSEException {
111
112        this(recipients, null);
113    }
114
115    /**
116     * Creates a curve x25519 Elliptic Curve Diffie-Hellman Multi-recipient decrypter.
117     *
118     * @param recipients     The list of private recipient's keys.
119     * @param defCritHeaders The names of the critical header parameters
120     *                       that are deferred to the application for
121     *                       processing, empty set or {@code null} if none.
122     *
123     * @throws JOSEException If the key subtype is not supported.
124     */
125    public X25519DecrypterMulti(final List<Pair<UnprotectedHeader, OctetKeyPair>> recipients, final Set<String> defCritHeaders)
126        throws JOSEException {
127
128        super(recipients.get(0).getRight().getCurve());
129
130        this.recipients = recipients;
131        critPolicy.setDeferredCriticalHeaderParams(defCritHeaders);
132    }
133
134    @Override
135    public Set<Curve> supportedEllipticCurves() {
136
137        return SUPPORTED_ELLIPTIC_CURVES;
138    }
139
140
141    @Override
142    public Set<String> getProcessedCriticalHeaderParams() {
143
144        return critPolicy.getProcessedCriticalHeaderParams();
145    }
146
147
148    @Override
149    public Set<String> getDeferredCriticalHeaderParams() {
150
151        return critPolicy.getProcessedCriticalHeaderParams();
152    }
153
154
155    @Override
156    public byte[] decrypt(final JWEHeader header,
157                          final List<JWERecipient> recipients,
158                          final Base64URL iv,
159                          final Base64URL cipherText,
160                          final Base64URL authTag)
161            throws JOSEException {
162
163        critPolicy.ensureHeaderPasses(header);
164
165        // Get ephemeral key from header
166        OctetKeyPair ephemeralPublicKey = (OctetKeyPair) header.getEphemeralPublicKey();
167
168        if (ephemeralPublicKey == null) {
169            throw new JOSEException("Missing ephemeral public key epk JWE header parameter");
170        }
171
172        List<Pair<UnprotectedHeader, SecretKey>> sharedKeys = new ArrayList<>();
173
174        for (Pair<UnprotectedHeader, OctetKeyPair> recipient : this.recipients) {
175            if (!recipient.getRight().getCurve().equals(ephemeralPublicKey.getCurve())) {
176                throw new JOSEException("Curve of ephemeral public key does not match curve of private key");
177            }
178
179            SecretKey Z = ECDH.deriveSharedSecret(
180                    ephemeralPublicKey,
181                    recipient.getRight()
182            );
183
184            sharedKeys.add(Pair.of(recipient.getLeft(), Z));
185        }
186
187        return decryptMulti(header, sharedKeys, recipients, iv, cipherText, authTag);
188    }
189}