package com.hdl.sdk.link.core.utils;
|
|
import android.text.TextUtils;
|
|
import com.hdl.sdk.link.common.config.TopicConstant;
|
import com.hdl.sdk.link.common.utils.ByteUtils;
|
|
import com.hdl.sdk.link.common.utils.LogUtils;
|
import com.hdl.sdk.link.core.bean.LinkRequest;
|
import com.hdl.sdk.link.core.config.HDLLinkConfig;
|
|
import java.io.UnsupportedEncodingException;
|
|
/**
|
* Created by hxb on 2021/12/23.
|
*/
|
public class EncryptUtil {
|
/**
|
* 获取加密数据
|
*
|
* @param linkRequest 请求数据
|
* @return
|
*/
|
public static byte[] getEncryBytes(LinkRequest linkRequest) throws UnsupportedEncodingException {
|
//判断是否需要加密
|
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();
|
}
|
}
|
|
/**
|
* 加密数据
|
*
|
* param bytes 需要加密数据
|
* @param secret 加密密钥
|
* @return
|
*/
|
public static byte[] encryBytes(byte []bytes,String secret) {
|
if(bytes==null|| TextUtils.isEmpty(secret)){
|
LogUtils.i("传入数据内容为空或者密钥为空");
|
return null;
|
}
|
return AesUtil.aesEncrypt(bytes, secret);
|
}
|
|
/**
|
* 判断当前主题数据是否需要加密
|
*
|
* @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//启用加密标志
|
);
|
}
|
}
|