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.util.Set;
022
023import javax.crypto.SecretKey;
024import javax.crypto.spec.SecretKeySpec;
025
026import com.nimbusds.jose.crypto.impl.*;
027import net.jcip.annotations.ThreadSafe;
028
029import com.nimbusds.jose.*;
030import com.nimbusds.jose.jwk.OctetSequenceKey;
031import com.nimbusds.jose.util.Base64URL;
032
033
034/**
035 * AES and AES GCM key wrap decrypter of {@link com.nimbusds.jose.JWEObject JWE
036 * objects}. Expects an AES key.
037 *
038 * <p>Unwraps the encrypted Content Encryption Key (CEK) with the specified AES
039 * key, and then uses the CEK along with the IV and authentication tag to
040 * decrypt the cipher text. See RFC 7518, sections
041 * <a href="https://tools.ietf.org/html/rfc7518#section-4.4">4.4</a> and
042 * <a href="https://tools.ietf.org/html/rfc7518#section-4.7">4.7</a> for more
043 * information.
044 *
045 * <p>This class is thread-safe.
046 *
047 * <p>Supports the following key management algorithms:
048 *
049 * <ul>
050 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#A128KW}
051 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#A192KW}
052 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#A256KW}
053 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#A128GCMKW}
054 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#A192GCMKW}
055 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#A256GCMKW}
056 * </ul>
057 *
058 * <p>Supports the following content encryption algorithms:
059 *
060 * <ul>
061 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256}
062 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384}
063 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512}
064 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128GCM}
065 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192GCM}
066 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256GCM}
067 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED}
068 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED}
069 *     <li>{@link com.nimbusds.jose.EncryptionMethod#XC20P}
070 * </ul>
071 *
072 * @author Melisa Halsband
073 * @author Vladimir Dzhuvinov
074 * @version 2015-06-29
075 */
076@ThreadSafe
077public class AESDecrypter extends AESCryptoProvider implements JWEDecrypter, CriticalHeaderParamsAware {
078
079
080        /**
081         * The critical header policy.
082         */
083        private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral();
084
085
086        /**
087         * Creates a new AES decrypter.
088         *
089         * @param kek The Key Encrypting Key. Must be 128 bits (16 bytes), 192
090         *            bits (24 bytes) or 256 bits (32 bytes). Must not be
091         *            {@code null}.
092         *
093         * @throws KeyLengthException If the KEK length is invalid.
094         */
095        public AESDecrypter(final SecretKey kek)
096                throws KeyLengthException {
097
098                this(kek, null);
099        }
100
101
102        /**
103         * Creates a new AES decrypter.
104         *
105         * @param keyBytes The Key Encrypting Key, as a byte array. Must be 128
106         *                 bits (16 bytes), 192 bits (24 bytes) or 256 bits (32
107         *                 bytes). Must not be {@code null}.
108         *
109         * @throws KeyLengthException If the KEK length is invalid.
110         */
111        public AESDecrypter(final byte[] keyBytes)
112                throws KeyLengthException {
113
114                this(new SecretKeySpec(keyBytes, "AES"));
115        }
116
117
118        /**
119         * Creates a new AES decrypter.
120         *
121         * @param octJWK The Key Encryption Key, as a JWK. Must be 128 bits (16
122         *               bytes), 192 bits (24 bytes), 256 bits (32 bytes), 384
123         *               bits (48 bytes) or 512 bits (64 bytes) long. Must not
124         *               be {@code null}.
125         *
126         * @throws KeyLengthException If the KEK length is invalid.
127         */
128        public AESDecrypter(final OctetSequenceKey octJWK)
129                throws KeyLengthException {
130
131                this(octJWK.toSecretKey("AES"));
132        }
133
134
135        /**
136         * Creates a new AES decrypter.
137         *
138         * @param kek            The Key Encrypting Key. Must be 128 bits (16
139         *                       bytes), 192 bits (24 bytes) or 256 bits (32
140         *                       bytes). Must not be {@code null}.
141         * @param defCritHeaders The names of the critical header parameters
142         *                       that are deferred to the application for
143         *                       processing, empty set or {@code null} if none.
144         *
145         * @throws KeyLengthException If the KEK length is invalid.
146         */
147        public AESDecrypter(final SecretKey kek, final Set<String> defCritHeaders)
148                throws KeyLengthException {
149
150                super(kek);
151
152                critPolicy.setDeferredCriticalHeaderParams(defCritHeaders);
153        }
154
155
156        @Override
157        public Set<String> getProcessedCriticalHeaderParams() {
158
159                return critPolicy.getProcessedCriticalHeaderParams();
160        }
161
162
163        @Override
164        public Set<String> getDeferredCriticalHeaderParams() {
165
166                return critPolicy.getProcessedCriticalHeaderParams();
167        }
168
169
170        @Override
171        public byte[] decrypt(final JWEHeader header,
172                              final Base64URL encryptedKey,
173                              final Base64URL iv,
174                              final Base64URL cipherText,
175                              final Base64URL authTag)
176                throws JOSEException {
177
178                // Validate required JWE parts
179                if (encryptedKey == null) {
180                        throw new JOSEException("Missing JWE encrypted key");
181                }
182
183                if (iv == null) {
184                        throw new JOSEException("Missing JWE initialization vector (IV)");
185                }
186
187                if (authTag == null) {
188                        throw new JOSEException("Missing JWE authentication tag");
189                }
190
191                critPolicy.ensureHeaderPasses(header);
192
193                // Derive the content encryption key
194                JWEAlgorithm alg = header.getAlgorithm();
195                int keyLength = header.getEncryptionMethod().cekBitLength();
196
197                final SecretKey cek;
198
199                if (alg.equals(JWEAlgorithm.A128KW) ||
200                    alg.equals(JWEAlgorithm.A192KW) ||
201                    alg.equals(JWEAlgorithm.A256KW))   {
202
203                        cek = AESKW.unwrapCEK(getKey(), encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider());
204
205                } else if (alg.equals(JWEAlgorithm.A128GCMKW) ||
206                           alg.equals(JWEAlgorithm.A192GCMKW) ||
207                           alg.equals(JWEAlgorithm.A256GCMKW)) {
208
209                        if (header.getIV() == null) {
210                                throw new JOSEException("Missing JWE \"iv\" header parameter");
211                        }
212
213                        byte[] keyIV = header.getIV().decode();
214
215                        if (header.getAuthTag() == null) {
216                                throw new JOSEException("Missing JWE \"tag\" header parameter");
217                        }
218
219                        byte[] keyTag = header.getAuthTag().decode();
220
221                        AuthenticatedCipherText authEncrCEK = new AuthenticatedCipherText(encryptedKey.decode(), keyTag);
222                        cek = AESGCMKW.decryptCEK(getKey(), keyIV, authEncrCEK, keyLength, getJCAContext().getKeyEncryptionProvider());
223
224                } else {
225
226                        throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, SUPPORTED_ALGORITHMS));
227                }
228
229                return ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext());
230        }
231}