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.gree.internal;
15 import java.nio.charset.StandardCharsets;
16 import java.security.InvalidKeyException;
17 import java.security.Key;
18 import java.security.NoSuchAlgorithmException;
19 import java.util.Base64;
21 import javax.crypto.BadPaddingException;
22 import javax.crypto.Cipher;
23 import javax.crypto.IllegalBlockSizeException;
24 import javax.crypto.NoSuchPaddingException;
25 import javax.crypto.spec.SecretKeySpec;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
30 * The CryptoUtil class provides functionality for encrypting and decrypting
31 * messages sent to and from the Air Conditioner
33 * @author John Cunha - Initial contribution
34 * @author Markus Michels - Refactoring, adapted to OH 2.5x
37 public class GreeCryptoUtil {
38 private static final String AES_KEY = "a3K8Bx%2r8Y7#xDh";
40 public static byte[] getAESGeneralKeyByteArray() {
41 return AES_KEY.getBytes(StandardCharsets.UTF_8);
44 public static String decryptPack(byte[] keyarray, String message) throws GreeException {
46 Key key = new SecretKeySpec(keyarray, "AES");
47 Base64.Decoder decoder = Base64.getDecoder();
48 byte[] imageByte = decoder.decode(message);
50 Cipher aesCipher = Cipher.getInstance("AES");
51 aesCipher.init(Cipher.DECRYPT_MODE, key);
52 byte[] bytePlainText = aesCipher.doFinal(imageByte);
54 return new String(bytePlainText, StandardCharsets.UTF_8);
55 } catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | InvalidKeyException
56 | IllegalBlockSizeException ex) {
57 throw new GreeException("Decryption of recieved data failed", ex);
61 public static String encryptPack(byte[] keyarray, String message) throws GreeException {
63 Key key = new SecretKeySpec(keyarray, "AES");
64 Cipher aesCipher = Cipher.getInstance("AES");
65 aesCipher.init(Cipher.ENCRYPT_MODE, key);
66 byte[] bytePlainText = aesCipher.doFinal(message.getBytes());
68 Base64.Encoder newencoder = Base64.getEncoder();
69 return new String(newencoder.encode(bytePlainText), StandardCharsets.UTF_8);
70 } catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | InvalidKeyException
71 | IllegalBlockSizeException ex) {
72 throw new GreeException("Unable to encrypt outbound data", ex);