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 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 * @version 2021-07-03
064 */
065@ThreadSafe
066public class PasswordBasedEncrypter extends PasswordBasedCryptoProvider implements JWEEncrypter {
067
068
069        /**
070         * The minimum salt length (8 bytes).
071         */
072        public static final int MIN_SALT_LENGTH = PBKDF2.MIN_SALT_LENGTH;
073
074
075        /**
076         * The cryptographic salt length, in bytes.
077         */
078        private final int saltLength;
079
080
081        /**
082         * The minimum recommended iteration count (1000).
083         */
084        public static final int MIN_RECOMMENDED_ITERATION_COUNT = 1000;
085
086
087        /**
088         * The iteration count.
089         */
090        private final int iterationCount;
091
092
093        /**
094         * Creates a new password-based encrypter.
095         *
096         * @param password       The password bytes. Must not be empty or
097         *                       {@code null}.
098         * @param saltLength     The length of the generated cryptographic
099         *                       salts, in bytes. Must be at least 8 bytes.
100         * @param iterationCount The pseudo-random function (PRF) iteration
101         *                       count. Must be at least 1000.
102         */
103        public PasswordBasedEncrypter(final byte[] password,
104                                      final int saltLength,
105                                      final int iterationCount) {
106
107                super(password);
108
109                if (saltLength < MIN_SALT_LENGTH) {
110                        throw new IllegalArgumentException("The minimum salt length (p2s) is " + MIN_SALT_LENGTH + " bytes");
111                }
112
113                this.saltLength = saltLength;
114
115                if (iterationCount < MIN_RECOMMENDED_ITERATION_COUNT) {
116                        throw new IllegalArgumentException("The minimum recommended iteration count (p2c) is " + MIN_RECOMMENDED_ITERATION_COUNT);
117                }
118
119                this.iterationCount = iterationCount;
120        }
121
122
123        /**
124         * Creates a new password-based encrypter.
125         *
126         * @param password       The password, as a UTF-8 encoded string. Must
127         *                       not be empty or {@code null}.
128         * @param saltLength     The length of the generated cryptographic
129         *                       salts, in bytes. Must be at least 8 bytes.
130         * @param iterationCount The pseudo-random function (PRF) iteration
131         *                       count. Must be at least 1000.
132         */
133        public PasswordBasedEncrypter(final String password,
134                                      final int saltLength,
135                                      final int iterationCount) {
136
137                this(password.getBytes(StandardCharset.UTF_8), saltLength, iterationCount);
138        }
139
140
141        @Override
142        public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText)
143                throws JOSEException {
144
145                final JWEAlgorithm alg = header.getAlgorithm();
146                final EncryptionMethod enc = header.getEncryptionMethod();
147
148                final byte[] salt = new byte[saltLength];
149                getJCAContext().getSecureRandom().nextBytes(salt);
150                final byte[] formattedSalt = PBKDF2.formatSalt(alg, salt);
151                final PRFParams prfParams = PRFParams.resolve(alg, getJCAContext().getMACProvider());
152                final SecretKey psKey = PBKDF2.deriveKey(getPassword(), formattedSalt, iterationCount, prfParams);
153
154                // We need to work on the header
155                final JWEHeader updatedHeader = new JWEHeader.Builder(header).
156                        pbes2Salt(Base64URL.encode(salt)).
157                        pbes2Count(iterationCount).
158                        build();
159
160                final SecretKey cek = ContentCryptoProvider.generateCEK(enc, getJCAContext().getSecureRandom());
161
162                // The second JWE part
163                final Base64URL encryptedKey = Base64URL.encode(AESKW.wrapCEK(cek, psKey, getJCAContext().getKeyEncryptionProvider()));
164
165                return  ContentCryptoProvider.encrypt(updatedHeader, clearText, cek, encryptedKey, getJCAContext());
166        }
167
168
169        /**
170         * Returns the length of the generated cryptographic salts.
171         *
172         * @return The length of the generated cryptographic salts, in bytes.
173         */
174        public int getSaltLength() {
175
176                return saltLength;
177        }
178
179
180        /**
181         * Returns the pseudo-random function (PRF) iteration count.
182         *
183         * @return The iteration count.
184         */
185        public int getIterationCount() {
186
187                return iterationCount;
188        }
189}