forked from SphericalKat/age-mobile
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
age.go
68 lines (53 loc) · 1.11 KB
/
age.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
package ageMobile
import (
"bytes"
"io"
"filippo.io/age"
)
type Keypair struct {
PrivateKey string
PublicKey string
}
func Encrypt(in []byte, publicKey string) ([]byte, error) {
recipient, err := age.ParseX25519Recipient(publicKey)
if err != nil {
return nil, err
}
out := &bytes.Buffer{}
w, err := age.Encrypt(out, recipient)
if err != nil {
return nil, err
}
if _, err := w.Write(in); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
return out.Bytes(), nil
}
func Decrypt(in []byte, privateKey string) ([]byte, error) {
identity, err := age.ParseX25519Identity(privateKey)
if err != nil {
return nil, err
}
out := &bytes.Buffer{}
r, err := age.Decrypt(bytes.NewBuffer(in), identity)
if err != nil {
return nil, err
}
if _, err := io.Copy(out, r); err != nil {
return nil, err
}
return out.Bytes(), nil
}
func GenerateKeypair() (*Keypair, error) {
identity, err := age.GenerateX25519Identity()
if err != nil {
return nil, err
}
return &Keypair{
PrivateKey: identity.Recipient().String(),
PublicKey: identity.String(),
}, nil
}