wangzhibo
4 天以前 ae6f40460dcd56af6c5f60ba52c883854c3bac55
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*  Copyright (C) 2024 Damien Gaignon, Martin.JM, Vitalii Tomin
 
    This file is part of Gadgetbridge.
 
    Gadgetbridge is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    Gadgetbridge is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.
 
    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>. */
 
/* TLV parsing and serialisation thanks to https://github.com/yihleego/tlv */
package nodomain.freeyourgadget.gadgetbridge.devices.huawei;
 
import static nodomain.freeyourgadget.gadgetbridge.devices.huawei.HuaweiConstants.CryptoTags;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
 
import nodomain.freeyourgadget.gadgetbridge.devices.huawei.HuaweiCrypto.CryptoException;
import nodomain.freeyourgadget.gadgetbridge.devices.huawei.HuaweiPacket.ParamsProvider;
import nodomain.freeyourgadget.gadgetbridge.util.StringUtils;
 
public class HuaweiTLV {
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HuaweiTLV huaweiTLV = (HuaweiTLV) o;
        return Objects.equals(valueMap, huaweiTLV.valueMap);
    }
 
    public static class TLV {
        private final byte tag;
        private final byte[] value;
 
        public TLV(byte tag, byte[] value) {
            this.tag = tag;
            this.value = value;
        }
 
        public byte getTag() {
            return tag;
        }
 
        public byte[] getValue() {
            return value;
        }
 
        public int length() {
            return 1 + VarInt.getVarIntSize(value.length) + value.length;
        }
 
        public byte[] serialize() {
            return ByteBuffer.allocate(this.length())
                    .put(tag)
                    .put(VarInt.putVarIntValue(value.length))
                    .put(value)
                    .array();
        }
 
        public String toString() {
            return "{tag: " + Integer.toHexString(tag & 0xFF) + " - Value: " + StringUtils.bytesToHex(value) + "} - ";
        }
 
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            TLV tlv = (TLV) o;
            return tag == tlv.tag && Arrays.equals(value, tlv.value);
        }
    }
 
    private static final Logger LOG = LoggerFactory.getLogger(HuaweiTLV.class);
 
    protected List<TLV> valueMap;
 
    public HuaweiTLV() {
        this.valueMap = new ArrayList<>();
    }
 
    public int length() {
        int length = 0;
        for (TLV tlv : valueMap)
            length += tlv.length();
        return length;
    }
 
    /**
     * Parse byte buffer into this HuaweiTLV
     * @param buffer The buffer to parse
     * @param offset The offset to start parsing at
     * @param length The length to parse
     * @return The HuaweiTLV object itself
     * @throws ArrayIndexOutOfBoundsException There are two general cases in which this exception
     *  can be thrown:
     *    1. offset + length is greater than the buffer length
     *    2. The buffer is malformed which causes an element size to be larger than the remaining
     *       buffer length
     */
    public HuaweiTLV parse(byte[] buffer, int offset, int length)  {
        if (buffer == null)
            return null;
        int parsed = 0;
        while (parsed < length) {
            // Tag is 1 byte
            byte tag = buffer[offset + parsed];
            parsed += 1;
            // It seems that there can be an extra null byte at the end of something encrypted
            // If that happens we ignore it
            if (parsed == length && tag == 0)
                break;
            // Size is a VarInt >= 1 byte
            VarInt varInt = new VarInt(buffer, offset + parsed);
            int size = varInt.dValue;
            parsed += varInt.size;
            byte[] value = new byte[size];
            System.arraycopy(buffer, offset + parsed, value, 0, size);
            put(tag, value);
            parsed += size;
        }
        LOG.debug("Parsed TLV: " + this);
        return this;
    }
 
    public HuaweiTLV parse(byte[] buffer) {
        if (buffer == null) {
            return null;
        }
        return parse(buffer, 0, buffer.length);
    }
 
    public byte[] serialize() {
        int length = this.length();
        if (length == 0)
            return new byte[0];
        ByteBuffer buffer = ByteBuffer.allocate(length);
        for (TLV entry : valueMap)
            buffer.put(entry.serialize());
        LOG.debug("Serialized TLV: " + this);
        return buffer.array();
    }
 
    public HuaweiTLV put(int tag) {
        byte[] value = new byte[0];
        valueMap.add(new TLV((byte)tag, value));
        return this;
    }
 
    public HuaweiTLV put(int tag, byte[] value) {
        if (value == null) {
            return this;
        }
        valueMap.add(new TLV((byte)tag, value));
        return this;
    }
 
    public HuaweiTLV put(int tag, byte value) {
        return put(tag, new byte[]{value});
    }
 
    public HuaweiTLV put(int tag, boolean value) {
        return put(tag, new byte[]{value ? (byte) 1 : (byte) 0});
    }
 
    public HuaweiTLV put(int tag, Long value) {
        return put(tag, ByteBuffer.allocate(8).putLong(value).array());
    }
 
    public HuaweiTLV put(int tag, Double value) {
        return put(tag, ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putDouble(value).array());
    }
 
    public HuaweiTLV put(int tag, int value) {
        return put(tag, ByteBuffer.allocate(4).putInt(value).array());
    }
 
    public HuaweiTLV put(int tag, short value) {
        return put(tag, ByteBuffer.allocate(2).putShort(value).array());
    }
 
    public HuaweiTLV put(int tag, String value) {
        if (value == null) {
            return this;
        }
        return put(tag, value.getBytes(StandardCharsets.UTF_8));
    }
 
    public HuaweiTLV put(int tag, HuaweiTLV value) {
        if (value == null) {
            return this;
        }
        return put(tag, value.serialize());
    }
 
    public List<TLV> get() {
        return this.valueMap;
    }
 
    public byte[] getBytes(int tag) throws HuaweiPacket.MissingTagException {
        for (TLV item : valueMap)
            if (item.getTag() == (byte) tag)
                return item.getValue();
        throw new HuaweiPacket.MissingTagException(tag);
    }
 
    public byte[] getBytes(int tag, byte[] defaultValue) {
        try {
            return getBytes(tag);
        } catch (HuaweiPacket.MissingTagException e) {
            return defaultValue;
        }
    }
 
    public Byte getByte(int tag) throws HuaweiPacket.MissingTagException {
        return getBytes(tag)[0];
    }
 
    public Byte getByte(int tag, Byte defaultValue) {
        try {
            return getByte(tag);
        } catch (HuaweiPacket.MissingTagException e) {
            return defaultValue;
        }
    }
 
    public Boolean getBoolean(int tag) throws HuaweiPacket.MissingTagException {
        return getBytes(tag)[0] == 1;
    }
 
    public Boolean getBoolean(int tag, Boolean defaultValue) {
        try {
            return getBoolean(tag);
        } catch (HuaweiPacket.MissingTagException e) {
            return defaultValue;
        }
    }
 
    public Integer getInteger(int tag) throws HuaweiPacket.MissingTagException {
        return ByteBuffer.wrap(getBytes(tag)).getInt();
    }
 
    public Integer getInteger(int tag, Integer defaultResult) {
        try {
            return getInteger(tag);
        } catch (HuaweiPacket.MissingTagException e) {
            return defaultResult;
        }
    }
 
    public Short getShort(int tag) throws HuaweiPacket.MissingTagException {
        return ByteBuffer.wrap(getBytes(tag)).getShort();
    }
 
    public Short getShort(int tag, Short defaultValue) {
        try {
            return getShort(tag);
        } catch (HuaweiPacket.MissingTagException e) {
            return defaultValue;
        }
    }
 
    public Long getLong(int tag) throws HuaweiPacket.MissingTagException {
        return ByteBuffer.wrap(getBytes(tag)).getLong();
    }
 
    public Integer getAsInteger(int tag) throws HuaweiPacket.MissingTagException {
        byte[] bytes = getBytes(tag);
        if(bytes.length == 1) {
            return bytes[0] & 0xFF;
        } else if(bytes.length == 2) {
            return ByteBuffer.wrap(getBytes(tag)).getShort() & 0xFFFF;
        }
        return ByteBuffer.wrap(getBytes(tag)).getInt();
    }
 
    public String getString(int tag) throws HuaweiPacket.MissingTagException {
        return new String(getBytes(tag), StandardCharsets.UTF_8);
    }
 
    public HuaweiTLV getObject(int tag) throws HuaweiPacket.MissingTagException {
        byte[] bytes = getBytes(tag);
        return new HuaweiTLV().parse(bytes, 0, bytes.length);
    }
 
    public List<HuaweiTLV> getObjects(int tag) {
        List<HuaweiTLV> returnValue = new ArrayList<>();
        for (TLV tlv : valueMap) {
            if (tlv.getTag() == (byte) tag)
                returnValue.add(new HuaweiTLV().parse(tlv.getValue()));
        }
        return returnValue;
    }
 
    public boolean contains(int tag) {
        for (TLV item : valueMap)
            if (item.getTag() == (byte) tag)
                return true;
        return false;
    }
 
    /**
     * Removes the last element that was added with the specified tag
     * @param tag The tag of the element that should be removed
     * @return The value contained in the removed tag
     */
    public byte[] remove(int tag) {
        TLV foundItem = null;
        for (TLV item : valueMap)
            if (item.getTag() == (byte) tag)
                foundItem = item;
        if (foundItem != null) {
            valueMap.remove(foundItem);
            return foundItem.getValue();
        } else {
            return null;
        }
    }
 
    /**
     * Get string representation of HuaweiTLV, "Empty" when no elements are present
     * @return String
     */
    public String toString() {
        if (valueMap.isEmpty())
            return "Empty";
 
        StringBuilder msg = new StringBuilder();
        for (TLV entry : valueMap)
            msg.append(entry.toString());
        return msg.substring(0, msg.length() - 3);
    }
 
    public static HuaweiTLV encryptRaw(ParamsProvider paramsProvider, byte[] data) throws CryptoException {
        byte[] key = paramsProvider.getSecretKey();
        byte[] nonce = paramsProvider.getIv();
        byte[] encryptedTLV = HuaweiCrypto.encrypt(
                paramsProvider.getEncryptMethod() == 0x01 || paramsProvider.getDeviceSupportType() == 0x04,
                data,
                key,
                nonce);
        return new HuaweiTLV()
                .put(CryptoTags.encryption, (byte) 0x01)
                .put(CryptoTags.initVector, nonce)
                .put(CryptoTags.cipherText, encryptedTLV);
    }
 
    public HuaweiTLV encrypt(ParamsProvider paramsProvider) throws CryptoException {
        byte[] serializedTLV = serialize();
        return encryptRaw(paramsProvider, serializedTLV);
    }
 
    public byte[] decryptRaw(ParamsProvider paramsProvider) throws CryptoException, HuaweiPacket.MissingTagException {
        byte[] key = paramsProvider.getSecretKey();
        return HuaweiCrypto.decrypt(
                paramsProvider.getEncryptMethod() == 0x01 || paramsProvider.getDeviceSupportType() == 0x04,
                getBytes(CryptoTags.cipherText),
                key,
                getBytes(CryptoTags.initVector));
    }
 
    public void decrypt(ParamsProvider paramsProvider) throws CryptoException, HuaweiPacket.MissingTagException {
        byte[] decryptedTLV = decryptRaw(paramsProvider);
        this.valueMap = new ArrayList<>();
        parse(decryptedTLV);
    }
}
 
