blob: d2e5ce8381f54d356674d58b7354e79b94b1d5d7 [file] [log] [blame]
<?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>AbstractHash.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 :: Jar Bundle</a> &gt; <a href="../index.html" class="el_bundle">shiro-core</a> &gt; <a href="index.source.html" class="el_package">org.apache.shiro.crypto.hash</a> &gt; <span class="el_source">AbstractHash.java</span></div><h1>AbstractHash.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
* &quot;License&quot;); 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
* &quot;AS IS&quot; 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.CodecSupport;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.UnknownAlgorithmException;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
* Provides a base for all Shiro Hash algorithms with support for salts and multiple hash iterations.
* &lt;p/&gt;
* Read
* &lt;a href=&quot;http://www.owasp.org/index.php/Hashing_Java&quot; target=&quot;blank&quot;&gt;http://www.owasp.org/index.php/Hashing_Java&lt;/a&gt;
* for a good article on the benefits of hashing, including what a 'salt' is as well as why it and multiple hash
* iterations can be useful.
* &lt;p/&gt;
* This class and its subclasses support hashing with additional capabilities of salting and multiple iterations via
* overloaded constructors.
*
* @since 0.9
* @deprecated in Shiro 1.1 in favor of using the concrete {@link SimpleHash} implementation directly.
*/
@Deprecated
public abstract class AbstractHash extends CodecSupport implements Hash, Serializable {
/**
* The hashed data
*/
<span class="pc" id="L52"> private byte[] bytes = null;</span>
/**
* Cached value of the {@link #toHex() toHex()} call so multiple calls won't incur repeated overhead.
*/
<span class="pc" id="L57"> private transient String hexEncoded = null;</span>
/**
* Cached value of the {@link #toBase64() toBase64()} call so multiple calls won't incur repeated overhead.
*/
<span class="pc" id="L61"> private transient String base64Encoded = null;</span>
/**
* Creates an new instance without any of its properties set (no hashing is performed).
* &lt;p/&gt;
* Because all constructors in this class (except this one) hash the {@code source} constructor argument, this
* default, no-arg 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 instantiating the instance with
* this default, no-arg constructor, you can then immediately call {@link #setBytes setBytes} to have a
* fully-initialized instance.
*/
<span class="fc" id="L72"> public AbstractHash() {</span>
<span class="fc" id="L73"> }</span>
/**
* Creates a hash of the specified {@code source} with no {@code salt} using a single hash iteration.
* &lt;p/&gt;
* It is a convenience constructor that merely executes &lt;code&gt;this( source, null, 1);&lt;/code&gt;.
* &lt;p/&gt;
* Please see the
* {@link #AbstractHash(Object source, Object salt, int numIterations) AbstractHash(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 source the object to be hashed.
* @throws CodecException if the specified {@code source} cannot be converted into a byte array (byte[]).
*/
public AbstractHash(Object source) throws CodecException {
<span class="nc" id="L89"> this(source, null, 1);</span>
<span class="nc" id="L90"> }</span>
/**
* Creates a hash of the specified {@code source} using the given {@code salt} using a single hash iteration.
* &lt;p/&gt;
* It is a convenience constructor that merely executes &lt;code&gt;this( source, salt, 1);&lt;/code&gt;.
* &lt;p/&gt;
* Please see the
* {@link #AbstractHash(Object source, Object salt, int numIterations) AbstractHash(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 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.
*/
public AbstractHash(Object source, Object salt) throws CodecException {
<span class="nc" id="L107"> this(source, salt, 1);</span>
<span class="nc" id="L108"> }</span>
/**
* Creates a hash of the specified {@code source} using the given {@code salt} a total of
* {@code hashIterations} times.
* &lt;p/&gt;
* By default, this class only supports Object method arguments of
* type {@code byte[]}, {@code char[]}, {@link String}, {@link java.io.File File}, or
* {@link java.io.InputStream InputStream}. If either argument is anything other than these
* types a {@link org.apache.shiro.codec.CodecException CodecException} will be thrown.
* &lt;p/&gt;
* 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 three supported types first before passing them in to this
* constructor}.
*
* @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.
*/
<span class="nc" id="L129"> public AbstractHash(Object source, Object salt, int hashIterations) throws CodecException {</span>
<span class="nc" id="L130"> byte[] sourceBytes = toBytes(source);</span>
<span class="nc" id="L131"> byte[] saltBytes = null;</span>
<span class="nc bnc" id="L132" title="All 2 branches missed."> if (salt != null) {</span>
<span class="nc" id="L133"> saltBytes = toBytes(salt);</span>
}
<span class="nc" id="L135"> byte[] hashedBytes = hash(sourceBytes, saltBytes, hashIterations);</span>
<span class="nc" id="L136"> setBytes(hashedBytes);</span>
<span class="nc" id="L137"> }</span>
/**
* Implemented by subclasses, this specifies the {@link MessageDigest MessageDigest} algorithm name
* to use when performing the hash.
*
* @return the {@link MessageDigest MessageDigest} algorithm name to use when performing the hash.
*/
public abstract String getAlgorithmName();
public byte[] getBytes() {
<span class="nc" id="L148"> return this.bytes;</span>
}
/**
* Sets the raw bytes stored by this hash instance.
* &lt;p/&gt;
* 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="nc" id="L160"> this.bytes = alreadyHashedBytes;</span>
<span class="nc" id="L161"> this.hexEncoded = null;</span>
<span class="nc" id="L162"> this.base64Encoded = null;</span>
<span class="nc" id="L163"> }</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="nc" id="L174"> return MessageDigest.getInstance(algorithmName);</span>
<span class="nc" id="L175"> } catch (NoSuchAlgorithmException e) {</span>
<span class="nc" id="L176"> String msg = &quot;No native '&quot; + algorithmName + &quot;' MessageDigest instance available on the current JVM.&quot;;</span>
<span class="nc" id="L177"> 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.
*/
protected byte[] hash(byte[] bytes) {
<span class="nc" id="L188"> return hash(bytes, null, 1);</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
*/
protected byte[] hash(byte[] bytes, byte[] salt) {
<span class="nc" id="L199"> return hash(bytes, salt, 1);</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="nc" id="L212"> MessageDigest digest = getDigest(getAlgorithmName());</span>
<span class="nc bnc" id="L213" title="All 2 branches missed."> if (salt != null) {</span>
<span class="nc" id="L214"> digest.reset();</span>
<span class="nc" id="L215"> digest.update(salt);</span>
}
<span class="nc" id="L217"> byte[] hashed = digest.digest(bytes);</span>
<span class="nc" id="L218"> int iterations = hashIterations - 1; //already hashed once above</span>
//iterate remaining number:
<span class="nc bnc" id="L220" title="All 2 branches missed."> for (int i = 0; i &lt; iterations; i++) {</span>
<span class="nc" id="L221"> digest.reset();</span>
<span class="nc" id="L222"> hashed = digest.digest(hashed);</span>
}
<span class="nc" id="L224"> return hashed;</span>
}
/**
* Returns a hex-encoded string of the underlying {@link #getBytes byte array}.
* &lt;p/&gt;
* 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="nc bnc" id="L237" title="All 2 branches missed."> if (this.hexEncoded == null) {</span>
<span class="nc" id="L238"> this.hexEncoded = Hex.encodeToString(getBytes());</span>
}
<span class="nc" id="L240"> return this.hexEncoded;</span>
}
/**
* Returns a Base64-encoded string of the underlying {@link #getBytes byte array}.
* &lt;p/&gt;
* 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="nc bnc" id="L253" title="All 2 branches missed."> if (this.base64Encoded == null) {</span>
//cache result in case this method is called multiple times.
<span class="nc" id="L255"> this.base64Encoded = Base64.encodeToString(getBytes());</span>
}
<span class="nc" id="L257"> 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="L266"> 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="nc bnc" id="L278" title="All 2 branches missed."> if (o instanceof Hash) {</span>
<span class="nc" id="L279"> Hash other = (Hash) o;</span>
<span class="nc" id="L280"> return MessageDigest.isEqual(getBytes(), other.getBytes());</span>
}
<span class="nc" id="L282"> return false;</span>
}
/**
* Simply returns toHex().hashCode();
*
* @return toHex().hashCode()
*/
public int hashCode() {
<span class="nc bnc" id="L291" title="All 4 branches missed."> if (this.bytes == null || this.bytes.length == 0) {</span>
<span class="nc" id="L292"> return 0;</span>
}
<span class="nc" id="L294"> return Arrays.hashCode(this.bytes);</span>
}
private static void printMainUsage(Class&lt;? extends AbstractHash&gt; clazz, String type) {
<span class="nc" id="L298"> System.out.println(&quot;Prints an &quot; + type + &quot; hash value.&quot;);</span>
<span class="nc" id="L299"> System.out.println(&quot;Usage: java &quot; + clazz.getName() + &quot; [-base64] [-salt &lt;saltValue&gt;] [-times &lt;N&gt;] &lt;valueToHash&gt;&quot;);</span>
<span class="nc" id="L300"> System.out.println(&quot;Options:&quot;);</span>
<span class="nc" id="L301"> System.out.println(&quot;\t-base64\t\tPrints the hash value as a base64 String instead of the default hex.&quot;);</span>
<span class="nc" id="L302"> System.out.println(&quot;\t-salt\t\tSalts the hash with the specified &lt;saltValue&gt;&quot;);</span>
<span class="nc" id="L303"> System.out.println(&quot;\t-times\t\tHashes the input &lt;N&gt; number of times&quot;);</span>
<span class="nc" id="L304"> }</span>
private static boolean isReserved(String arg) {
<span class="nc bnc" id="L307" title="All 6 branches missed."> return &quot;-base64&quot;.equals(arg) || &quot;-times&quot;.equals(arg) || &quot;-salt&quot;.equals(arg);</span>
}
static int doMain(Class&lt;? extends AbstractHash&gt; clazz, String[] args) {
<span class="nc" id="L311"> String simple = clazz.getSimpleName();</span>
<span class="nc" id="L312"> int index = simple.indexOf(&quot;Hash&quot;);</span>
<span class="nc" id="L313"> String type = simple.substring(0, index).toUpperCase();</span>
<span class="nc bnc" id="L315" title="All 6 branches missed."> if (args == null || args.length &lt; 1 || args.length &gt; 7) {</span>
<span class="nc" id="L316"> printMainUsage(clazz, type);</span>
<span class="nc" id="L317"> return -1;</span>
}
<span class="nc" id="L319"> boolean hex = true;</span>
<span class="nc" id="L320"> String salt = null;</span>
<span class="nc" id="L321"> int times = 1;</span>
<span class="nc" id="L322"> String text = args[args.length - 1];</span>
<span class="nc bnc" id="L323" title="All 2 branches missed."> for (int i = 0; i &lt; args.length; i++) {</span>
<span class="nc" id="L324"> String arg = args[i];</span>
<span class="nc bnc" id="L325" title="All 2 branches missed."> if (arg.equals(&quot;-base64&quot;)) {</span>
<span class="nc" id="L326"> hex = false;</span>
<span class="nc bnc" id="L327" title="All 2 branches missed."> } else if (arg.equals(&quot;-salt&quot;)) {</span>
<span class="nc bnc" id="L328" title="All 2 branches missed."> if ((i + 1) &gt;= (args.length - 1)) {</span>
<span class="nc" id="L329"> String msg = &quot;Salt argument must be followed by a salt value. The final argument is &quot; +</span>
&quot;reserved for the value to hash.&quot;;
<span class="nc" id="L331"> System.out.println(msg);</span>
<span class="nc" id="L332"> printMainUsage(clazz, type);</span>
<span class="nc" id="L333"> return -1;</span>
}
<span class="nc" id="L335"> salt = args[i + 1];</span>
<span class="nc bnc" id="L336" title="All 2 branches missed."> } else if (arg.equals(&quot;-times&quot;)) {</span>
<span class="nc bnc" id="L337" title="All 2 branches missed."> if ((i + 1) &gt;= (args.length - 1)) {</span>
<span class="nc" id="L338"> String msg = &quot;Times argument must be followed by an integer value. The final argument is &quot; +</span>
&quot;reserved for the value to hash&quot;;
<span class="nc" id="L340"> System.out.println(msg);</span>
<span class="nc" id="L341"> printMainUsage(clazz, type);</span>
<span class="nc" id="L342"> return -1;</span>
}
try {
<span class="nc" id="L345"> times = Integer.valueOf(args[i + 1]);</span>
<span class="nc" id="L346"> } catch (NumberFormatException e) {</span>
<span class="nc" id="L347"> String msg = &quot;Times argument must be followed by an integer value.&quot;;</span>
<span class="nc" id="L348"> System.out.println(msg);</span>
<span class="nc" id="L349"> printMainUsage(clazz, type);</span>
<span class="nc" id="L350"> return -1;</span>
<span class="nc" id="L351"> }</span>
}
}
<span class="nc" id="L355"> Hash hash = new Md2Hash(text, salt, times);</span>
<span class="nc bnc" id="L356" title="All 2 branches missed."> String hashed = hex ? hash.toHex() : hash.toBase64();</span>
<span class="nc bnc" id="L357" title="All 2 branches missed."> System.out.print(hex ? &quot;Hex: &quot; : &quot;Base64: &quot;);</span>
<span class="nc" id="L358"> System.out.println(hashed);</span>
<span class="nc" id="L359"> return 0;</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>