-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
key_data.go
71 lines (61 loc) · 1.86 KB
/
key_data.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package tdesktop
import (
"encoding/binary"
"github.com/go-faster/errors"
"github.com/gotd/td/internal/crypto"
)
type keyData struct {
localKey crypto.Key
accountsIDx []uint32
}
// See https://github.com/telegramdesktop/tdesktop/blob/v2.9.8/Telegram/SourceFiles/storage/storage_domain.cpp#L119-L159.
func readKeyData(tgf *tdesktopFile, passcode []byte) (_ keyData, rErr error) {
salt, err := tgf.readArray()
if err != nil {
return keyData{}, errors.Wrap(err, "read salt")
}
if l := len(salt); l != localEncryptSaltSize {
return keyData{}, errors.Errorf("invalid salt length %d", l)
}
passcodeKey := createLocalKey(passcode, salt)
keyEncrypted, err := tgf.readArray()
if err != nil {
return keyData{}, errors.Wrap(err, "read keyEncrypted")
}
keyInnerData, err := decryptLocal(keyEncrypted, passcodeKey)
if err != nil {
return keyData{}, errors.Wrap(err, "decrypt keyEncrypted")
}
key, _, err := readArray(keyInnerData, binary.LittleEndian)
if err != nil {
return keyData{}, errors.Wrap(err, "read key")
}
if l := len(key); l < len(crypto.Key{}) {
return keyData{}, errors.Errorf("key too small (%d)", l)
}
var localKey crypto.Key
copy(localKey[:], key)
infoEncrypted, err := tgf.readArray()
if err != nil {
return keyData{}, errors.Wrap(err, "read infoEncrypted")
}
infoDecrypted, err := decryptLocal(infoEncrypted, localKey)
if err != nil {
return keyData{}, ErrKeyInfoDecrypt
}
// Skip decrypted data length.
infoDecrypted = infoDecrypted[4:]
// Read count of accounts.
count := int(binary.BigEndian.Uint32(infoDecrypted))
infoDecrypted = infoDecrypted[4:]
// Preallocate accountsIDx.
accountsIDx := make([]uint32, 0, count)
for i := 0; i < count; i++ {
idx := binary.BigEndian.Uint32(infoDecrypted[i*4:])
accountsIDx = append(accountsIDx, idx)
}
return keyData{
localKey: localKey,
accountsIDx: accountsIDx,
}, nil
}