-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha256cbc_hmac.go
283 lines (238 loc) · 7.68 KB
/
a256cbc_hmac.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
package joseprimitives
import (
"crypto/aes"
"crypto/ecdh"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
josecipher "github.com/go-jose/go-jose/v4/cipher"
)
const (
// KeyEncryptionAlgorithm is the key encryption algorithm.
KeyEncryptionAlgorithm = "ECDH-1PU+A256KW"
// ContentEncryptionAlgorithm is the content encryption algorithm.
ContentEncryptionAlgorithm = "A256CBC-HS512"
)
const (
HeaderKeyAlg = "alg"
HeaderKeyEnc = "enc"
HeaderKeyApu = "apu"
HeaderKeyApv = "apv"
HeaderKeyEpk = "epk"
HeaderKeySkid = "skid"
HeaderKeyKid = "kid"
)
type encryptionOption func(*encryptionOptions)
type encryptionOptions struct {
kid string
skid string
}
// WithKid sets the 'kid' option.
func WithKid(kid string) encryptionOption {
return func(opts *encryptionOptions) {
opts.kid = kid
}
}
// WithSkid sets the 'skid' option.
func WithSkid(skid string) encryptionOption {
return func(opts *encryptionOptions) {
opts.skid = skid
}
}
// Encrypt encrypts a plaintext using the ECDH-1PU+A256KW and A256CBC-HS512 algorithms.
func Encrypt(recipient *ecdh.PublicKey, sender *ecdh.PrivateKey, plaintext []byte, opts ...encryptionOption) (string, error) {
if recipient.Curve() != sender.Curve() {
return "",
fmt.Errorf(
"curve mismatch: recipient's curve '%s', sender's curve '%s'",
recipient.Curve(), sender.Curve(),
)
}
o := &encryptionOptions{}
for _, opt := range opts {
opt(o)
}
var (
epk *ecdh.PrivateKey
err error
)
switch recipient.Curve() {
case ecdh.X25519():
epk, err = ecdh.X25519().GenerateKey(rand.Reader)
if err != nil {
return "", fmt.Errorf("failed to generate ephemeral key: %w", err)
}
case ecdh.P384():
epk, err = ecdh.P384().GenerateKey(rand.Reader)
if err != nil {
return "", fmt.Errorf("failed to generate ephemeral key: %w", err)
}
default:
return "", fmt.Errorf("unsupported curve: '%s'", recipient.Curve())
}
kek, err := NewECDHPU1Key(
ZxKeyPair{p: epk, pub: recipient},
ZxKeyPair{p: sender, pub: recipient},
)
if err != nil {
return "", fmt.Errorf("failed to key agreement: %w", err)
}
cek := make([]byte, 64)
_, err = rand.Read(cek)
if err != nil {
return "", fmt.Errorf("failed to generate cek: %w", err)
}
nonce := make([]byte, aes.BlockSize)
_, err = rand.Read(nonce)
if err != nil {
return "", fmt.Errorf("failed to generate nonce: %w", err)
}
encrypter, err := josecipher.NewCBCHMAC(cek, aes.NewCipher)
if err != nil {
return "", fmt.Errorf("failed to create encrypter: %w", err)
}
add, err := getHeaders(
o.skid, o.kid, recipient, sender, epk)
if err != nil {
return "", fmt.Errorf("failed to create headers: %w", err)
}
headersBytes, err := json.Marshal(add)
if err != nil {
return "", fmt.Errorf("failed to marshal headers: %w", err)
}
ciphertext := encrypter.Seal(nil, nonce, plaintext, headersBytes)
if len(ciphertext) == 0 {
return "", errors.New("failed to encrypt plaintext")
}
encryptedCek, err := kek.Wrap(cek)
if err != nil {
return "", fmt.Errorf("failed to wrap cek: %w", err)
}
noAuthCiphertext, authTag, err := extractAuthTag(ciphertext, len(plaintext), aes.BlockSize, len(cek)/2)
if err != nil {
return "", fmt.Errorf("failed to extract auth tag: %w", err)
}
compactToken := fmt.Sprintf(
"%s.%s.%s.%s.%s",
base64.URLEncoding.EncodeToString(headersBytes),
base64.URLEncoding.EncodeToString(encryptedCek),
base64.URLEncoding.EncodeToString(nonce),
base64.URLEncoding.EncodeToString(noAuthCiphertext),
base64.URLEncoding.EncodeToString(authTag),
)
return compactToken, nil
}
// Decrypt decrypts a compact token.
func Decrypt(recipient *ecdh.PrivateKey, sender *ecdh.PublicKey, compactToken string) ([]byte, error) {
headersBytes, encryptedCek, nonce, ciphertext, authTag, err := parseCompactToken(compactToken)
if err != nil {
return nil, fmt.Errorf("failed to parse compact token: %w", err)
}
headers := map[string]string{}
if err = json.Unmarshal(headersBytes, &headers); err != nil {
return nil, fmt.Errorf("failed to decode headers: %w", err)
}
e, ok := headers[HeaderKeyEpk]
if !ok {
return nil, errors.New("epk not found in headers")
}
epkjwk := &JWK{}
if err = json.Unmarshal([]byte(e), epkjwk); err != nil {
return nil, fmt.Errorf("failed to unmarshal epk: %w", err)
}
ephemeral, err := Export(epkjwk)
if err != nil {
return nil, fmt.Errorf("failed to export epk: %w", err)
}
kek, err := NewECDHPU1Key(ZxKeyPair{p: recipient, pub: ephemeral}, ZxKeyPair{p: recipient, pub: sender})
if err != nil {
return nil, fmt.Errorf("failed to key agreement: %w", err)
}
cek, err := kek.Unwrap(encryptedCek)
if err != nil {
return nil, fmt.Errorf("failed to unwrap cek: %w", err)
}
decrypter, err := josecipher.NewCBCHMAC(cek, aes.NewCipher)
if err != nil {
return nil, fmt.Errorf("failed to create decrypter: %w", err)
}
ciphertext = append(ciphertext, authTag...)
plaintext, err := decrypter.Open(nil, nonce, ciphertext, headersBytes)
if err != nil {
return nil, fmt.Errorf("failed to decrypt ciphertext: %w", err)
}
return plaintext, nil
}
//nolint:gocritic // it's okay for the function to have many return statements
func parseCompactToken(compactToken string) (headers, encryptedCek, nonce, ciphertext, authTag []byte, err error) {
parts := strings.Split(compactToken, ".")
if len(parts) != 5 {
return nil, nil, nil, nil, nil, errors.New("invalid compact token")
}
headers, err = base64.URLEncoding.DecodeString(parts[0])
if err != nil {
return nil, nil, nil, nil, nil, fmt.Errorf("failed to decode headers: %w", err)
}
encryptedCek, err = base64.URLEncoding.DecodeString(parts[1])
if err != nil {
return nil, nil, nil, nil, nil, fmt.Errorf("failed to decode encrypted cek: %w", err)
}
nonce, err = base64.URLEncoding.DecodeString(parts[2])
if err != nil {
return nil, nil, nil, nil, nil, fmt.Errorf("failed to decode nonce: %w", err)
}
ciphertext, err = base64.URLEncoding.DecodeString(parts[3])
if err != nil {
return nil, nil, nil, nil, nil, fmt.Errorf("failed to decode ciphertext: %w", err)
}
authTag, err = base64.URLEncoding.DecodeString(parts[4])
if err != nil {
return nil, nil, nil, nil, nil, fmt.Errorf("failed to decode auth tag: %w", err)
}
return headers, encryptedCek, nonce, ciphertext, authTag, nil
}
func getHeaders(
skid, kid string,
recipient *ecdh.PublicKey,
sender *ecdh.PrivateKey,
epk *ecdh.PrivateKey,
) (map[string]string, error) {
epkjwk, err := Import(epk.PublicKey())
if err != nil {
return nil, fmt.Errorf("failed to import epk to jwt: %w", err)
}
epkstr, err := json.Marshal(epkjwk)
if err != nil {
return nil, fmt.Errorf("failed to encode epk: %w", err)
}
apuBytes := append(epk.PublicKey().Bytes(), sender.PublicKey().Bytes()...)
apuHash := sha256.Sum256(apuBytes)
apvHash := sha256.Sum256(recipient.Bytes())
headers := map[string]string{}
headers[HeaderKeyAlg] = KeyEncryptionAlgorithm
headers[HeaderKeyEnc] = ContentEncryptionAlgorithm
headers[HeaderKeyApu] = base64.URLEncoding.EncodeToString(apuHash[:])
headers[HeaderKeyApv] = base64.URLEncoding.EncodeToString(apvHash[:])
headers[HeaderKeyEpk] = string(epkstr)
if skid != "" {
headers[HeaderKeySkid] = skid
}
if kid != "" {
headers[HeaderKeyKid] = kid
}
return headers, nil
}
func extractAuthTag(ciphertextWithAuthTag []byte, plaintextLength, blockSize, authTagLength int) (
ciphertext []byte, authTag []byte, err error) {
paddedLength := (plaintextLength + blockSize - 1) / blockSize * blockSize
if len(ciphertextWithAuthTag) < paddedLength+authTagLength {
return nil, nil, errors.New("invalid ciphertext length")
}
ciphertext = ciphertextWithAuthTag[:paddedLength]
authTag = ciphertextWithAuthTag[paddedLength : paddedLength+authTagLength]
return ciphertext, authTag, nil
}