]> git.basschouten.com Git - openhab-addons.git/blob
769747b45997d5a35f818b967fc706a2ca6b11fe
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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
14 package org.openhab.binding.miio.internal.cloud;
15
16 import java.security.InvalidKeyException;
17 import java.security.MessageDigest;
18 import java.security.NoSuchAlgorithmException;
19 import java.util.Base64;
20
21 import javax.crypto.Mac;
22 import javax.crypto.spec.SecretKeySpec;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.openhab.binding.miio.internal.MiIoCryptoException;
26
27 /**
28  * The {@link CloudCrypto} is responsible for encryption for Xiaomi cloud communication.
29  *
30  * @author Marcel Verpaalen - Initial contribution
31  */
32 @NonNullByDefault
33 public class CloudCrypto {
34
35     /**
36      * Compute SHA256 hash value for the byte array
37      *
38      * @param inBytes ByteArray to be hashed
39      * @return BASE64 encoded hash value
40      * @throws MiIoCryptoException
41      */
42     public static String sha256Hash(byte[] inBytes) throws MiIoCryptoException {
43         try {
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);
48         }
49     }
50
51     /**
52      * Compute HmacSHA256 hash value for the byte array
53      *
54      * @param key for encoding
55      * @param cipherText ByteArray to be encoded
56      * @return BASE64 encoded hash value
57      * @throws MiIoCryptoException
58      */
59     public static String hMacSha256Encode(byte[] key, byte[] cipherText) throws MiIoCryptoException {
60         try {
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);
67         }
68     }
69 }