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