-
Notifications
You must be signed in to change notification settings - Fork 0
/
x25519.go
310 lines (270 loc) · 9.17 KB
/
x25519.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// copy from https://github.com/FiloSottile/age/blob/v1.0.0/x25519.go and update
// Copyright 2019 Google LLC
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package age
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"io"
"strings"
// "filippo.io/age/internal/bech32"
"github.com/xiaoyang-chen/x25519/internal/age/internal/bech32"
// "filippo.io/age/internal/format"
"github.com/xiaoyang-chen/x25519/internal/age/internal/format"
githubPkgErrors "github.com/pkg/errors"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/curve25519"
"golang.org/x/crypto/hkdf"
)
const x25519Label = "age-encryption.org/v1/X25519"
// X25519Recipient is the standard age public key. Messages encrypted to this
// recipient can be decrypted with the corresponding X25519Identity.
//
// This recipient is anonymous, in the sense that an attacker can't tell from
// the message alone if it is encrypted to a certain recipient.
type X25519Recipient struct {
theirPublicKey []byte
}
var _ Recipient = &X25519Recipient{}
// newX25519RecipientFromPoint returns a new X25519Recipient from a raw Curve25519 point.
func newX25519RecipientFromPoint(publicKey []byte) (*X25519Recipient, error) {
if len(publicKey) != curve25519.PointSize {
return nil, errors.New("invalid X25519 public key")
}
r := &X25519Recipient{
theirPublicKey: make([]byte, curve25519.PointSize),
}
copy(r.theirPublicKey, publicKey)
return r, nil
}
// ParseX25519Recipient returns a new X25519Recipient from a Bech32 public key
// encoding with the "age1" prefix.
func ParseX25519Recipient(s string) (*X25519Recipient, error) {
t, k, err := bech32.Decode(s)
if err != nil {
return nil, fmt.Errorf("malformed recipient %q: %v", s, err)
}
if t != "age" {
return nil, fmt.Errorf("malformed recipient %q: invalid type %q", s, t)
}
r, err := newX25519RecipientFromPoint(k)
if err != nil {
return nil, fmt.Errorf("malformed recipient %q: %v", s, err)
}
return r, nil
}
func (r *X25519Recipient) Wrap(fileKey []byte) ([]*Stanza, error) {
ephemeral := make([]byte, curve25519.ScalarSize)
if _, err := rand.Read(ephemeral); err != nil {
return nil, err
}
ourPublicKey, err := curve25519.X25519(ephemeral, curve25519.Basepoint)
if err != nil {
return nil, err
}
sharedSecret, err := curve25519.X25519(ephemeral, r.theirPublicKey)
if err != nil {
return nil, err
}
l := &Stanza{
Type: "X25519",
Args: []string{format.EncodeToString(ourPublicKey)},
}
salt := make([]byte, 0, len(ourPublicKey)+len(r.theirPublicKey))
salt = append(salt, ourPublicKey...)
salt = append(salt, r.theirPublicKey...)
h := hkdf.New(sha256.New, sharedSecret, salt, []byte(x25519Label))
wrappingKey := make([]byte, chacha20poly1305.KeySize)
if _, err := io.ReadFull(h, wrappingKey); err != nil {
return nil, err
}
wrappedKey, err := aeadEncrypt(wrappingKey, fileKey)
if err != nil {
return nil, err
}
l.Body = wrappedKey
return []*Stanza{l}, nil
}
// String returns the Bech32 public key encoding of r.
func (r *X25519Recipient) String() string {
s, _ := bech32.Encode("age", r.theirPublicKey)
return s
}
// X25519Identity is the standard age private key, which can decrypt messages
// encrypted to the corresponding X25519Recipient.
type X25519Identity struct {
secretKey, ourPublicKey []byte
}
var _ Identity = &X25519Identity{}
// newX25519IdentityFromScalar returns a new X25519Identity from a raw Curve25519 scalar.
func newX25519IdentityFromScalar(secretKey []byte) (*X25519Identity, error) {
if len(secretKey) != curve25519.ScalarSize {
return nil, errors.New("invalid X25519 secret key")
}
i := &X25519Identity{
secretKey: make([]byte, curve25519.ScalarSize),
}
copy(i.secretKey, secretKey)
i.ourPublicKey, _ = curve25519.X25519(i.secretKey, curve25519.Basepoint)
return i, nil
}
// GenerateX25519Identity randomly generates a new X25519Identity.
func GenerateX25519Identity() (*X25519Identity, error) {
secretKey := make([]byte, curve25519.ScalarSize)
if _, err := rand.Read(secretKey); err != nil {
return nil, fmt.Errorf("internal error: %v", err)
}
return newX25519IdentityFromScalar(secretKey)
}
// ParseX25519Identity returns a new X25519Identity from a Bech32 private key
// encoding with the "AGE-SECRET-KEY-1" prefix.
func ParseX25519Identity(s string) (*X25519Identity, error) {
t, k, err := bech32.Decode(s)
if err != nil {
return nil, fmt.Errorf("malformed secret key: %v", err)
}
if t != "AGE-SECRET-KEY-" {
return nil, fmt.Errorf("malformed secret key: unknown type %q", t)
}
r, err := newX25519IdentityFromScalar(k)
if err != nil {
return nil, fmt.Errorf("malformed secret key: %v", err)
}
return r, nil
}
func (i *X25519Identity) Unwrap(stanzas []*Stanza) ([]byte, error) {
return multiUnwrap(i.unwrap, stanzas)
}
func (i *X25519Identity) unwrap(block *Stanza) ([]byte, error) {
if block.Type != "X25519" {
return nil, ErrIncorrectIdentity
}
if len(block.Args) != 1 {
return nil, errors.New("invalid X25519 recipient block")
}
publicKey, err := format.DecodeString(block.Args[0])
if err != nil {
return nil, fmt.Errorf("failed to parse X25519 recipient: %v", err)
}
if len(publicKey) != curve25519.PointSize {
return nil, errors.New("invalid X25519 recipient block")
}
sharedSecret, err := curve25519.X25519(i.secretKey, publicKey)
if err != nil {
return nil, fmt.Errorf("invalid X25519 recipient: %v", err)
}
salt := make([]byte, 0, len(publicKey)+len(i.ourPublicKey))
salt = append(salt, publicKey...)
salt = append(salt, i.ourPublicKey...)
h := hkdf.New(sha256.New, sharedSecret, salt, []byte(x25519Label))
wrappingKey := make([]byte, chacha20poly1305.KeySize)
if _, err := io.ReadFull(h, wrappingKey); err != nil {
return nil, err
}
fileKey, err := aeadDecrypt(wrappingKey, fileKeySize, block.Body)
if err == errIncorrectCiphertextSize {
return nil, errors.New("invalid X25519 recipient block: incorrect file key size")
} else if err != nil {
return nil, ErrIncorrectIdentity
}
return fileKey, nil
}
// Recipient returns the public X25519Recipient value corresponding to i.
func (i *X25519Identity) Recipient() *X25519Recipient {
r := &X25519Recipient{}
r.theirPublicKey = i.ourPublicKey
return r
}
// String returns the Bech32 private key encoding of i.
func (i *X25519Identity) String() string {
s, _ := bech32.Encode("AGE-SECRET-KEY-", i.secretKey)
return strings.ToUpper(s)
}
// add by xiaoyang-chen line start
// PrivateKey returns the Bech32 private key(Upper) with prefix encoding of i, add by xiaoyang-chen.
func (i *X25519Identity) PrivateKey(prefix string) (private string, err error) {
if private, err = bech32.Encode(prefix, i.secretKey); err != nil {
err = githubPkgErrors.Wrap(err, "bech32 encode fail")
return
}
private = strings.ToUpper(private)
return
}
// PublicKey returns the Bech32 public key encoding of i, add by xiaoyang-chen.
func (i *X25519Identity) PublicKey(prefix string) (public string, err error) {
if public, err = bech32.Encode(prefix, i.ourPublicKey); err != nil {
err = githubPkgErrors.Wrap(err, "bech32 encode fail")
}
return
}
// EncryptByX25519PublicKey encrypt the bytes by public key, add by xiaoyang-chen.
func EncryptByX25519PublicKey(in []byte, publicKey, prefix string) (out []byte, err error) {
var hrp string
var data []byte
if hrp, data, err = bech32.Decode(publicKey); err != nil {
err = githubPkgErrors.Wrap(err, "bech32 decode fail")
return
}
if hrp != prefix {
err = githubPkgErrors.Errorf("wrong prefix, correct: %s, wrong: %s", hrp, prefix)
return
}
var r *X25519Recipient
if r, err = newX25519RecipientFromPoint(data); err != nil {
err = githubPkgErrors.Wrap(err, "new x25519 recipient from public key fail")
return
}
var outBuff = bytes.NewBuffer(make([]byte, 0, 1024))
var ioWC io.WriteCloser
if ioWC, err = Encrypt(outBuff, r); err != nil {
err = githubPkgErrors.Wrap(err, "get encrypt writer fail")
return
}
if _, err = ioWC.Write(in); err != nil {
err = githubPkgErrors.Wrap(err, "encrypt writer write fail")
return
}
if err = ioWC.Close(); err != nil {
err = githubPkgErrors.Wrap(err, "close encrypt writer fail")
return
}
out = outBuff.Bytes()
return
}
// DecryptByX25519PrivateKey decrypt the bytes by private key, add by xiaoyang-chen.
func DecryptByX25519PrivateKey(in []byte, privateKey, prefix string) (out []byte, err error) {
var hrp string
var data []byte
if hrp, data, err = bech32.Decode(privateKey); err != nil {
err = githubPkgErrors.Wrap(err, "bech32 decode fail")
return
}
if hrp != strings.ToUpper(prefix) {
err = githubPkgErrors.Errorf("wrong prefix, correct: %s, wrong: %s", hrp, prefix)
return
}
var i *X25519Identity
if i, err = newX25519IdentityFromScalar(data); err != nil {
err = githubPkgErrors.Wrap(err, "new x25519 identity from private key fail")
return
}
var r io.Reader
if r, err = Decrypt(bytes.NewReader(in), i); err != nil {
err = githubPkgErrors.Wrap(err, "get decrypt reader fail")
return
}
var outBuff = bytes.NewBuffer(make([]byte, 0, 1024))
if _, err = io.Copy(outBuff, r); err != nil {
err = githubPkgErrors.Wrap(err, "decrypt reader read fail")
return
}
out = outBuff.Bytes()
return
}
// add by xiaoyang-chen line end