| <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../jacoco-resources/report.gif" type="image/gif"/><title>SimpleHash.java</title><link rel="stylesheet" href="../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../index.html" class="el_report">Apache Shiro :: Cryptography :: Hashing</a> > <a href="index.source.html" class="el_package">org.apache.shiro.crypto.hash</a> > <span class="el_source">SimpleHash.java</span></div><h1>SimpleHash.java</h1><pre class="source lang-java linenums">/* |
| * Licensed to the Apache Software Foundation (ASF) under one |
| * or more contributor license agreements. See the NOTICE file |
| * distributed with this work for additional information |
| * regarding copyright ownership. The ASF licenses this file |
| * to you under the Apache License, Version 2.0 (the |
| * "License"); you may not use this file except in compliance |
| * with the License. You may obtain a copy of the License at |
| * |
| * http://www.apache.org/licenses/LICENSE-2.0 |
| * |
| * Unless required by applicable law or agreed to in writing, |
| * software distributed under the License is distributed on an |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| * KIND, either express or implied. See the License for the |
| * specific language governing permissions and limitations |
| * under the License. |
| */ |
| package org.apache.shiro.crypto.hash; |
| |
| import org.apache.shiro.codec.Base64; |
| import org.apache.shiro.codec.CodecException; |
| import org.apache.shiro.codec.Hex; |
| import org.apache.shiro.crypto.UnknownAlgorithmException; |
| import org.apache.shiro.util.ByteSource; |
| import org.apache.shiro.util.StringUtils; |
| |
| import java.security.MessageDigest; |
| import java.security.NoSuchAlgorithmException; |
| import java.util.Arrays; |
| |
| /** |
| * A {@code Hash} implementation that allows any {@link java.security.MessageDigest MessageDigest} algorithm name to |
| * be used. This class is a less type-safe variant than the other {@code AbstractHash} subclasses |
| * (e.g. {@link Sha512Hash}, etc), but it does allow for any algorithm name to be specified in case the other subclass |
| * implementations do not represent an algorithm that you may want to use. |
| * <p/> |
| * As of Shiro 1.1, this class effectively replaces the (now-deprecated) {@link AbstractHash} class. It subclasses |
| * {@code AbstractHash} only to retain backwards-compatibility. |
| * |
| * @since 1.1 |
| */ |
| public class SimpleHash extends AbstractHash { |
| |
| private static final int DEFAULT_ITERATIONS = 1; |
| |
| /** |
| * The {@link java.security.MessageDigest MessageDigest} algorithm name to use when performing the hash. |
| */ |
| private final String algorithmName; |
| |
| /** |
| * The hashed data |
| */ |
| private byte[] bytes; |
| |
| /** |
| * Supplied salt, if any. |
| */ |
| private ByteSource salt; |
| |
| /** |
| * Number of hash iterations to perform. Defaults to 1 in the constructor. |
| */ |
| private int iterations; |
| |
| /** |
| * Cached value of the {@link #toHex() toHex()} call so multiple calls won't incur repeated overhead. |
| */ |
| <span class="fc" id="L70"> private transient String hexEncoded = null;</span> |
| |
| /** |
| * Cached value of the {@link #toBase64() toBase64()} call so multiple calls won't incur repeated overhead. |
| */ |
| <span class="fc" id="L75"> private transient String base64Encoded = null;</span> |
| |
| /** |
| * Creates an new instance with only its {@code algorithmName} set - no hashing is performed. |
| * <p/> |
| * Because all other constructors in this class hash the {@code source} constructor argument, this |
| * constructor is useful in scenarios when you have a byte array that you know is already hashed and |
| * just want to set the bytes in their raw form directly on an instance. After using this constructor, |
| * you can then immediately call {@link #setBytes setBytes} to have a fully-initialized instance. |
| * <p/> |
| * <b>N.B.</b>The algorithm identified by the {@code algorithmName} parameter must be available on the JVM. If it |
| * is not, a {@link UnknownAlgorithmException} will be thrown when the hash is performed (not at instantiation). |
| * |
| * @param algorithmName the {@link java.security.MessageDigest MessageDigest} algorithm name to use when |
| * performing the hash. |
| * @see UnknownAlgorithmException |
| */ |
| <span class="fc" id="L92"> public SimpleHash(String algorithmName) {</span> |
| <span class="fc" id="L93"> this.algorithmName = algorithmName;</span> |
| <span class="fc" id="L94"> this.iterations = DEFAULT_ITERATIONS;</span> |
| <span class="fc" id="L95"> }</span> |
| |
| /** |
| * Creates an {@code algorithmName}-specific hash of the specified {@code source} with no {@code salt} using a |
| * single hash iteration. |
| * <p/> |
| * This is a convenience constructor that merely executes <code>this( algorithmName, source, null, 1);</code>. |
| * <p/> |
| * Please see the |
| * {@link #SimpleHash(String algorithmName, Object source, Object salt, int numIterations) SimpleHashHash(algorithmName, Object,Object,int)} |
| * constructor for the types of Objects that may be passed into this constructor, as well as how to support further |
| * types. |
| * |
| * @param algorithmName the {@link java.security.MessageDigest MessageDigest} algorithm name to use when |
| * performing the hash. |
| * @param source the object to be hashed. |
| * @throws org.apache.shiro.codec.CodecException |
| * if the specified {@code source} cannot be converted into a byte array (byte[]). |
| * @throws UnknownAlgorithmException if the {@code algorithmName} is not available. |
| */ |
| public SimpleHash(String algorithmName, Object source) throws CodecException, UnknownAlgorithmException { |
| //noinspection NullableProblems |
| <span class="fc" id="L117"> this(algorithmName, source, null, DEFAULT_ITERATIONS);</span> |
| <span class="fc" id="L118"> }</span> |
| |
| /** |
| * Creates an {@code algorithmName}-specific hash of the specified {@code source} using the given {@code salt} |
| * using a single hash iteration. |
| * <p/> |
| * It is a convenience constructor that merely executes <code>this( algorithmName, source, salt, 1);</code>. |
| * <p/> |
| * Please see the |
| * {@link #SimpleHash(String algorithmName, Object source, Object salt, int numIterations) SimpleHashHash(algorithmName, Object,Object,int)} |
| * constructor for the types of Objects that may be passed into this constructor, as well as how to support further |
| * types. |
| * |
| * @param algorithmName the {@link java.security.MessageDigest MessageDigest} algorithm name to use when |
| * performing the hash. |
| * @param source the source object to be hashed. |
| * @param salt the salt to use for the hash |
| * @throws CodecException if either constructor argument cannot be converted into a byte array. |
| * @throws UnknownAlgorithmException if the {@code algorithmName} is not available. |
| */ |
| public SimpleHash(String algorithmName, Object source, Object salt) throws CodecException, UnknownAlgorithmException { |
| <span class="nc" id="L139"> this(algorithmName, source, salt, DEFAULT_ITERATIONS);</span> |
| <span class="nc" id="L140"> }</span> |
| |
| /** |
| * Creates an {@code algorithmName}-specific hash of the specified {@code source} using the given |
| * {@code salt} a total of {@code hashIterations} times. |
| * <p/> |
| * By default, this class only supports Object method arguments of |
| * type {@code byte[]}, {@code char[]}, {@link String}, {@link java.io.File File}, |
| * {@link java.io.InputStream InputStream} or {@link org.apache.shiro.util.ByteSource ByteSource}. If either |
| * argument is anything other than these types a {@link org.apache.shiro.codec.CodecException CodecException} |
| * will be thrown. |
| * <p/> |
| * If you want to be able to hash other object types, or use other salt types, you need to override the |
| * {@link #toBytes(Object) toBytes(Object)} method to support those specific types. Your other option is to |
| * convert your arguments to one of the default supported types first before passing them in to this |
| * constructor}. |
| * |
| * @param algorithmName the {@link java.security.MessageDigest MessageDigest} algorithm name to use when |
| * performing the hash. |
| * @param source the source object to be hashed. |
| * @param salt the salt to use for the hash |
| * @param hashIterations the number of times the {@code source} argument hashed for attack resiliency. |
| * @throws CodecException if either Object constructor argument cannot be converted into a byte array. |
| * @throws UnknownAlgorithmException if the {@code algorithmName} is not available. |
| */ |
| public SimpleHash(String algorithmName, Object source, Object salt, int hashIterations) |
| <span class="fc" id="L166"> throws CodecException, UnknownAlgorithmException {</span> |
| <span class="pc bpc" id="L167" title="1 of 2 branches missed."> if (!StringUtils.hasText(algorithmName)) {</span> |
| <span class="nc" id="L168"> throw new NullPointerException("algorithmName argument cannot be null or empty.");</span> |
| } |
| <span class="fc" id="L170"> this.algorithmName = algorithmName;</span> |
| <span class="fc" id="L171"> this.iterations = Math.max(DEFAULT_ITERATIONS, hashIterations);</span> |
| <span class="fc" id="L172"> ByteSource saltBytes = null;</span> |
| <span class="fc bfc" id="L173" title="All 2 branches covered."> if (salt != null) {</span> |
| <span class="fc" id="L174"> saltBytes = convertSaltToBytes(salt);</span> |
| <span class="fc" id="L175"> this.salt = saltBytes;</span> |
| } |
| <span class="fc" id="L177"> ByteSource sourceBytes = convertSourceToBytes(source);</span> |
| <span class="fc" id="L178"> hash(sourceBytes, saltBytes, hashIterations);</span> |
| <span class="fc" id="L179"> }</span> |
| |
| /** |
| * Acquires the specified {@code source} argument's bytes and returns them in the form of a {@code ByteSource} instance. |
| * <p/> |
| * This implementation merely delegates to the convenience {@link #toByteSource(Object)} method for generic |
| * conversion. Can be overridden by subclasses for source-specific conversion. |
| * |
| * @param source the source object to be hashed. |
| * @return the source's bytes in the form of a {@code ByteSource} instance. |
| * @since 1.2 |
| */ |
| protected ByteSource convertSourceToBytes(Object source) { |
| <span class="fc" id="L192"> return toByteSource(source);</span> |
| } |
| |
| /** |
| * Acquires the specified {@code salt} argument's bytes and returns them in the form of a {@code ByteSource} instance. |
| * <p/> |
| * This implementation merely delegates to the convenience {@link #toByteSource(Object)} method for generic |
| * conversion. Can be overridden by subclasses for salt-specific conversion. |
| * |
| * @param salt the salt to be use for the hash. |
| * @return the salt's bytes in the form of a {@code ByteSource} instance. |
| * @since 1.2 |
| */ |
| protected ByteSource convertSaltToBytes(Object salt) { |
| <span class="fc" id="L206"> return toByteSource(salt);</span> |
| } |
| |
| /** |
| * Converts a given object into a {@code ByteSource} instance. Assumes the object can be converted to bytes. |
| * |
| * @param o the Object to convert into a {@code ByteSource} instance. |
| * @return the {@code ByteSource} representation of the specified object's bytes. |
| * @since 1.2 |
| */ |
| protected ByteSource toByteSource(Object o) { |
| <span class="pc bpc" id="L217" title="1 of 2 branches missed."> if (o == null) {</span> |
| <span class="nc" id="L218"> return null;</span> |
| } |
| <span class="fc bfc" id="L220" title="All 2 branches covered."> if (o instanceof ByteSource) {</span> |
| <span class="fc" id="L221"> return (ByteSource) o;</span> |
| } |
| <span class="fc" id="L223"> byte[] bytes = toBytes(o);</span> |
| <span class="fc" id="L224"> return ByteSource.Util.bytes(bytes);</span> |
| } |
| |
| private void hash(ByteSource source, ByteSource salt, int hashIterations) throws CodecException, UnknownAlgorithmException { |
| <span class="fc bfc" id="L228" title="All 2 branches covered."> byte[] saltBytes = salt != null ? salt.getBytes() : null;</span> |
| <span class="fc" id="L229"> byte[] hashedBytes = hash(source.getBytes(), saltBytes, hashIterations);</span> |
| <span class="fc" id="L230"> setBytes(hashedBytes);</span> |
| <span class="fc" id="L231"> }</span> |
| |
| /** |
| * Returns the {@link java.security.MessageDigest MessageDigest} algorithm name to use when performing the hash. |
| * |
| * @return the {@link java.security.MessageDigest MessageDigest} algorithm name to use when performing the hash. |
| */ |
| public String getAlgorithmName() { |
| <span class="fc" id="L239"> return this.algorithmName;</span> |
| } |
| |
| public ByteSource getSalt() { |
| <span class="fc" id="L243"> return this.salt;</span> |
| } |
| |
| public int getIterations() { |
| <span class="fc" id="L247"> return this.iterations;</span> |
| } |
| |
| public byte[] getBytes() { |
| <span class="fc" id="L251"> return this.bytes;</span> |
| } |
| |
| /** |
| * Sets the raw bytes stored by this hash instance. |
| * <p/> |
| * The bytes are kept in raw form - they will not be hashed/changed. This is primarily a utility method for |
| * constructing a Hash instance when the hashed value is already known. |
| * |
| * @param alreadyHashedBytes the raw already-hashed bytes to store in this instance. |
| */ |
| public void setBytes(byte[] alreadyHashedBytes) { |
| <span class="fc" id="L263"> this.bytes = alreadyHashedBytes;</span> |
| <span class="fc" id="L264"> this.hexEncoded = null;</span> |
| <span class="fc" id="L265"> this.base64Encoded = null;</span> |
| <span class="fc" id="L266"> }</span> |
| |
| /** |
| * Sets the iterations used to previously compute AN ALREADY GENERATED HASH. |
| * <p/> |
| * This is provided <em>ONLY</em> to reconstitute an already-created Hash instance. It should ONLY ever be |
| * invoked when re-constructing a hash instance from an already-hashed value. |
| * |
| * @param iterations the number of hash iterations used to previously create the hash/digest. |
| * @since 1.2 |
| */ |
| public void setIterations(int iterations) { |
| <span class="fc" id="L278"> this.iterations = Math.max(DEFAULT_ITERATIONS, iterations);</span> |
| <span class="fc" id="L279"> }</span> |
| |
| /** |
| * Sets the salt used to previously compute AN ALREADY GENERATED HASH. |
| * <p/> |
| * This is provided <em>ONLY</em> to reconstitute a Hash instance that has already been computed. It should ONLY |
| * ever be invoked when re-constructing a hash instance from an already-hashed value. |
| * |
| * @param salt the salt used to previously create the hash/digest. |
| * @since 1.2 |
| */ |
| public void setSalt(ByteSource salt) { |
| <span class="fc" id="L291"> this.salt = salt;</span> |
| <span class="fc" id="L292"> }</span> |
| |
| /** |
| * Returns the JDK MessageDigest instance to use for executing the hash. |
| * |
| * @param algorithmName the algorithm to use for the hash, provided by subclasses. |
| * @return the MessageDigest object for the specified {@code algorithm}. |
| * @throws UnknownAlgorithmException if the specified algorithm name is not available. |
| */ |
| protected MessageDigest getDigest(String algorithmName) throws UnknownAlgorithmException { |
| try { |
| <span class="fc" id="L303"> return MessageDigest.getInstance(algorithmName);</span> |
| <span class="nc" id="L304"> } catch (NoSuchAlgorithmException e) {</span> |
| <span class="nc" id="L305"> String msg = "No native '" + algorithmName + "' MessageDigest instance available on the current JVM.";</span> |
| <span class="nc" id="L306"> throw new UnknownAlgorithmException(msg, e);</span> |
| } |
| } |
| |
| /** |
| * Hashes the specified byte array without a salt for a single iteration. |
| * |
| * @param bytes the bytes to hash. |
| * @return the hashed bytes. |
| * @throws UnknownAlgorithmException if the configured {@link #getAlgorithmName() algorithmName} is not available. |
| */ |
| protected byte[] hash(byte[] bytes) throws UnknownAlgorithmException { |
| <span class="nc" id="L318"> return hash(bytes, null, DEFAULT_ITERATIONS);</span> |
| } |
| |
| /** |
| * Hashes the specified byte array using the given {@code salt} for a single iteration. |
| * |
| * @param bytes the bytes to hash |
| * @param salt the salt to use for the initial hash |
| * @return the hashed bytes |
| * @throws UnknownAlgorithmException if the configured {@link #getAlgorithmName() algorithmName} is not available. |
| */ |
| protected byte[] hash(byte[] bytes, byte[] salt) throws UnknownAlgorithmException { |
| <span class="nc" id="L330"> return hash(bytes, salt, DEFAULT_ITERATIONS);</span> |
| } |
| |
| /** |
| * Hashes the specified byte array using the given {@code salt} for the specified number of iterations. |
| * |
| * @param bytes the bytes to hash |
| * @param salt the salt to use for the initial hash |
| * @param hashIterations the number of times the the {@code bytes} will be hashed (for attack resiliency). |
| * @return the hashed bytes. |
| * @throws UnknownAlgorithmException if the {@link #getAlgorithmName() algorithmName} is not available. |
| */ |
| protected byte[] hash(byte[] bytes, byte[] salt, int hashIterations) throws UnknownAlgorithmException { |
| <span class="fc" id="L343"> MessageDigest digest = getDigest(getAlgorithmName());</span> |
| <span class="fc bfc" id="L344" title="All 2 branches covered."> if (salt != null) {</span> |
| <span class="fc" id="L345"> digest.reset();</span> |
| <span class="fc" id="L346"> digest.update(salt);</span> |
| } |
| <span class="fc" id="L348"> byte[] hashed = digest.digest(bytes);</span> |
| <span class="fc" id="L349"> int iterations = hashIterations - 1; //already hashed once above</span> |
| //iterate remaining number: |
| <span class="fc bfc" id="L351" title="All 2 branches covered."> for (int i = 0; i < iterations; i++) {</span> |
| <span class="fc" id="L352"> digest.reset();</span> |
| <span class="fc" id="L353"> hashed = digest.digest(hashed);</span> |
| } |
| <span class="fc" id="L355"> return hashed;</span> |
| } |
| |
| public boolean isEmpty() { |
| <span class="nc bnc" id="L359" title="All 4 branches missed."> return this.bytes == null || this.bytes.length == 0;</span> |
| } |
| |
| /** |
| * Returns a hex-encoded string of the underlying {@link #getBytes byte array}. |
| * <p/> |
| * This implementation caches the resulting hex string so multiple calls to this method remain efficient. |
| * However, calling {@link #setBytes setBytes} will null the cached value, forcing it to be recalculated the |
| * next time this method is called. |
| * |
| * @return a hex-encoded string of the underlying {@link #getBytes byte array}. |
| */ |
| public String toHex() { |
| <span class="fc bfc" id="L372" title="All 2 branches covered."> if (this.hexEncoded == null) {</span> |
| <span class="fc" id="L373"> this.hexEncoded = Hex.encodeToString(getBytes());</span> |
| } |
| <span class="fc" id="L375"> return this.hexEncoded;</span> |
| } |
| |
| /** |
| * Returns a Base64-encoded string of the underlying {@link #getBytes byte array}. |
| * <p/> |
| * This implementation caches the resulting Base64 string so multiple calls to this method remain efficient. |
| * However, calling {@link #setBytes setBytes} will null the cached value, forcing it to be recalculated the |
| * next time this method is called. |
| * |
| * @return a Base64-encoded string of the underlying {@link #getBytes byte array}. |
| */ |
| public String toBase64() { |
| <span class="fc bfc" id="L388" title="All 2 branches covered."> if (this.base64Encoded == null) {</span> |
| //cache result in case this method is called multiple times. |
| <span class="fc" id="L390"> this.base64Encoded = Base64.encodeToString(getBytes());</span> |
| } |
| <span class="fc" id="L392"> return this.base64Encoded;</span> |
| } |
| |
| /** |
| * Simple implementation that merely returns {@link #toHex() toHex()}. |
| * |
| * @return the {@link #toHex() toHex()} value. |
| */ |
| public String toString() { |
| <span class="nc" id="L401"> return toHex();</span> |
| } |
| |
| /** |
| * Returns {@code true} if the specified object is a Hash and its {@link #getBytes byte array} is identical to |
| * this Hash's byte array, {@code false} otherwise. |
| * |
| * @param o the object (Hash) to check for equality. |
| * @return {@code true} if the specified object is a Hash and its {@link #getBytes byte array} is identical to |
| * this Hash's byte array, {@code false} otherwise. |
| */ |
| public boolean equals(Object o) { |
| <span class="pc bpc" id="L413" title="1 of 2 branches missed."> if (o instanceof Hash) {</span> |
| <span class="fc" id="L414"> Hash other = (Hash) o;</span> |
| <span class="fc" id="L415"> return MessageDigest.isEqual(getBytes(), other.getBytes());</span> |
| } |
| <span class="nc" id="L417"> return false;</span> |
| } |
| |
| /** |
| * Simply returns toHex().hashCode(); |
| * |
| * @return toHex().hashCode() |
| */ |
| public int hashCode() { |
| <span class="nc bnc" id="L426" title="All 4 branches missed."> if (this.bytes == null || this.bytes.length == 0) {</span> |
| <span class="nc" id="L427"> return 0;</span> |
| } |
| <span class="nc" id="L429"> return Arrays.hashCode(this.bytes);</span> |
| } |
| } |
| </pre><div class="footer"><span class="right">Created with <a href="http://www.eclemma.org/jacoco">JaCoCo</a> 0.7.7.201606060606</span></div></body></html> |