-
Notifications
You must be signed in to change notification settings - Fork 9
/
decrypt.go
69 lines (55 loc) · 1.57 KB
/
decrypt.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package keys
import (
"context"
"fmt"
"io"
"io/fs"
"strings"
"filippo.io/age"
"namespacelabs.dev/foundation/internal/cli/fncobra/name"
"namespacelabs.dev/foundation/internal/fnerrors"
)
const SnapshotKeys = "fn.keys"
type Reader interface {
io.Reader
io.ReaderAt
}
var ErrKeyGen = fnerrors.UsageError(
fmt.Sprintf("Please run `%s keys generate` to generate a new identity.", name.CmdName),
"Decryption requires that at least one identity to be configured.")
func Decrypt(ctx context.Context, keyDir fs.FS, src io.Reader) ([]byte, error) {
if keyDir == nil {
return nil, ErrKeyGen
}
var identities []age.Identity
if err := Visit(ctx, keyDir, func(xi *age.X25519Identity) error {
identities = append(identities, xi)
return nil
}); err != nil {
return nil, err
}
if len(identities) == 0 {
return nil, ErrKeyGen
}
decrypted, err := age.Decrypt(src, identities...)
if err != nil {
if _, ok := err.(*age.NoIdentityMatchError); ok {
var recipients []string
for _, x := range identities {
if id, ok := x.(*age.X25519Identity); ok {
recipients = append(recipients, id.Recipient().String())
}
}
return nil, fnerrors.New("failed to decrypt: no identity matched (had %s)", strings.Join(recipients, ", "))
}
return nil, err
}
decryptedContents, err := io.ReadAll(decrypted)
if err != nil {
return nil, err
}
return decryptedContents, nil
}