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
257 lines (210 loc) · 6.71 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
package net
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
libp2p "gx/ipfs/QmPvyPwuCgJ7pDmrKDxRtsScJgBaM5h4EpRL2qQJsmXf4n/go-libp2p-crypto"
"io"
"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
pk, err := pubKey.ToCurve25519()
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
}
for i := 0; i < 24; i++ {
nonce[i] = n[i]
}
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)
rand.Read(secretKey)
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)
mac.Write(ciphertext)
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) {
curve25519Privkey := privKey.ToCurve25519()
var plaintext []byte
n := ciphertext[:NonceBytes]
ephemPubkeyBytes := ciphertext[NonceBytes : NonceBytes+EphemeralPublicKeyBytes]
ct := ciphertext[NonceBytes+EphemeralPublicKeyBytes:]
var ephemPubkey [32]byte
for i := 0; i < 32; i++ {
ephemPubkey[i] = ephemPubkeyBytes[i]
}
var nonce [24]byte
for i := 0; i < 24; i++ {
nonce[i] = n[i]
}
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)
mac.Write(ciphertext[CiphertextVersionBytes+EncryptedSecretKeyBytes : len(ciphertext)-MacBytes])
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
}