]> git.basschouten.com Git - openhab-addons.git/blob
a614441a614bd8c58a4eb30d863786f85b4952d5
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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 import org.eclipse.jdt.annotation.NonNullByDefault;
18
19 /**
20  * The {@link Hash} class contains static methods for creating hashes
21  * of strings. Usually for password hashing.
22  *
23  * @author Chris Graham - Initial contribution
24  */
25 @NonNullByDefault
26 public class Hash {
27     private static final String MD5_HASH_ALGORITHM = "MD5";
28     private static final String UTF8_CHAR_SET = "UTF-8";
29
30     /**
31      * Given a string, return the MD5 hash of the String.
32      *
33      * @param unhashed The string contents to be hashed.
34      * @return MD5 Hashed value of the String. Null if there is a problem hashing the String.
35      */
36     public static String getMD5Hash(String unhashed) {
37         try {
38             byte[] bytesOfMessage = unhashed.getBytes(UTF8_CHAR_SET);
39
40             MessageDigest md5 = MessageDigest.getInstance(MD5_HASH_ALGORITHM);
41
42             byte[] hash = md5.digest(bytesOfMessage);
43
44             StringBuilder sb = new StringBuilder(2 * hash.length);
45
46             for (byte b : hash) {
47                 sb.append(String.format("%02x", b & 0xff));
48             }
49
50             String digest = sb.toString();
51
52             return digest;
53         } catch (Exception exp) {
54             // Instead of null we return the unhashed password.
55             return unhashed;
56         }
57     }
58 }