]> git.basschouten.com Git - openhab-addons.git/blob
7907b868568eeb8dbcd8d22300356c59ad7b727e
[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.haassohnpelletstove.internal;
14
15 import java.nio.charset.Charset;
16 import java.nio.charset.StandardCharsets;
17 import java.security.MessageDigest;
18 import java.security.NoSuchAlgorithmException;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22
23 /**
24  * The {@link MD5Utils} is responsible for generating the MD5 hash
25  *
26  *
27  * @author Christian Feininger - Initial contribution
28  */
29 @NonNullByDefault
30 public class MD5Utils {
31
32     private static final Charset UTF_8 = StandardCharsets.UTF_8;
33
34     private static byte[] digest(byte[] input) {
35         MessageDigest md;
36         try {
37             md = MessageDigest.getInstance("MD5");
38         } catch (NoSuchAlgorithmException e) {
39             throw new IllegalArgumentException(e);
40         }
41         byte[] result = md.digest(input);
42         return result;
43     }
44
45     private static String bytesToHex(byte[] bytes) {
46         StringBuilder sb = new StringBuilder();
47         for (byte b : bytes) {
48             sb.append(String.format("%02x", b));
49         }
50         return sb.toString();
51     }
52
53     /***
54      * Returns an encrypted MD5 string
55      *
56      * @param input nonce as input
57      * @return Encrypted String
58      */
59     public static String getMD5String(@Nullable String input) {
60         if (input != null) {
61             byte[] md5InBytes = MD5Utils.digest(input.getBytes(UTF_8));
62             return bytesToHex(md5InBytes);
63         }
64         return "";
65     }
66 }