View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  package org.opencastproject.urlsigning.utils;
22  
23  import org.apache.commons.codec.binary.Hex;
24  
25  import java.io.UnsupportedEncodingException;
26  import java.nio.charset.StandardCharsets;
27  import java.security.InvalidKeyException;
28  import java.security.NoSuchAlgorithmException;
29  
30  import javax.crypto.Mac;
31  import javax.crypto.spec.SecretKeySpec;
32  
33  /**
34   * A utility class to hash plain text with the SHA-256 algorithm.
35   */
36  public final class SHA256Util {
37    /** The algorithm to use to encode the HMAC. */
38    private static final String ALGORITHM = "HmacSHA256";
39  
40    private SHA256Util() {
41    }
42  
43    /**
44     * Create a SHA 256 digest string from a string and a secret key.
45     *
46     * @param plainText
47     *          The plaintext string to hash.
48     * @param secretKey
49     *          The key to use to create the hash.
50     * @return Returns a hash of the plain text hashed with the secret key.
51     * @throws NoSuchAlgorithmException
52     *           Thrown if the algorithm is not supported on this platform.
53     * @throws InvalidKeyException
54     *           Thrown if the secret key is invalid.
55     * @throws UnsupportedEncodingException
56     *           Thrown if unable to convert bytes into a hex string.
57     */
58    public static String digest(String plainText, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException,
59            UnsupportedEncodingException {
60      SecretKeySpec key = new SecretKeySpec((secretKey).getBytes(StandardCharsets.UTF_8), ALGORITHM);
61      Mac mac = Mac.getInstance(ALGORITHM);
62      mac.init(key);
63      byte[] bytes = mac.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
64  
65      // Convert raw bytes to Hex
66      byte[] hexBytes = new Hex().encode(bytes);
67  
68      // Covert array of Hex bytes to a String
69      return new String(hexBytes, "UTF-8");
70    }
71  }