final class VarInt {
    int dValue; // Decoded value of the VarInt
    int size; // Size of the encoded value
    byte[] eValue; // Encoded value of the VarInt
 
    public VarInt(byte[] src, int offset) {
        this.dValue = getVarIntValue(src, offset);
        this.eValue = putVarIntValue(this.dValue);
        this.size = this.eValue.length;
    }
 
    public String toString() {
        return "VarInt(dValue: " + this.dValue + ", size: " + this.size + ", eValue: " + StringUtils.bytesToHex(this.eValue) + ")";
    }
    
    /**
    * Returns the size of the encoded input value.
    *
    * @param value the integer to be measured
    * @return the encoding size of the input value
    */
    public static int getVarIntSize(int value) {
        int result = 0;
        do {
        result++;
        value >>>= 7;
        } while (value != 0);
        return result;
    }
 
    /**
    * Decode a byte array of a variable-length encoding from start,
    * 7 bits per byte.
    * Return the decoded value in int.
    *
    * @param src the byte array to get the var int from
    * @return the decoded value in int
    */
    public static int getVarIntValue(byte[] src, int offset) {
        int result = 0;
        int b;
        while (true) {
            b = src[offset];
            result += (b & 0x7F);
            if ((b & 0x80) == 0) { break; }
            result <<= 7;
            offset++;
        }
        return result;
    }
 
    /**
    * Encode an integer in a variable-length encoding, 7 bits per byte.
    * Return the encoded value in byte[]
    *
    * @param value the int value to encode
    * @return the encoded value in byte[]
    */
    public static byte[] putVarIntValue(int value) {
        int size = getVarIntSize(value);
        byte[] result = new byte[size];
        result[size - 1] = (byte)(value & 0x7F);
        for (int offset = size - 2; offset >= 0; offset--) {
            value >>>= 7;
            result[offset] = (byte)((value & 0x7F) | 0x80);
        }
        return result;
    }
}