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