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