/
t808_0x0a00.go
53 lines (44 loc) · 1019 Bytes
/
t808_0x0a00.go
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
package protocol
import (
"crypto/rsa"
"errors"
"math/big"
)
// 终端 RSA公钥
type T808_0x0A00 struct {
PublicKey *rsa.PublicKey
}
func (entity *T808_0x0A00) MsgID() MsgID {
return MsgT808_0x0A00
}
func (entity *T808_0x0A00) Encode() ([]byte, error) {
if entity.PublicKey == nil || entity.PublicKey.N == nil {
return nil, errors.New("invalid public key")
}
if entity.PublicKey.Size() != 128 {
return nil, errors.New("public key must be 1024 bits")
}
writer := NewWriter()
writer.WriteUint32(uint32(entity.PublicKey.E))
writer.Write(entity.PublicKey.N.Bytes(), 128)
return writer.Bytes(), nil
}
func (entity *T808_0x0A00) Decode(data []byte) (int, error) {
if len(data) < 132 {
return 0, ErrInvalidBody
}
reader := NewReader(data)
e, err := reader.ReadUint32()
if err != nil {
return 0, err
}
n, err := reader.Read(128)
if err != nil {
return 0, err
}
entity.PublicKey = &rsa.PublicKey{
E: int(e),
N: big.NewInt(0).SetBytes(n),
}
return len(data) - reader.Len(), nil
}