2 * Copyright (c) 2010-2020 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
14 package org.openhab.binding.miio.internal.cloud;
16 import java.security.InvalidKeyException;
17 import java.security.MessageDigest;
18 import java.security.NoSuchAlgorithmException;
19 import java.util.Base64;
21 import javax.crypto.Mac;
22 import javax.crypto.spec.SecretKeySpec;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.openhab.binding.miio.internal.MiIoCryptoException;
28 * The {@link CloudCrypto} is responsible for encryption for Xiaomi cloud communication.
30 * @author Marcel Verpaalen - Initial contribution
33 public class CloudCrypto {
36 * Compute SHA256 hash value for the byte array
38 * @param inBytes ByteArray to be hashed
39 * @return BASE64 encoded hash value
40 * @throws MiIoCryptoException
42 public static String sha256Hash(byte[] inBytes) throws MiIoCryptoException {
44 MessageDigest md = MessageDigest.getInstance("SHA-256");
45 return Base64.getEncoder().encodeToString(md.digest(inBytes));
46 } catch (NoSuchAlgorithmException e) {
47 throw new MiIoCryptoException(e.getMessage(), e);
52 * Compute HmacSHA256 hash value for the byte array
54 * @param key for encoding
55 * @param cipherText ByteArray to be encoded
56 * @return BASE64 encoded hash value
57 * @throws MiIoCryptoException
59 public static String hMacSha256Encode(byte[] key, byte[] cipherText) throws MiIoCryptoException {
61 Mac sha256Hmac = Mac.getInstance("HmacSHA256");
62 SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA256");
63 sha256Hmac.init(secretKey);
64 return Base64.getEncoder().encodeToString(sha256Hmac.doFinal(cipherText));
65 } catch (NoSuchAlgorithmException | InvalidKeyException e) {
66 throw new MiIoCryptoException(e.getMessage(), e);