| 110 | } |
| 111 | |
| 112 | public static class Response { |
| 113 | private byte type; // 1字节类型 |
| 114 | private int length; // 4字节长度 |
| 115 | private byte status; // 1字节状态码 |
| 116 | private byte[] data; // 数据部分 |
| 117 | |
| 118 | public Response(byte type, byte status, byte[] data) { |
| 119 | this.type = type; |
| 120 | this.status = status; |
| 121 | this.data = data; |
| 122 | this.length = (data != null ? data.length : 0) + 1; // +1是状态码的长度 |
| 123 | } |
| 124 | |
| 125 | // 编码响应包(带加密) |
| 126 | public byte[] encode() { |
| 127 | // 加密数据 |
| 128 | byte[] encryptedData = xorProcess(data); |
| 129 | |
| 130 | ByteBuffer buffer = ByteBuffer.allocate(MAGIC_PREFIX.length + 5 + length); |
| 131 | buffer.put(MAGIC_PREFIX); |
| 132 | buffer.put(type); |
| 133 | buffer.putInt(length); |
| 134 | buffer.put(status); |
| 135 | if (encryptedData != null && encryptedData.length > 0) { |
| 136 | buffer.put(encryptedData); |
| 137 | } |
| 138 | return buffer.array(); |
| 139 | } |
| 140 | |
| 141 | // 解码响应包(带解密) |
| 142 | public static Response decode(byte[] rawData) { |
| 143 | if (!validate(rawData)) { |
| 144 | return null; |
| 145 | } |
| 146 | ByteBuffer buffer = ByteBuffer.wrap(rawData); |
| 147 | buffer.position(MAGIC_PREFIX.length); |
| 148 | byte type = buffer.get(); |
| 149 | int length = buffer.getInt(); |
| 150 | byte status = buffer.get(); |
| 151 | |
| 152 | // 读取并解密数据 |
| 153 | byte[] encryptedData = null; |
| 154 | if (length > 1) { // length包含status的1字节 |
| 155 | encryptedData = new byte[length - 1]; |
| 156 | buffer.get(encryptedData); |
| 157 | encryptedData = xorProcess(encryptedData); |
| 158 | } |
| 159 | |
| 160 | return new Response(type, status, encryptedData); |
| 161 | } |
| 162 | |
| 163 | // 获取原始数据 |
| 164 | public byte[] getData() { |
| 165 | return data; |
| 166 | } |
| 167 | |
| 168 | // 获取解密后的字符串数据 |
| 169 | public String getDataAsString() { |
nothing calls this directly
no outgoing calls
no test coverage detected