1/*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.hash;
18
19import com.google.common.base.Charsets;
20import com.google.common.collect.ImmutableMap;
21import com.google.common.collect.ImmutableSet;
22import com.google.common.jdk5backport.Arrays;
23
24import junit.framework.TestCase;
25
26import java.security.MessageDigest;
27import java.security.NoSuchAlgorithmException;
28/**
29 * Tests for the MessageDigestHashFunction.
30 *
31 * @author Kurt Alfred Kluever
32 */
33public class MessageDigestHashFunctionTest extends TestCase {
34  private static final ImmutableSet<String> INPUTS = ImmutableSet.of("", "Z", "foobar");
35
36  // From "How Provider Implementations Are Requested and Supplied" from
37  // http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
38  //  - Some providers may choose to also include alias names.
39  //  - For example, the "SHA-1" algorithm might be referred to as "SHA1".
40  //  - The algorithm name is not case-sensitive.
41  private static final ImmutableMap<String, HashFunction> ALGORITHMS =
42      new ImmutableMap.Builder<String, HashFunction>()
43          .put("MD5", Hashing.md5())
44          .put("SHA", Hashing.sha1()) // Not the official name, but still works
45          .put("SHA1", Hashing.sha1()) // Not the official name, but still works
46          .put("sHa-1", Hashing.sha1()) // Not the official name, but still works
47          .put("SHA-1", Hashing.sha1())
48          .put("SHA-256", Hashing.sha256())
49          .put("SHA-512", Hashing.sha512())
50          .build();
51
52  public void testHashing() {
53    for (String stringToTest : INPUTS) {
54      for (String algorithmToTest : ALGORITHMS.keySet()) {
55        assertMessageDigestHashing(HashTestUtils.ascii(stringToTest), algorithmToTest);
56      }
57    }
58  }
59
60  public void testPutAfterHash() {
61    Hasher sha1 = Hashing.sha1().newHasher();
62
63    assertEquals("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
64        sha1.putString("The quick brown fox jumps over the lazy dog", Charsets.UTF_8)
65            .hash()
66            .toString());
67    try {
68      sha1.putInt(42);
69      fail();
70    } catch (IllegalStateException expected) {
71    }
72  }
73
74  public void testHashTwice() {
75    Hasher sha1 = Hashing.sha1().newHasher();
76
77    assertEquals("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
78        sha1.putString("The quick brown fox jumps over the lazy dog", Charsets.UTF_8)
79            .hash()
80            .toString());
81    try {
82      sha1.hash();
83      fail();
84    } catch (IllegalStateException expected) {
85    }
86  }
87
88  public void testToString() {
89    assertEquals("Hashing.md5()", Hashing.md5().toString());
90    assertEquals("Hashing.sha1()", Hashing.sha1().toString());
91    assertEquals("Hashing.sha256()", Hashing.sha256().toString());
92    assertEquals("Hashing.sha512()", Hashing.sha512().toString());
93  }
94
95  private static void assertMessageDigestHashing(byte[] input, String algorithmName) {
96    try {
97      MessageDigest digest = MessageDigest.getInstance(algorithmName);
98      assertEquals(
99          HashCode.fromBytes(digest.digest(input)),
100          ALGORITHMS.get(algorithmName).hashBytes(input));
101      for (int bytes = 4; bytes <= digest.getDigestLength(); bytes++) {
102        assertEquals(
103            HashCode.fromBytes(Arrays.copyOf(digest.digest(input), bytes)),
104            new MessageDigestHashFunction(algorithmName, bytes, algorithmName).hashBytes(input));
105      }
106      try {
107        int maxSize = digest.getDigestLength();
108        new MessageDigestHashFunction(algorithmName, maxSize + 1, algorithmName);
109        fail();
110      } catch (IllegalArgumentException expected) {
111      }
112    } catch (NoSuchAlgorithmException nsae) {
113      throw new AssertionError(nsae);
114    }
115  }
116}
117