]> git.basschouten.com Git - openhab-addons.git/blob
f88a7ec0ae05b29ebc13a3773a90fd85c01444c6
[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.mqtt.internal.ssl;
14
15 import java.security.MessageDigest;
16 import java.security.NoSuchAlgorithmException;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.openhab.core.util.HexUtils;
20
21 /**
22  * Encapsulates a {@link MessageDigest} with a specific Hash method. Extracts the digest data of
23  * a certificate.
24  *
25  * @author David Graeff - Initial contribution
26  */
27 @NonNullByDefault
28 public class PinMessageDigest {
29     protected final MessageDigest messageDigest;
30     private final String method;
31
32     /**
33      * Creates a message digest for a certificate/public key pinning.
34      *
35      * @param method The hash method to use
36      * @throws NoSuchAlgorithmException
37      */
38     public PinMessageDigest(String method) throws NoSuchAlgorithmException {
39         this.method = method;
40         this.messageDigest = MessageDigest.getInstance(method);
41     }
42
43     /**
44      * Outputs a string like "SHA-256:83F9171E06A313118889F7D79302BD1B7A2042EE0CFD029ABF8DD06FFA6CD9D3"
45      *
46      * @param digestData Digest data
47      */
48     public String toHexString(byte[] digestData) {
49         return getMethod() + ":" + HexUtils.bytesToHex(digestData);
50     }
51
52     byte[] digest(byte[] origData) {
53         synchronized (messageDigest) {
54             return messageDigest.digest(origData);
55         }
56     }
57
58     /**
59      * @return Return the digest method for instance SHA-256
60      */
61     public String getMethod() {
62         return method;
63     }
64 }