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
020import java.util.Arrays;
021import javax.crypto.SecretKey;
022
023import com.nimbusds.jose.*;
024import com.nimbusds.jose.crypto.impl.*;
025import com.nimbusds.jose.util.Base64URL;
026import com.nimbusds.jose.util.StandardCharset;
027import net.jcip.annotations.ThreadSafe;
028
029
030/**
031 * Password-based encrypter of {@link com.nimbusds.jose.JWEObject JWE objects}.
032 * Expects a password.
033 *
034 * <p>See RFC 7518
035 * <a href="https://tools.ietf.org/html/rfc7518#section-4.8">section 4.8</a>
036 * for more information.
037 *
038 * <p>This class is thread-safe.
039 *
040 * <p>Supports the following key management algorithms:
041 *
042 * <ul>
043 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS256_A128KW}
044 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS384_A192KW}
045 *     <li>{@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS512_A256KW}
046 * </ul>
047 *
048 * <p>Supports the following content encryption algorithms:
049 *
050 * <ul>
051 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256}
052 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384}
053 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512}
054 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128GCM}
055 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A192GCM}
056 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256GCM}
057 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED}
058 *     <li>{@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED}
059 *     <li>{@link com.nimbusds.jose.EncryptionMethod#XC20P}
060 * </ul>
061 *
062 * @author Vladimir Dzhuvinov
063 * @author Egor Puzanov
064 * @version 2023-09-10
065 */
066@ThreadSafe
067public class PasswordBasedEncrypter extends PasswordBasedCryptoProvider implements JWEEncrypter {
068
069
070        /**
071         * The minimum salt length (8 bytes).
072         */
073        public static final int MIN_SALT_LENGTH = PBKDF2.MIN_SALT_LENGTH;
074
075
076        /**
077         * The cryptographic salt length, in bytes.
078         */
079        private final int saltLength;
080
081
082        /**
083         * The minimum recommended iteration count (1000).
084         */
085        public static final int MIN_RECOMMENDED_ITERATION_COUNT = 1000;
086
087
088        /**
089         * The iteration count.
090         */
091        private final int iterationCount;
092
093
094        /**
095         * Creates a new password-based encrypter.
096         *
097         * @param password       The password bytes. Must not be empty or
098         *                       {@code null}.
099         * @param saltLength     The length of the generated cryptographic
100         *                       salts, in bytes. Must be at least 8 bytes.
101         * @param iterationCount The pseudo-random function (PRF) iteration
102         *                       count. Must be at least 1000.
103         */
104        public PasswordBasedEncrypter(final byte[] password,
105                                      final int saltLength,
106                                      final int iterationCount) {
107
108                super(password);
109
110                if (saltLength < MIN_SALT_LENGTH) {
111                        throw new IllegalArgumentException("The minimum salt length (p2s) is " + MIN_SALT_LENGTH + " bytes");
112                }
113
114                this.saltLength = saltLength;
115
116                if (iterationCount < MIN_RECOMMENDED_ITERATION_COUNT) {
117                        throw new IllegalArgumentException("The minimum recommended iteration count (p2c) is " + MIN_RECOMMENDED_ITERATION_COUNT);
118                }
119
120                this.iterationCount = iterationCount;
121        }
122
123
124        /**
125         * Creates a new password-based encrypter.
126         *
127         * @param password       The password, as a UTF-8 encoded string. Must
128         *                       not be empty or {@code null}.
129         * @param saltLength     The length of the generated cryptographic
130         *                       salts, in bytes. Must be at least 8 bytes.
131         * @param iterationCount The pseudo-random function (PRF) iteration
132         *                       count. Must be at least 1000.
133         */
134        public PasswordBasedEncrypter(final String password,
135                                      final int saltLength,
136                                      final int iterationCount) {
137
138                this(password.getBytes(StandardCharset.UTF_8), saltLength, iterationCount);
139        }
140
141
142        /**
143         * Encrypts the specified clear text of a {@link JWEObject JWE object}.
144         *
145         * @param header    The JSON Web Encryption (JWE) header. Must specify
146         *                  a supported JWE algorithm and method. Must not be
147         *                  {@code null}.
148         * @param clearText The clear text to encrypt. Must not be {@code null}.
149         *
150         * @return The resulting JWE crypto parts.
151         *
152         * @throws JOSEException If the JWE algorithm or method is not
153         *                       supported or if encryption failed for some
154         *                       other internal reason.
155         */
156        @Deprecated
157        public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText)
158                throws JOSEException {
159
160                return encrypt(header, clearText, AAD.compute(header));
161        }
162
163
164        @Override
165        public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText, final byte[] aad)
166                throws JOSEException {
167
168                final JWEAlgorithm alg = JWEHeaderValidation.getAlgorithmAndEnsureNotNull(header);
169                final EncryptionMethod enc = header.getEncryptionMethod();
170
171                final byte[] salt = new byte[saltLength];
172                getJCAContext().getSecureRandom().nextBytes(salt);
173                final byte[] formattedSalt = PBKDF2.formatSalt(alg, salt);
174                final PRFParams prfParams = PRFParams.resolve(alg, getJCAContext().getMACProvider());
175                final SecretKey psKey = PBKDF2.deriveKey(getPassword(), formattedSalt, iterationCount, prfParams);
176
177                // We need to work on the header
178                final JWEHeader updatedHeader = new JWEHeader.Builder(header).
179                        pbes2Salt(Base64URL.encode(salt)).
180                        pbes2Count(iterationCount).
181                        build();
182
183                final SecretKey cek = ContentCryptoProvider.generateCEK(enc, getJCAContext().getSecureRandom());
184
185                // The second JWE part
186                final Base64URL encryptedKey = Base64URL.encode(AESKW.wrapCEK(cek, psKey, getJCAContext().getKeyEncryptionProvider()));
187
188                // for JWEObject we need update the AAD as well
189                final byte[] updatedAAD = Arrays.equals(AAD.compute(header), aad) ? AAD.compute(updatedHeader) : aad;
190
191                return ContentCryptoProvider.encrypt(updatedHeader, clearText, updatedAAD, cek, encryptedKey, getJCAContext());
192        }
193
194
195        /**
196         * Returns the length of the generated cryptographic salts.
197         *
198         * @return The length of the generated cryptographic salts, in bytes.
199         */
200        public int getSaltLength() {
201
202                return saltLength;
203        }
204
205
206        /**
207         * Returns the pseudo-random function (PRF) iteration count.
208         *
209         * @return The iteration count.
210         */
211        public int getIterationCount() {
212
213                return iterationCount;
214        }
215}