package com.hdl.sdk.link.core.utils; import com.hdl.sdk.link.common.config.TopicConstant; import com.hdl.sdk.link.common.utils.ByteUtils; import com.hdl.sdk.link.core.bean.LinkRequest; import com.hdl.sdk.link.core.config.HDLLinkConfig; /** * Created by hxb on 2021/12/23. */ public class EncryptUtil { /** * 获取加密数据 * * @param linkRequest 请求数据 * @return */ public static byte[] getEncryBytes(LinkRequest linkRequest) { try { //判断是否需要加密 if (ifNeedEncrypt(linkRequest.getTopic(), linkRequest.isEncrypt())) { //需要加密 byte[] dataBytes = AesUtil.aesEncrypt(linkRequest.getData(), HDLLinkConfig.getInstance().getLocalSecret()); String headString = "Topic:" + linkRequest.getTopic() + "\r\n" + "Length:" + dataBytes.length + "\r\n" + "\r\n"; byte[] headBytes = headString.getBytes("utf-8"); byte[] sendBytes = ByteUtils.concatBytes(headBytes, dataBytes); return sendBytes; } else { return linkRequest.getSendBytes(); } } catch (Exception e) { return new byte[]{}; } } /** * 判断当前主题数据是否需要加密 * * @param topicStr 当前主题 * @return */ public static boolean ifNeedEncrypt(String topicStr, boolean isLocalEncrypt) { //过滤相关需要加密的主题 return (!topicStr.contains(TopicConstant.GATEWAY_AUTH_BROADCAST) //网关广播入网指令 && !topicStr.contains(TopicConstant.DEIVCE_AUTH_REQUEST) //入网认证 && !topicStr.contains(TopicConstant.GATEWAY_SEARCH) //搜索网关主题 && !topicStr.contains(TopicConstant.GATEWAY_SEARCH_REPLY) //搜索网关主题回复 && !topicStr.equals(TopicConstant.BROADCAST) && isLocalEncrypt//启用加密标志 ); } }