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.shiro.crypto.hash.format;
020
021import org.apache.shiro.codec.Base64;
022import org.apache.shiro.crypto.hash.Hash;
023import org.apache.shiro.crypto.hash.SimpleHash;
024import org.apache.shiro.util.ByteSource;
025import org.apache.shiro.util.StringUtils;
026
027/**
028 * The {@code Shiro1CryptFormat} is a fully reversible
029 * <a href="http://packages.python.org/passlib/modular_crypt_format.html">Modular Crypt Format</a> (MCF).  Because it is
030 * fully reversible (i.e. Hash -&gt; String, String -&gt; Hash), it does NOT use the traditional MCF encoding alphabet
031 * (the traditional MCF encoding, aka H64, is bit-destructive and cannot be reversed).  Instead, it uses fully
032 * reversible Base64 encoding for the Hash digest and any salt value.
033 * <h2>Format</h2>
034 * <p>Hash instances formatted with this implementation will result in a String with the following dollar-sign ($)
035 * delimited format:</p>
036 * <pre>
037 * <b>$</b>mcfFormatId<b>$</b>algorithmName<b>$</b>iterationCount<b>$</b>base64EncodedSalt<b>$</b>base64EncodedDigest
038 * </pre>
039 * <p>Each token is defined as follows:</p>
040 * <table>
041 *     <tr>
042 *         <th>Position</th>
043 *         <th>Token</th>
044 *         <th>Description</th>
045 *         <th>Required?</th>
046 *     </tr>
047 *     <tr>
048 *         <td>1</td>
049 *         <td>{@code mcfFormatId}</td>
050 *         <td>The Modular Crypt Format identifier for this implementation, equal to <b>{@code shiro1}</b>.
051 *             ( This implies that all {@code shiro1} MCF-formatted strings will always begin with the prefix
052 *             {@code $shiro1$} ).</td>
053 *         <td>true</td>
054 *     </tr>
055 *     <tr>
056 *         <td>2</td>
057 *         <td>{@code algorithmName}</td>
058 *         <td>The name of the hash algorithm used to perform the hash.  This is an algorithm name understood by
059 *         {@code MessageDigest}.{@link java.security.MessageDigest#getInstance(String) getInstance}, for example
060 *         {@code MD5}, {@code SHA-256}, {@code SHA-256}, etc.</td>
061 *         <td>true</td>
062 *     </tr>
063 *     <tr>
064 *         <td>3</td>
065 *         <td>{@code iterationCount}</td>
066 *         <td>The number of hash iterations performed.</td>
067 *         <td>true (1 <= N <= Integer.MAX_VALUE)</td>
068 *     </tr>
069 *     <tr>
070 *         <td>4</td>
071 *         <td>{@code base64EncodedSalt}</td>
072 *         <td>The Base64-encoded salt byte array.  This token only exists if a salt was used to perform the hash.</td>
073 *         <td>false</td>
074 *     </tr>
075 *     <tr>
076 *         <td>5</td>
077 *         <td>{@code base64EncodedDigest}</td>
078 *         <td>The Base64-encoded digest byte array.  This is the actual hash result.</td>
079 *         <td>true</td>
080 *     </tr>
081 * </table>
082 *
083 * @see ModularCryptFormat
084 * @see ParsableHashFormat
085 *
086 * @since 1.2
087 */
088public class Shiro1CryptFormat implements ModularCryptFormat, ParsableHashFormat {
089
090    public static final String ID = "shiro1";
091    public static final String MCF_PREFIX = TOKEN_DELIMITER + ID + TOKEN_DELIMITER;
092
093    public Shiro1CryptFormat() {
094    }
095
096    public String getId() {
097        return ID;
098    }
099
100    public String format(Hash hash) {
101        if (hash == null) {
102            return null;
103        }
104
105        String algorithmName = hash.getAlgorithmName();
106        ByteSource salt = hash.getSalt();
107        int iterations = hash.getIterations();
108        StringBuilder sb = new StringBuilder(MCF_PREFIX).append(algorithmName).append(TOKEN_DELIMITER).append(iterations).append(TOKEN_DELIMITER);
109
110        if (salt != null) {
111            sb.append(salt.toBase64());
112        }
113
114        sb.append(TOKEN_DELIMITER);
115        sb.append(hash.toBase64());
116
117        return sb.toString();
118    }
119
120    public Hash parse(String formatted) {
121        if (formatted == null) {
122            return null;
123        }
124        if (!formatted.startsWith(MCF_PREFIX)) {
125            //TODO create a HashFormatException class
126            String msg = "The argument is not a valid '" + ID + "' formatted hash.";
127            throw new IllegalArgumentException(msg);
128        }
129
130        String suffix = formatted.substring(MCF_PREFIX.length());
131        String[] parts = suffix.split("\\$");
132
133        //last part is always the digest/checksum, Base64-encoded:
134        int i = parts.length-1;
135        String digestBase64 = parts[i--];
136        //second-to-last part is always the salt, Base64-encoded:
137        String saltBase64 = parts[i--];
138        String iterationsString = parts[i--];
139        String algorithmName = parts[i];
140
141        byte[] digest = Base64.decode(digestBase64);
142        ByteSource salt = null;
143
144        if (StringUtils.hasLength(saltBase64)) {
145            byte[] saltBytes = Base64.decode(saltBase64);
146            salt = ByteSource.Util.bytes(saltBytes);
147        }
148
149        int iterations;
150        try {
151            iterations = Integer.parseInt(iterationsString);
152        } catch (NumberFormatException e) {
153            String msg = "Unable to parse formatted hash string: " + formatted;
154            throw new IllegalArgumentException(msg, e);
155        }
156
157        SimpleHash hash = new SimpleHash(algorithmName);
158        hash.setBytes(digest);
159        if (salt != null) {
160            hash.setSalt(salt);
161        }
162        hash.setIterations(iterations);
163
164        return hash;
165    }
166}