-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaegis.go
103 lines (91 loc) · 1.88 KB
/
aegis.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
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
package main
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
)
type hexedBytes []byte
type based64Bytes []byte
type aegis struct {
Version int
Header header
Db based64Bytes
}
type header struct {
Slots []slot
Params params
}
type slot struct {
Type int
UUID string
Key hexedBytes
Params params `json:"key_params"`
N int
R int
P int
Salt hexedBytes
}
type params struct {
Nonce hexedBytes
Tag hexedBytes
}
func (a aegis) Decrypt(password []byte) db {
var masterKey []byte
for _, slot := range a.Header.Slots {
if slot.Type != 1 {
continue
}
derived, err := deriveKey(password, slot)
if err != nil {
continue
}
decrypted, err := decryptData(derived, slot.Key, slot.Params)
if err != nil {
continue
}
masterKey = decrypted
break
}
if masterKey == nil {
errAndExit("Provided password did not match any of the slots", nil)
}
output, err := decryptData(masterKey, a.Db, a.Header.Params)
if err != nil {
errAndExit("Failed to decrypt database field: %v", err)
}
aegisDb := db{}
err = json.Unmarshal(output, &aegisDb)
if err != nil {
errAndExit("Failed to unmarshal decrypted database: %v", err)
}
return aegisDb
}
func (b *hexedBytes) UnmarshalJSON(data []byte) error {
if len(data) < 2 {
return fmt.Errorf("empty field")
}
data = data[1 : len(data)-1]
buffer := make([]byte, hex.DecodedLen(len(data)))
n, err := hex.Decode(buffer, data)
if err != nil {
return err
}
*b = buffer[:n]
return nil
}
func (b *based64Bytes) UnmarshalJSON(data []byte) error {
if len(data) < 2 {
return fmt.Errorf("empty field")
}
data = data[1 : len(data)-1]
data = bytes.ReplaceAll(data, []byte{'\\'}, []byte{})
buffer := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
n, err := base64.StdEncoding.Decode(buffer, data)
if err != nil {
return err
}
*b = buffer[:n]
return nil
}