001/* 
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.  
018 */
019package org.apache.wiki.util;
020
021import javax.crypto.SecretKeyFactory;
022import javax.crypto.spec.PBEKeySpec;
023import java.nio.charset.StandardCharsets;
024import java.security.MessageDigest;
025import java.security.NoSuchAlgorithmException;
026import java.security.SecureRandom;
027import java.security.spec.InvalidKeySpecException;
028import java.util.Base64;
029import java.util.Random;
030
031
032/**
033 * Hashes and verifies salted SHA-1 passwords, which are compliant with RFC
034 * 2307.
035 */
036public final class CryptoUtil {
037
038    private static final String SSHA = "{SSHA}";
039
040    private static final String SHA1 = "{SHA-1}";
041
042    private static final String SHA256 = "{SHA-256}";
043
044    private static final Random RANDOM = new SecureRandom();
045
046    private static final int DEFAULT_SALT_SIZE = 8;
047
048    /** Prefix of PBKDF2-HMAC-SHA256 password entries, the current password-storage format. */
049    public static final String PBKDF2_PREFIX = "{PBKDF2-SHA256}";
050
051    /** Iteration count for new PBKDF2-HMAC-SHA256 hashes, per current OWASP password-storage guidance. */
052    private static final int PBKDF2_ITERATIONS = 600_000;
053
054    private static final int PBKDF2_KEY_LENGTH_BYTES = 32;
055
056    private static final int PBKDF2_SALT_SIZE = 16;
057
058    private static final Object HELP = "--help";
059
060    private static final Object HASH = "--hash";
061
062    private static final Object VERIFY = "--verify";
063
064    /**
065     * Private constructor to prevent direct instantiation.
066     */
067    private CryptoUtil() {}
068
069    /**
070     * <p>
071     * Convenience method for hashing and verifying salted SHA-1 or SHA-256 passwords from
072     * the command line. This method requires <code>commons-codec-1.3.jar</code>
073     * (or a newer version) to be on the classpath. Command line arguments are
074     * as follows:
075     * </p>
076     * <ul>
077     * <li><code>--hash <var>password</var> SSHA</code> - hashes <var>password</var></code>
078     * and prints a password digest that looks like this: <blockquote><code>{SSHA}yfT8SRT/WoOuNuA6KbJeF10OznZmb28=</code></blockquote></li>
079     * <li><code>--verify <var>password</var> <var>digest</var></code> -
080     * verifies <var>password</var> by extracting the salt from <var>digest</var>
081     * (which is identical to what is printed by <code>--hash</code>) and
082     * re-computing the digest again using the password and salt. If the
083     * password supplied is the same as the one used to create the original
084     * digest, <code>true</code> will be printed; otherwise <code>false</code></li>
085     * </ul>
086     * <p>For example, one way to use this utility is to change to JSPWiki's <code>build</code> directory
087     * and type the following command:</p>
088     * <blockquote><code>java -cp JSPWiki.jar:../lib/commons-codec-1.3.jar org.apache.wiki.util.CryptoUtil --hash mynewpassword</code></blockquote>
089     * 
090     * @param args arguments for this method as described above
091     * @throws Exception Catches nothing; throws everything up.
092     */
093    public static void main( final String[] args ) throws Exception {
094        // Print help if the user requested it, or if no arguments
095        if( args.length == 0 || ( args.length == 1 && HELP.equals( args[0] ) ) ) {
096            System.out.println( "Usage: CryptoUtil [options] " );
097            System.out.println( "   --hash   password algorithm             create hash for password" );
098            System.out.println( "   --verify password digest algorithm      verify password for digest" );
099            System.out.println( "Valid algorithm options are {SSHA} and {SHA-256}. If no algorithm is specified or an unsupported algorithm is specified, SHA-256 is used." );
100        }
101
102        if( HASH.equals( args[0] ) ) {
103        // User wants to hash the password
104            if( args.length < 2 ) {
105                throw new IllegalArgumentException( "Error: --hash requires a 'password' argument." );
106            }
107            final String password = args[1].trim();
108            final String algorithm = args.length > 2 ? args[2].trim() : SHA256;
109
110            System.out.println( CryptoUtil.getSaltedPassword( password.getBytes( StandardCharsets.UTF_8 ), algorithm ) );
111        } else if( VERIFY.equals( args[0] ) ) {
112        // User wants to verify an existing password
113            if( args.length < 3 ) {
114                throw new IllegalArgumentException( "Error: --hash requires 'password' and 'digest' arguments." );
115            }
116            final String password = args[1].trim();
117            final String digest = args[2].trim();
118
119            System.out.println( CryptoUtil.verifySaltedPassword( password.getBytes( StandardCharsets.UTF_8 ), digest ) );
120        } else {
121            System.out.println( "Wrong usage. Try --help." );
122        }
123    }
124
125    /**
126     * <p>
127     * Creates an RFC 2307-compliant salted, hashed password with the SHA1 or SHA-256
128     * MessageDigest algorithm. After the password is digested, the first 20 or 32
129     * bytes of the digest will be the actual password hash; the remaining bytes
130     * will be a randomly generated salt of length {@link #DEFAULT_SALT_SIZE},
131     * for example: <blockquote><code>{SSHA}3cGWem65NCEkF5Ew5AEk45ak8LHUWAwPVXAyyw==</code></blockquote>
132     * </p>
133     * <p>
134     * In layman's terms, the formula is
135     * <code>digest( secret + salt ) + salt</code>. The resulting digest is Base64-encoded.
136     * </p>
137     * <p>
138     * Note that successive invocations of this method with the same password
139     * will result in different hashes! (This, of course, is exactly the point.)
140     * </p>
141     * 
142     * @param password the password to be digested
143     * @return the Base64-encoded password hash, prepended by
144     *         <code>{SSHA}</code> or <code>{SHA256}</code>.
145     * @throws NoSuchAlgorithmException If your JVM does not supply the necessary algorithm. Should not happen.
146     */
147    public static String getSaltedPassword( final byte[] password, final String algorithm ) throws NoSuchAlgorithmException {
148        final byte[] salt = new byte[ DEFAULT_SALT_SIZE ];
149        RANDOM.nextBytes( salt );
150
151        return getSaltedPassword( password, salt, algorithm );
152    }
153
154    /**
155     * <p>
156     * Helper method that creates an RFC 2307-compliant salted, hashed password with the SHA1 or SHA256
157     * MessageDigest algorithm. After the password is digested, the first 20 or 32
158     * bytes of the digest will be the actual password hash; the remaining bytes
159     * will be the salt. Thus, supplying a password <code>testing123</code>
160     * and a random salt <code>foo</code> produces the hash when using SHA1:
161     * </p>
162     * <blockquote><code>{SSHA}yfT8SRT/WoOuNuA6KbJeF10OznZmb28=</code></blockquote>
163     * <p>
164     * In layman's terms, the formula is
165     * <code>digest( secret + salt ) + salt</code>. The resulting digest is Base64-encoded.</p>
166     * 
167     * @param password the password to be digested
168     * @param salt the random salt
169     * @return the Base64-encoded password hash, prepended by <code>{SSHA}</code> or <code>{SHA256}</code>.
170     * @throws NoSuchAlgorithmException If your JVM does not supply the necessary algorithm. Should not happen.
171     */
172    static String getSaltedPassword( final byte[] password, final byte[] salt, final String algorithm ) throws NoSuchAlgorithmException {
173        //The term SSHA is used as a password prefix for backwards compatibility, but we use SHA-1 when fetching an instance
174        //of MessageDigest, as it is the guaranteed option. We also need to remove curly braces surrounding the string for
175        //backwards compatibility.
176        final String algorithmToUse = algorithm.equals(SSHA) ? SHA1 : algorithm;
177        final MessageDigest digest = MessageDigest.getInstance( algorithmToUse.substring( 1, algorithmToUse.length() -1 ) );
178        digest.update( password );
179        final byte[] hash = digest.digest( salt );
180
181        // Create an array with the hash plus the salt
182        final byte[] all = new byte[hash.length + salt.length];
183        System.arraycopy(hash, 0, all, 0, hash.length);
184        System.arraycopy(salt, 0, all, hash.length, salt.length);
185        final byte[] base64 = Base64.getEncoder().encode( all );
186        
187        return algorithm + new String( base64, StandardCharsets.UTF_8 );
188    }
189
190    /**
191     * <p>Creates an iterated, salted PBKDF2-HMAC-SHA256 hash of the given password, suitable for storage. Unlike the
192     * single-iteration digests above, the work factor makes offline cracking of a disclosed user database
193     * expensive. The format is <code>{PBKDF2-SHA256}<var>iterations</var>$base64(salt)$base64(hash)</code>, so the
194     * iteration count of stored entries can be raised in the future without breaking old entries.</p>
195     *
196     * @param password the password to be hashed
197     * @return the password entry, prepended by <code>{PBKDF2-SHA256}</code>
198     * @throws NoSuchAlgorithmException If your JVM does not supply the necessary algorithm. Should not happen.
199     */
200    public static String getPbkdf2SaltedPassword( final byte[] password ) throws NoSuchAlgorithmException {
201        final byte[] salt = new byte[ PBKDF2_SALT_SIZE ];
202        RANDOM.nextBytes( salt );
203        return getPbkdf2SaltedPassword( password, salt, PBKDF2_ITERATIONS );
204    }
205
206    static String getPbkdf2SaltedPassword( final byte[] password, final byte[] salt, final int iterations ) throws NoSuchAlgorithmException {
207        final byte[] hash = pbkdf2( password, salt, iterations );
208        final Base64.Encoder encoder = Base64.getEncoder();
209        return PBKDF2_PREFIX + iterations + "$" + encoder.encodeToString( salt ) + "$" + encoder.encodeToString( hash );
210    }
211
212    /**
213     * Verifies a password against a <code>{PBKDF2-SHA256}</code> entry created by
214     * {@link #getPbkdf2SaltedPassword(byte[])}. The comparison is constant-time.
215     *
216     * @param password the password to verify
217     * @param entry the stored password entry
218     * @return true if the password matches the entry
219     * @throws NoSuchAlgorithmException If your JVM does not supply the necessary algorithm. Should not happen.
220     */
221    public static boolean verifyPbkdf2SaltedPassword( final byte[] password, final String entry ) throws NoSuchAlgorithmException {
222        if( !entry.startsWith( PBKDF2_PREFIX ) ) {
223            throw new IllegalArgumentException( "Hash not prefixed by expected algorithm; is it really a PBKDF2 hash?" );
224        }
225        final String[] fields = entry.substring( PBKDF2_PREFIX.length() ).split( "\\$" );
226        if( fields.length != 3 ) {
227            throw new IllegalArgumentException( "Malformed PBKDF2 password entry" );
228        }
229        final int iterations = Integer.parseInt( fields[ 0 ] );
230        final byte[] salt = Base64.getDecoder().decode( fields[ 1 ] );
231        final byte[] expected = Base64.getDecoder().decode( fields[ 2 ] );
232        final byte[] hash = pbkdf2( password, salt, iterations );
233        return MessageDigest.isEqual( expected, hash );
234    }
235
236    private static byte[] pbkdf2( final byte[] password, final byte[] salt, final int iterations ) throws NoSuchAlgorithmException {
237        final char[] chars = new String( password, StandardCharsets.UTF_8 ).toCharArray();
238        final PBEKeySpec spec = new PBEKeySpec( chars, salt, iterations, PBKDF2_KEY_LENGTH_BYTES * 8 );
239        try {
240            return SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA256" ).generateSecret( spec ).getEncoded();
241        } catch( final InvalidKeySpecException e ) {
242            throw new NoSuchAlgorithmException( "Unable to compute PBKDF2 hash", e );
243        } finally {
244            spec.clearPassword();
245        }
246    }
247
248    /**
249     *  Compares a password to a given entry and returns true, if it matches.
250     *
251     *  @param password The password in bytes.
252     *  @param entry The password entry, typically starting with {SSHA}.
253     *  @return True, if the password matches.
254     *  @throws NoSuchAlgorithmException If there is no SHA available.
255     */
256    public static boolean verifySaltedPassword( final byte[] password, final String entry ) throws NoSuchAlgorithmException {
257        if( !entry.startsWith( SSHA ) && !entry.startsWith( SHA256 ) && !entry.startsWith( CryptoUtil.PBKDF2_PREFIX )  ) {
258            throw new IllegalArgumentException( "Hash not prefixed by expected algorithm; is it really a salted hash?" );
259        }
260        final String algorithm;
261        if (entry.startsWith(PBKDF2_PREFIX)) {
262            return verifyPbkdf2SaltedPassword(password, entry);
263        } else if (entry.startsWith(SSHA)) {
264            algorithm = SSHA;
265        } else if (entry.startsWith(SHA256)) {
266            algorithm = SHA256;
267        } else {
268            throw new NoSuchAlgorithmException("unknown hash algorithm prefix");
269        }
270
271        String hash2 = entry.substring( algorithm.length() );
272        byte[] bits = hash2.getBytes( StandardCharsets.UTF_8 );
273        final byte[] challenge = Base64.getDecoder().decode(bits);
274
275        // Extract the password hash and salt
276        final byte[] passwordHash = extractPasswordHash( challenge, algorithm.equals( SSHA ) ? 20 : 32 );
277        final byte[] salt = extractSalt( challenge, algorithm.equals( SSHA ) ? 20 : 32  );
278
279        // Re-create the hash using the password and the extracted salt
280        // The term SSHA is used as a password prefix for backwards compatibility, but we use SHA-1 when fetching an instance
281        // of MessageDigest, as it is the guaranteed option. We also need to remove curly braces surrounding the string for
282        // backwards compatibility.
283        final String algorithmToUse = algorithm.equals( SSHA ) ? SHA1 : algorithm;
284        final MessageDigest digest = MessageDigest.getInstance( algorithmToUse.substring( 1, algorithmToUse.length() -1 ) );
285        digest.update( password );
286        final byte[] hash = digest.digest( salt );
287
288        // See if our extracted hash matches what we just re-created
289        return MessageDigest.isEqual( passwordHash, hash );
290    }
291
292    /**
293     * Helper method that extracts the hashed password fragment from a supplied salted SHA-1 or SHA-256 digest
294     * by taking all the characters before position 20 or 32 depending on algorithm.
295     * 
296     * @param digest the salted digest, which is assumed to have been previously decoded from Base64.
297     * @return the password hash
298     * @throws IllegalArgumentException if the length of the supplied digest is less than or equal to 20 bytes
299     */
300    static byte[] extractPasswordHash( final byte[] digest, final int hashLength ) throws IllegalArgumentException {
301        if( digest.length < hashLength ) {
302            throw new IllegalArgumentException( "Hash was shorter than expected; could not extract password hash!" );
303        }
304
305        // Extract the password hash
306        final byte[] hash = new byte[ hashLength ];
307        System.arraycopy( digest, 0, hash, 0, hashLength );
308
309        return hash;
310    }
311
312    /**
313     * Helper method that extracts the salt from supplied salted digest by taking all the characters after a given index.
314     * 
315     * @param digest the salted digest, which is assumed to have been previously decoded from Base64.
316     * @return the salt
317     * @throws IllegalArgumentException if the length of the supplied digest is less than given length.
318     */
319    static byte[] extractSalt( final byte[] digest, final int hashLength ) throws IllegalArgumentException {
320        if( digest.length <= hashLength ) {
321            throw new IllegalArgumentException( "Hash was shorter than expected; we found no salt!" );
322        }
323
324        // Extract the salt
325        final byte[] salt = new byte[digest.length - hashLength];
326        System.arraycopy(digest, hashLength, salt, 0, digest.length - hashLength);
327
328        return salt;
329    }
330
331}