This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 283
/
encryption.go
290 lines (240 loc) · 7.41 KB
/
encryption.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
package net
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
libp2p "gx/ipfs/QmTW4SdgBWq9GjsBsHeUx8WuGxzhgzAf88UMH2w62PC8yK/go-libp2p-crypto"
"io"
extra "github.com/agl/ed25519/extra25519"
"golang.org/x/crypto/hkdf"
"golang.org/x/crypto/nacl/box"
)
const (
// The version of the encryption algorithm used. Currently only 1 is supported
CiphertextVersion = 1
// Length of the serialized version in bytes
CiphertextVersionBytes = 4
// Length of the secret key used to generate the AES and MAC keys in bytes
SecretKeyBytes = 32
// Length of the AES key in bytes
AESKeyBytes = 32
// Length of the MAC key in bytes
MacKeyBytes = 32
// Length of the RSA encrypted secret key ciphertext in bytes
EncryptedSecretKeyBytes = 512
// Length of the MAC in bytes
MacBytes = 32
// Length of nacl nonce
NonceBytes = 24
// Length of nacl ephemeral public key
EphemeralPublicKeyBytes = 32
)
var (
// The ciphertext cannot be shorter than CiphertextVersionBytes + EncryptedSecretKeyBytes + aes.BlockSize + MacKeyBytes
ErrShortCiphertext = errors.New("ciphertext is too short")
// The HMAC included in the ciphertext is invalid
ErrInvalidHmac = errors.New("invalid Hmac")
// Nacl box decryption failed
BoxDecryptionError = errors.New("failed to decrypt curve25519")
// Satic salt used in the hdkf
Salt = []byte("OpenBazaar Encryption Algorithm")
)
func Encrypt(pubKey libp2p.PubKey, plaintext []byte) ([]byte, error) {
rsaPubkey, ok := pubKey.(*libp2p.RsaPublicKey)
if ok {
return encryptRSA(rsaPubkey, plaintext)
}
ed25519Pubkey, ok := pubKey.(*libp2p.Ed25519PublicKey)
if ok {
return encryptCurve25519(ed25519Pubkey, plaintext)
}
return nil, errors.New("could not determine key type")
}
func encryptCurve25519(pubKey *libp2p.Ed25519PublicKey, plaintext []byte) ([]byte, error) {
// Generated ephemeral key pair
ephemPub, ephemPriv, err := box.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
// Convert recipient's key into curve25519
rawBytes, err := pubKey.Raw()
if err != nil {
return nil, err
}
var raw [32]byte
copy(raw[:], rawBytes)
pk, err := pubkeyToCurve25519(raw)
if err != nil {
return nil, err
}
// Encrypt with nacl
var ciphertext []byte
var nonce [24]byte
n := make([]byte, 24)
_, err = rand.Read(n)
if err != nil {
return nil, err
}
copy(nonce[:], n)
ciphertext = box.Seal(ciphertext, plaintext, &nonce, pk, ephemPriv)
// Prepend the ephemeral public key
ciphertext = append(ephemPub[:], ciphertext...)
// Prepend nonce
ciphertext = append(nonce[:], ciphertext...)
return ciphertext, nil
}
func encryptRSA(pubKey *libp2p.RsaPublicKey, plaintext []byte) ([]byte, error) {
// Encrypt random secret key with RSA pubkey
secretKey := make([]byte, SecretKeyBytes)
_, err := rand.Read(secretKey)
if err != nil {
return nil, err
}
encKey, err := pubKey.Encrypt(secretKey)
if err != nil {
return nil, err
}
// Derive MAC and AES keys from the secret key using hkdf
hash := sha256.New
hkdfReader := hkdf.New(hash, secretKey, Salt, nil)
aesKey := make([]byte, AESKeyBytes)
_, err = io.ReadFull(hkdfReader, aesKey)
if err != nil {
return nil, err
}
macKey := make([]byte, MacKeyBytes)
_, err = io.ReadFull(hkdfReader, macKey)
if err != nil {
return nil, err
}
// Encrypt message with the AES key
block, err := aes.NewCipher(aesKey)
if err != nil {
return nil, err
}
/* The IV needs to be unique, but not secure. Therefore it is common to
include it at the beginning of the ciphertext. */
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
// Create the HMAC
mac := hmac.New(sha256.New, macKey)
_, err = mac.Write(ciphertext)
if err != nil {
return nil, err
}
messageMac := mac.Sum(nil)
// Prepend the ciphertext with the encrypted secret key
ciphertext = append(encKey, ciphertext...)
// Prepend version
version := make([]byte, CiphertextVersionBytes)
binary.BigEndian.PutUint32(version, uint32(CiphertextVersion))
ciphertext = append(version, ciphertext...)
// Append the MAC
ciphertext = append(ciphertext, messageMac...)
return ciphertext, nil
}
func Decrypt(privKey libp2p.PrivKey, ciphertext []byte) ([]byte, error) {
rsaPrivkey, ok := privKey.(*libp2p.RsaPrivateKey)
if ok {
return decryptRSA(rsaPrivkey, ciphertext)
}
ed25519Privkey, ok := privKey.(*libp2p.Ed25519PrivateKey)
if ok {
return decryptCurve25519(ed25519Privkey, ciphertext)
}
return nil, errors.New("could not determine key type")
}
func decryptCurve25519(privKey *libp2p.Ed25519PrivateKey, ciphertext []byte) ([]byte, error) {
rawBytes, err := privKey.Raw()
if err != nil {
return nil, err
}
var raw [64]byte
copy(raw[:], rawBytes)
curve25519Privkey := privkeyToCurve25519(raw)
var plaintext []byte
n := ciphertext[:NonceBytes]
ephemPubkeyBytes := ciphertext[NonceBytes : NonceBytes+EphemeralPublicKeyBytes]
ct := ciphertext[NonceBytes+EphemeralPublicKeyBytes:]
var ephemPubkey [32]byte
copy(ephemPubkey[:], ephemPubkeyBytes)
var nonce [24]byte
copy(nonce[:], n)
plaintext, success := box.Open(plaintext, ct, &nonce, &ephemPubkey, curve25519Privkey)
if !success {
return nil, BoxDecryptionError
}
return plaintext, nil
}
func decryptRSA(privKey *libp2p.RsaPrivateKey, ciphertext []byte) ([]byte, error) {
if len(ciphertext) < CiphertextVersionBytes+EncryptedSecretKeyBytes+aes.BlockSize+MacKeyBytes {
return nil, ErrShortCiphertext
}
// Decrypt the secret key using the RSA private key
secretKey, err := privKey.Decrypt(ciphertext[CiphertextVersionBytes : CiphertextVersionBytes+EncryptedSecretKeyBytes])
if err != nil {
return nil, err
}
// Derive the AES and MAC keys from the secret key using hdkf
hash := sha256.New
hkdfReader := hkdf.New(hash, secretKey, Salt, nil)
aesKey := make([]byte, AESKeyBytes)
_, err = io.ReadFull(hkdfReader, aesKey)
if err != nil {
return nil, err
}
macKey := make([]byte, MacKeyBytes)
_, err = io.ReadFull(hkdfReader, macKey)
if err != nil {
return nil, err
}
// Calculate the HMAC and verify it is correct
mac := hmac.New(sha256.New, macKey)
_, err = mac.Write(ciphertext[CiphertextVersionBytes+EncryptedSecretKeyBytes : len(ciphertext)-MacBytes])
if err != nil {
return nil, err
}
messageMac := mac.Sum(nil)
if !hmac.Equal(messageMac, ciphertext[len(ciphertext)-MacBytes:]) {
return nil, ErrInvalidHmac
}
// Decrypt the AES ciphertext
block, err := aes.NewCipher(aesKey)
if err != nil {
return nil, err
}
ciphertext = ciphertext[CiphertextVersionBytes+EncryptedSecretKeyBytes : len(ciphertext)-MacBytes]
if len(ciphertext) < aes.BlockSize {
return nil, err
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
// XORKeyStream can work in-place if the two arguments are the same
stream.XORKeyStream(ciphertext, ciphertext)
plaintext := ciphertext
return plaintext, nil
}
func privkeyToCurve25519(sk [64]byte) *[32]byte {
var skNew [32]byte
extra.PrivateKeyToCurve25519(&skNew, &sk)
return &skNew
}
func pubkeyToCurve25519(pk [32]byte) (*[32]byte, error) {
var pkNew [32]byte
success := extra.PublicKeyToCurve25519(&pkNew, &pk)
if !success {
return nil, fmt.Errorf("error converting ed25519 pubkey to curve25519 pubkey")
}
return &pkNew, nil
}