2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.miio.internal.cloud;
15 import java.security.InvalidKeyException;
16 import java.security.MessageDigest;
17 import java.security.NoSuchAlgorithmException;
18 import java.util.Base64;
20 import javax.crypto.Mac;
21 import javax.crypto.spec.SecretKeySpec;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.openhab.binding.miio.internal.MiIoCryptoException;
27 * The {@link CloudCrypto} is responsible for encryption for Xiaomi cloud communication.
29 * @author Marcel Verpaalen - Initial contribution
32 public class CloudCrypto {
35 * Compute SHA256 hash value for the byte array
37 * @param inBytes ByteArray to be hashed
38 * @return BASE64 encoded hash value
39 * @throws MiIoCryptoException
41 public static String sha256Hash(byte[] inBytes) throws MiIoCryptoException {
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);
51 * Compute HmacSHA256 hash value for the byte array
53 * @param key for encoding
54 * @param cipherText ByteArray to be encoded
55 * @return BASE64 encoded hash value
56 * @throws MiIoCryptoException
58 public static String hMacSha256Encode(byte[] key, byte[] cipherText) throws MiIoCryptoException {
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);