]> git.basschouten.com Git - openhab-addons.git/blob
297f9b18b0086bbf72524974e6b84c252edafc62
[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.miio.internal.cloud;
14
15 import java.security.InvalidKeyException;
16 import java.security.MessageDigest;
17 import java.security.NoSuchAlgorithmException;
18 import java.util.Base64;
19
20 import javax.crypto.Mac;
21 import javax.crypto.spec.SecretKeySpec;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.openhab.binding.miio.internal.MiIoCryptoException;
25
26 /**
27  * The {@link CloudCrypto} is responsible for encryption for Xiaomi cloud communication.
28  *
29  * @author Marcel Verpaalen - Initial contribution
30  */
31 @NonNullByDefault
32 public class CloudCrypto {
33
34     /**
35      * Compute SHA256 hash value for the byte array
36      *
37      * @param inBytes ByteArray to be hashed
38      * @return BASE64 encoded hash value
39      * @throws MiIoCryptoException
40      */
41     public static String sha256Hash(byte[] inBytes) throws MiIoCryptoException {
42         try {
43             MessageDigest md = MessageDigest.getInstance("SHA-256");
44             return Base64.getEncoder().encodeToString(md.digest(inBytes));
45         } catch (NoSuchAlgorithmException e) {
46             throw new MiIoCryptoException(e.getMessage(), e);
47         }
48     }
49
50     /**
51      * Compute HmacSHA256 hash value for the byte array
52      *
53      * @param key for encoding
54      * @param cipherText ByteArray to be encoded
55      * @return BASE64 encoded hash value
56      * @throws MiIoCryptoException
57      */
58     public static String hMacSha256Encode(byte[] key, byte[] cipherText) throws MiIoCryptoException {
59         try {
60             Mac sha256Hmac = Mac.getInstance("HmacSHA256");
61             SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA256");
62             sha256Hmac.init(secretKey);
63             return Base64.getEncoder().encodeToString(sha256Hmac.doFinal(cipherText));
64         } catch (NoSuchAlgorithmException | InvalidKeyException e) {
65             throw new MiIoCryptoException(e.getMessage(), e);
66         }
67     }
68 }