wjc
2024-12-23 f753d8366041354da60b8096060f3ab5159e3880
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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 {
    private static final String TAG=EncryptUtil.class.getName();
    /**
     * 获取加密数据
     *
     * @param linkRequest 请求数据
     * @return
     */
    public static byte[] getEncryBytes(LinkRequest linkRequest) throws UnsupportedEncodingException {
        //判断是否需要加密
        if (ifNeedEncrypt(linkRequest.getTopic(), linkRequest.isEncrypt())) {
            String localSecret=HDLLinkConfig.getInstance().getLocalSecret();
            if(TextUtils.isEmpty(localSecret)){
                LogUtils.e(TAG, "找不到本地密钥,这个问题可能要排期解决");
                //没有密钥使用明文
                return linkRequest.getSendBytes();
            }
            //需要加密
            byte[] dataBytes = AesUtil.aesEncrypt(linkRequest.getData(), localSecret);
            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//启用加密标志
        );
    }
}