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.crypto.hash.Hash; 22 import org.apache.shiro.crypto.hash.SimpleHash; 23 import org.apache.shiro.crypto.hash.SimpleHashProvider; 24 import org.apache.shiro.lang.codec.Base64; 25 import org.apache.shiro.lang.util.ByteSource; 26 import org.apache.shiro.lang.util.StringUtils; 27 28 /** 29 * The {@code Shiro1CryptFormat} is a fully reversible 30 * <a href="http://packages.python.org/passlib/modular_crypt_format.html">Modular Crypt Format</a> (MCF). Because it is 31 * fully reversible (i.e. Hash -> String, String -> Hash), it does NOT use the traditional MCF encoding alphabet 32 * (the traditional MCF encoding, aka H64, is bit-destructive and cannot be reversed). Instead, it uses fully 33 * reversible Base64 encoding for the Hash digest and any salt value. 34 * <h2>Format</h2> 35 * <p>Hash instances formatted with this implementation will result in a String with the following dollar-sign ($) 36 * delimited format:</p> 37 * <pre> 38 * <b>$</b>mcfFormatId<b>$</b>algorithmName<b>$</b>iterationCount<b>$</b>base64EncodedSalt<b>$</b>base64EncodedDigest 39 * </pre> 40 * <p>Each token is defined as follows:</p> 41 * <table> 42 * <tr> 43 * <th>Position</th> 44 * <th>Token</th> 45 * <th>Description</th> 46 * <th>Required?</th> 47 * </tr> 48 * <tr> 49 * <td>1</td> 50 * <td>{@code mcfFormatId}</td> 51 * <td>The Modular Crypt Format identifier for this implementation, equal to <b>{@code shiro1}</b>. 52 * ( This implies that all {@code shiro1} MCF-formatted strings will always begin with the prefix 53 * {@code $shiro1$} ).</td> 54 * <td>true</td> 55 * </tr> 56 * <tr> 57 * <td>2</td> 58 * <td>{@code algorithmName}</td> 59 * <td>The name of the hash algorithm used to perform the hash. This is an algorithm name understood by 60 * {@code MessageDigest}.{@link java.security.MessageDigest#getInstance(String) getInstance}, for example 61 * {@code MD5}, {@code SHA-256}, {@code SHA-256}, etc.</td> 62 * <td>true</td> 63 * </tr> 64 * <tr> 65 * <td>3</td> 66 * <td>{@code iterationCount}</td> 67 * <td>The number of hash iterations performed.</td> 68 * <td>true (1 <= N <= Integer.MAX_VALUE)</td> 69 * </tr> 70 * <tr> 71 * <td>4</td> 72 * <td>{@code base64EncodedSalt}</td> 73 * <td>The Base64-encoded salt byte array. This token only exists if a salt was used to perform the hash.</td> 74 * <td>false</td> 75 * </tr> 76 * <tr> 77 * <td>5</td> 78 * <td>{@code base64EncodedDigest}</td> 79 * <td>The Base64-encoded digest byte array. This is the actual hash result.</td> 80 * <td>true</td> 81 * </tr> 82 * </table> 83 * 84 * @see ModularCryptFormat 85 * @see ParsableHashFormat 86 * @since 1.2 87 */ 88 public class Shiro1CryptFormat implements ModularCryptFormat, ParsableHashFormat { 89 90 /** 91 * shiro1 crypt id. 92 */ 93 public static final String ID = "shiro1"; 94 95 /** 96 * shiro1 crypt format prefix 97 */ 98 public static final String MCF_PREFIX = TOKEN_DELIMITER + ID + TOKEN_DELIMITER; 99 100 public Shiro1CryptFormat() { 101 } 102 103 @Override 104 public String getId() { 105 return ID; 106 } 107 108 @Override 109 public String format(final Hash hash) { 110 if (hash == null) { 111 return null; 112 } 113 114 String algorithmName = hash.getAlgorithmName(); 115 ByteSource salt = hash.getSalt(); 116 int iterations = hash.getIterations(); 117 StringBuilder sb = new StringBuilder(MCF_PREFIX) 118 .append(algorithmName) 119 .append(TOKEN_DELIMITER) 120 .append(iterations) 121 .append(TOKEN_DELIMITER); 122 123 if (salt != null) { 124 sb.append(salt.toBase64()); 125 } 126 127 sb.append(TOKEN_DELIMITER); 128 sb.append(hash.toBase64()); 129 130 return sb.toString(); 131 } 132 133 @Override 134 public Hash parse(final String formatted) { 135 if (formatted == null) { 136 return null; 137 } 138 if (!formatted.startsWith(MCF_PREFIX)) { 139 //TODO create a HashFormatException class 140 String msg = "The argument is not a valid '" + ID + "' formatted hash."; 141 throw new IllegalArgumentException(msg); 142 } 143 144 String suffix = formatted.substring(MCF_PREFIX.length()); 145 String[] parts = suffix.split("\\$"); 146 147 final String algorithmName = parts[0]; 148 if (!new SimpleHashProvider().getImplementedAlgorithms().contains(algorithmName)) { 149 throw new UnsupportedOperationException("Algorithm " + algorithmName + " is not supported in shiro1 format."); 150 } 151 152 //last part is always the digest/checksum, Base64-encoded: 153 int i = parts.length - 1; 154 String digestBase64 = parts[i--]; 155 //second-to-last part is always the salt, Base64-encoded: 156 String saltBase64 = parts[i--]; 157 String iterationsString = parts[i--]; 158 159 byte[] digest = Base64.decode(digestBase64); 160 ByteSource salt; 161 162 if (StringUtils.hasLength(saltBase64)) { 163 byte[] saltBytes = Base64.decode(saltBase64); 164 salt = ByteSource.Util.bytes(saltBytes); 165 } else { 166 salt = ByteSource.Util.bytes(new byte[0]); 167 } 168 169 int iterations; 170 try { 171 iterations = Integer.parseInt(iterationsString); 172 } catch (NumberFormatException e) { 173 String msg = "Unable to parse formatted hash string: " + formatted; 174 throw new IllegalArgumentException(msg, e); 175 } 176 177 SimpleHash hash = new SimpleHash(algorithmName); 178 hash.setBytes(digest); 179 hash.setSalt(salt); 180 hash.setIterations(iterations); 181 182 return hash; 183 } 184 }