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