001/*
002 * nimbus-jose-jwt
003 *
004 * Copyright 2012-2016, Connect2id Ltd.
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 java.security.*;
022import java.security.interfaces.ECPrivateKey;
023import java.security.interfaces.ECPublicKey;
024import java.security.spec.ECParameterSpec;
025import java.util.Collections;
026import java.util.LinkedHashSet;
027import java.util.Set;
028import javax.crypto.SecretKey;
029
030import com.nimbusds.jose.*;
031import com.nimbusds.jose.crypto.impl.ECDH;
032import com.nimbusds.jose.crypto.impl.ECDHCryptoProvider;
033import com.nimbusds.jose.jwk.Curve;
034import com.nimbusds.jose.jwk.ECKey;
035import net.jcip.annotations.ThreadSafe;
036
037
038/**
039 * Elliptic Curve Diffie-Hellman encrypter of
040 * {@link com.nimbusds.jose.JWEObject JWE objects} for curves using EC JWK keys.
041 * Expects a public EC key (with a P-256, P-384 or P-521 curve).
042 *
043 * <p>See RFC 7518
044 * <a href="https://tools.ietf.org/html/rfc7518#section-4.6">section 4.6</a>
045 * for more information.
046 *
047 * <p>For Curve25519/X25519, see {@link X25519Encrypter} instead.
048 *
049 * <p>This class is thread-safe.
050 *
051 * <p>Supports the following key management algorithms:
052 *
053 * <ul>
054 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES}
055 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A128KW}
056 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A192KW}
057 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A256KW}
058 * </ul>
059 *
060 * <p>Supports the following elliptic curves:
061 *
062 * <ul>
063 *     <li>{@link com.nimbusds.jose.jwk.Curve#P_256}
064 *     <li>{@link com.nimbusds.jose.jwk.Curve#P_384}
065 *     <li>{@link com.nimbusds.jose.jwk.Curve#P_521}
066 * </ul>
067 *
068 * <p>Supports the following content encryption algorithms:
069 *
070 * <ul>
071 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256}
072 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384}
073 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512}
074 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128GCM}
075 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192GCM}
076 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256GCM}
077 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED}
078 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED}
079 * </ul>
080 *
081 * @author Tim McLean
082 * @author Vladimir Dzhuvinov
083 * @version 2018-07-12
084 */
085@ThreadSafe
086public class ECDHEncrypter extends ECDHCryptoProvider implements JWEEncrypter {
087
088
089        /**
090         * The supported EC JWK curves by the ECDH crypto provider class.
091         */
092        public static final Set<Curve> SUPPORTED_ELLIPTIC_CURVES;
093
094
095        static {
096                Set<Curve> curves = new LinkedHashSet<>();
097                curves.add(Curve.P_256);
098                curves.add(Curve.P_384);
099                curves.add(Curve.P_521);
100                SUPPORTED_ELLIPTIC_CURVES = Collections.unmodifiableSet(curves);
101        }
102
103
104        /**
105         * The public EC key.
106         */
107        private final ECPublicKey publicKey;
108
109
110        /**
111         * Creates a new Elliptic Curve Diffie-Hellman encrypter.
112         *
113         * @param publicKey The public EC key. Must not be {@code null}.
114         *
115         * @throws JOSEException If the elliptic curve is not supported.
116         */
117        public ECDHEncrypter(final ECPublicKey publicKey)
118                throws JOSEException {
119
120                super(Curve.forECParameterSpec(publicKey.getParams()));
121
122                this.publicKey = publicKey;
123        }
124
125
126        /**
127         * Creates a new Elliptic Curve Diffie-Hellman encrypter.
128         *
129         * @param ecJWK The EC JSON Web Key (JWK). Must not be {@code null}.
130         *
131         * @throws JOSEException If the elliptic curve is not supported.
132         */
133        public ECDHEncrypter(final ECKey ecJWK)
134                throws JOSEException {
135
136                super(ecJWK.getCurve());
137
138                publicKey = ecJWK.toECPublicKey();
139        }
140
141
142        /**
143         * Returns the public EC key.
144         *
145         * @return The public EC key.
146         */
147        public ECPublicKey getPublicKey() {
148
149                return publicKey;
150        }
151
152
153        @Override
154        public Set<Curve> supportedEllipticCurves() {
155
156                return SUPPORTED_ELLIPTIC_CURVES;
157        }
158
159
160        @Override
161        public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText)
162                throws JOSEException {
163
164                // Generate ephemeral EC key pair on the same curve as the consumer's public key
165                KeyPair ephemeralKeyPair = generateEphemeralKeyPair(publicKey.getParams());
166                ECPublicKey ephemeralPublicKey = (ECPublicKey)ephemeralKeyPair.getPublic();
167                ECPrivateKey ephemeralPrivateKey = (ECPrivateKey)ephemeralKeyPair.getPrivate();
168
169                // Add the ephemeral public EC key to the header
170                JWEHeader updatedHeader = new JWEHeader.Builder(header).
171                        ephemeralPublicKey(new ECKey.Builder(getCurve(), ephemeralPublicKey).build()).
172                        build();
173
174                // Derive 'Z'
175                SecretKey Z = ECDH.deriveSharedSecret(
176                        publicKey,
177                        ephemeralPrivateKey,
178                        getJCAContext().getKeyEncryptionProvider());
179
180                return encryptWithZ(updatedHeader, Z, clearText);
181        }
182
183
184        /**
185         * Generates a new ephemeral EC key pair with the specified curve.
186         *
187         * @param ecParameterSpec The EC key spec. Must not be {@code null}.
188         *
189         * @return The EC key pair.
190         *
191         * @throws JOSEException If the EC key pair couldn't be generated.
192         */
193        private KeyPair generateEphemeralKeyPair(final ECParameterSpec ecParameterSpec)
194                throws JOSEException {
195
196                Provider keProvider = getJCAContext().getKeyEncryptionProvider();
197
198                try {
199                        KeyPairGenerator generator;
200
201                        if (keProvider != null) {
202                                generator = KeyPairGenerator.getInstance("EC", keProvider);
203                        } else {
204                                generator = KeyPairGenerator.getInstance("EC");
205                        }
206
207                        generator.initialize(ecParameterSpec);
208                        return generator.generateKeyPair();
209                } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
210                        throw new JOSEException("Couldn't generate ephemeral EC key pair: " + e.getMessage(), e);
211                }
212        }
213}