]> git.basschouten.com Git - openhab-addons.git/blob
52d7b2a78967b4308af34095d243c37bd257a11a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.opensprinkler.internal.util;
14
15 import java.security.MessageDigest;
16
17 /**
18  * The {@link Hash} class contains static methods for creating hashes
19  * of strings. Usually for password hashing.
20  *
21  * @author Chris Graham - Initial contribution
22  */
23 public class Hash {
24     private static final String MD5_HASH_ALGORITHM = "MD5";
25     private static final String UTF8_CHAR_SET = "UTF-8";
26
27     /**
28      * Given a string, return the MD5 hash of the String.
29      *
30      * @param unhashed The string contents to be hashed.
31      * @return MD5 Hashed value of the String. Null if there is a problem hashing the String.
32      */
33     public static String getMD5Hash(String unhashed) {
34         try {
35             byte[] bytesOfMessage = unhashed.getBytes(UTF8_CHAR_SET);
36
37             MessageDigest md5 = MessageDigest.getInstance(MD5_HASH_ALGORITHM);
38
39             byte[] hash = md5.digest(bytesOfMessage);
40
41             StringBuilder sb = new StringBuilder(2 * hash.length);
42
43             for (byte b : hash) {
44                 sb.append(String.format("%02x", b & 0xff));
45             }
46
47             String digest = sb.toString();
48
49             return digest;
50         } catch (Exception exp) {
51             return null;
52         }
53     }
54 }