View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.crypto.hash.format;
20  
21  import org.apache.shiro.codec.Base64;
22  import org.apache.shiro.crypto.hash.Hash;
23  import org.apache.shiro.crypto.hash.SimpleHash;
24  import org.apache.shiro.util.ByteSource;
25  import org.apache.shiro.util.StringUtils;
26  
27  /**
28   * The {@code Shiro1CryptFormat} is a fully reversible
29   * <a href="http://packages.python.org/passlib/modular_crypt_format.html">Modular Crypt Format</a> (MCF).  Because it is
30   * fully reversible (i.e. Hash -&gt; String, String -&gt; Hash), it does NOT use the traditional MCF encoding alphabet
31   * (the traditional MCF encoding, aka H64, is bit-destructive and cannot be reversed).  Instead, it uses fully
32   * reversible Base64 encoding for the Hash digest and any salt value.
33   * <h2>Format</h2>
34   * <p>Hash instances formatted with this implementation will result in a String with the following dollar-sign ($)
35   * delimited format:</p>
36   * <pre>
37   * <b>$</b>mcfFormatId<b>$</b>algorithmName<b>$</b>iterationCount<b>$</b>base64EncodedSalt<b>$</b>base64EncodedDigest
38   * </pre>
39   * <p>Each token is defined as follows:</p>
40   * <table>
41   *     <tr>
42   *         <th>Position</th>
43   *         <th>Token</th>
44   *         <th>Description</th>
45   *         <th>Required?</th>
46   *     </tr>
47   *     <tr>
48   *         <td>1</td>
49   *         <td>{@code mcfFormatId}</td>
50   *         <td>The Modular Crypt Format identifier for this implementation, equal to <b>{@code shiro1}</b>.
51   *             ( This implies that all {@code shiro1} MCF-formatted strings will always begin with the prefix
52   *             {@code $shiro1$} ).</td>
53   *         <td>true</td>
54   *     </tr>
55   *     <tr>
56   *         <td>2</td>
57   *         <td>{@code algorithmName}</td>
58   *         <td>The name of the hash algorithm used to perform the hash.  This is an algorithm name understood by
59   *         {@code MessageDigest}.{@link java.security.MessageDigest#getInstance(String) getInstance}, for example
60   *         {@code MD5}, {@code SHA-256}, {@code SHA-256}, etc.</td>
61   *         <td>true</td>
62   *     </tr>
63   *     <tr>
64   *         <td>3</td>
65   *         <td>{@code iterationCount}</td>
66   *         <td>The number of hash iterations performed.</td>
67   *         <td>true (1 <= N <= Integer.MAX_VALUE)</td>
68   *     </tr>
69   *     <tr>
70   *         <td>4</td>
71   *         <td>{@code base64EncodedSalt}</td>
72   *         <td>The Base64-encoded salt byte array.  This token only exists if a salt was used to perform the hash.</td>
73   *         <td>false</td>
74   *     </tr>
75   *     <tr>
76   *         <td>5</td>
77   *         <td>{@code base64EncodedDigest}</td>
78   *         <td>The Base64-encoded digest byte array.  This is the actual hash result.</td>
79   *         <td>true</td>
80   *     </tr>
81   * </table>
82   *
83   * @see ModularCryptFormat
84   * @see ParsableHashFormat
85   *
86   * @since 1.2
87   */
88  public class Shiro1CryptFormat implements ModularCryptFormat, ParsableHashFormat {
89  
90      public static final String ID = "shiro1";
91      public static final String MCF_PREFIX = TOKEN_DELIMITER + ID + TOKEN_DELIMITER;
92  
93      public Shiro1CryptFormat() {
94      }
95  
96      public String getId() {
97          return ID;
98      }
99  
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 }