-
Notifications
You must be signed in to change notification settings - Fork 13
/
crypto.go
67 lines (55 loc) · 1.3 KB
/
crypto.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
package primitives
import (
"crypto/ed25519"
"encoding/hex"
"fmt"
"strconv"
"github.com/threefoldtech/tfexplorer/schema"
"github.com/threefoldtech/zbus"
"github.com/threefoldtech/zos/pkg/app"
"github.com/threefoldtech/zos/pkg/stubs"
)
func decryptSecret(secret, userID string, reservationVersion int, client zbus.Client) (string, error) {
if len(secret) == 0 {
return "", nil
}
identity := stubs.NewIdentityManagerStub(client)
bytes, err := hex.DecodeString(secret)
if err != nil {
return "", err
}
var (
out []byte
userPubKey ed25519.PublicKey
)
switch reservationVersion {
case 0:
out, err = identity.Decrypt(bytes)
default:
userPubKey, err = fetchUserPublicKey(userID)
if err != nil {
return "", fmt.Errorf("failed to retrieve user %s public key: %w", userID, err)
}
out, err = identity.DecryptECDH(bytes, userPubKey)
}
return string(out), err
}
func fetchUserPublicKey(userID string) (ed25519.PublicKey, error) {
iid, err := strconv.Atoi(userID)
if err != nil {
return nil, err
}
explorer, err := app.ExplorerClient()
if err != nil {
return nil, err
}
user, err := explorer.Phonebook.Get(schema.ID(iid))
if err != nil {
return nil, err
}
b, err := hex.DecodeString(user.Pubkey)
if err != nil {
return nil, err
}
return ed25519.PublicKey(b), nil
}