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.PrivateKey;
022import java.util.Set;
023import javax.crypto.SecretKey;
024
025import com.nimbusds.jose.*;
026import com.nimbusds.jose.jwk.RSAKey;
027import com.nimbusds.jose.util.Base64URL;
028import net.jcip.annotations.ThreadSafe;
029
030
031/**
032 * RSA decrypter of {@link com.nimbusds.jose.JWEObject JWE objects}. Expects a
033 * private RSA key.
034 *
035 * <p>Decrypts the encrypted Content Encryption Key (CEK) with the private RSA
036 * key, and then uses the CEK along with the IV and authentication tag to
037 * decrypt the cipher text. See RFC 7518, sections
038 * <a href="https://tools.ietf.org/html/rfc7518#section-4.2">4.2</a> and
039 * <a href="https://tools.ietf.org/html/rfc7518#section-4.3">4.3</a> for more
040 * 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#RSA1_5}
048 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#RSA_OAEP}
049 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#RSA_OAEP_256}
050 * </ul>
051 *
052 * <p>Supports the following content encryption algorithms:
053 *
054 * <ul>
055 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256}
056 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384}
057 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512}
058 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128GCM}
059 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192GCM}
060 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256GCM}
061 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED}
062 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED}
063 * </ul>
064 * 
065 * @author David Ortiz
066 * @author Vladimir Dzhuvinov
067 * @author Dimitar A. Stoikov
068 * @version 2016-06-29
069 */
070@ThreadSafe
071public class RSADecrypter extends RSACryptoProvider implements JWEDecrypter, CriticalHeaderParamsAware {
072
073
074        /**
075         * The critical header policy.
076         */
077        private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral();
078
079
080        /**
081         * The private RSA key.
082         */
083        private final PrivateKey privateKey;
084
085
086        /**
087         * Creates a new RSA decrypter.
088         *
089         * @param privateKey The private RSA key. Must not be {@code null}.
090         */
091        public RSADecrypter(final PrivateKey privateKey) {
092
093                this(privateKey, null);
094        }
095
096
097        /**
098         * Creates a new RSA decrypter.
099         *
100         * @param rsaJWK The RSA JSON Web Key (JWK). Must contain a private
101         *               part. Must not be {@code null}.
102         *
103         * @throws JOSEException If the RSA JWK doesn't contain a private part
104         *                       or its extraction failed.
105         */
106        public RSADecrypter(final RSAKey rsaJWK)
107                throws JOSEException {
108
109                if (! rsaJWK.isPrivate()) {
110                        throw new JOSEException("The RSA JWK doesn't contain a private part");
111                }
112
113                privateKey = rsaJWK.toRSAPrivateKey();
114        }
115
116
117        /**
118         * Creates a new RSA decrypter.
119         *
120         * @param privateKey     The private RSA key. Its algorithm must be
121         *                       "RSA". Must not be {@code null}.
122         * @param defCritHeaders The names of the critical header parameters
123         *                       that are deferred to the application for
124         *                       processing, empty set or {@code null} if none.
125         */
126        public RSADecrypter(final PrivateKey privateKey,
127                            final Set<String> defCritHeaders) {
128
129                if (privateKey == null) {
130                        throw new IllegalArgumentException("The private RSA key must not be null");
131                }
132
133                if (! privateKey.getAlgorithm().equalsIgnoreCase("RSA")) {
134                        throw new IllegalArgumentException("The private key algorithm must be RSA");
135                }
136
137                this.privateKey = privateKey;
138
139                critPolicy.setDeferredCriticalHeaderParams(defCritHeaders);
140        }
141
142
143        /**
144         * Gets the private RSA key.
145         *
146         * @return The private RSA key. Casting to
147         *         {@link java.security.interfaces.RSAPrivateKey} may not be
148         *         possible if the key is backed by a key store that doesn't
149         *         expose the private key parameters.
150         */
151        public PrivateKey getPrivateKey() {
152
153                return privateKey;
154        }
155
156
157        @Override
158        public Set<String> getProcessedCriticalHeaderParams() {
159
160                return critPolicy.getProcessedCriticalHeaderParams();
161        }
162
163
164        @Override
165        public Set<String> getDeferredCriticalHeaderParams() {
166
167                return critPolicy.getProcessedCriticalHeaderParams();
168        }
169
170
171        @Override
172        public byte[] decrypt(final JWEHeader header,
173                              final Base64URL encryptedKey,
174                              final Base64URL iv,
175                              final Base64URL cipherText,
176                              final Base64URL authTag) 
177                throws JOSEException {
178
179                // Validate required JWE parts
180                if (encryptedKey == null) {
181                        throw new JOSEException("Missing JWE encrypted key");
182                }       
183
184                if (iv == null) {
185                        throw new JOSEException("Missing JWE initialization vector (IV)");
186                }
187
188                if (authTag == null) {
189                        throw new JOSEException("Missing JWE authentication tag");
190                }
191
192                critPolicy.ensureHeaderPasses(header);
193                
194
195                // Derive the content encryption key
196                JWEAlgorithm alg = header.getAlgorithm();
197
198                SecretKey cek;
199
200                if (alg.equals(JWEAlgorithm.RSA1_5)) {
201
202                        int keyLength = header.getEncryptionMethod().cekBitLength();
203
204                        // Protect against MMA attack by generating random CEK on failure,
205                        // see http://www.ietf.org/mail-archive/web/jose/current/msg01832.html
206                        final SecretKey randomCEK = ContentCryptoProvider.generateCEK(header.getEncryptionMethod(), getJCAContext().getSecureRandom());
207
208                        try {
209                                cek = RSA1_5.decryptCEK(privateKey, encryptedKey.decode(), keyLength, getJCAContext().getKeyEncryptionProvider());
210
211                                if (cek == null) {
212                                        // CEK length mismatch, signalled by null instead of
213                                        // exception to prevent MMA attack
214                                        cek = randomCEK;
215                                }
216
217                        } catch (Exception e) {
218                                // continue
219                                cek = randomCEK;
220                        }
221                
222                } else if (alg.equals(JWEAlgorithm.RSA_OAEP)) {
223
224                        cek = RSA_OAEP.decryptCEK(privateKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider());
225
226                } else if (alg.equals(JWEAlgorithm.RSA_OAEP_256)) {
227                        
228                        cek = RSA_OAEP_256.decryptCEK(privateKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider());
229                        
230                } else {
231                
232                        throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, SUPPORTED_ALGORITHMS));
233                }
234
235                return ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext());
236        }
237}
238