-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecrypt.go
62 lines (50 loc) · 1.19 KB
/
decrypt.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
// SPDX-FileCopyrightText: 2024 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package securly
import (
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwe"
"github.com/lestrrat-go/jwx/v2/jwk"
)
type decrypter struct {
key jwk.Key
}
// Decrypt converts a byte slice into a *Message and decodes
// it it using the provided key.
func Decrypt(buf []byte, opts ...DecryptOption) (*Message, error) {
d := decrypter{}
opts = append(opts, validateDecrypt())
for _, opt := range opts {
if opt != nil {
err := opt.apply(&d)
if err != nil {
return nil, err
}
}
}
// Parse the JWE to extract the header
JWE, err := jwe.Parse(buf)
if err != nil {
return nil, err
}
// Extract the algorithm from the JWE header
alg, ok := JWE.ProtectedHeaders().Get(jwe.AlgorithmKey)
if !ok {
return nil, err
}
// Decrypt the JWE
decrypted, err := jwe.Decrypt(buf, jwe.WithKey(alg.(jwa.KeyEncryptionAlgorithm), d.key))
if err != nil {
return nil, err
}
bytes, err := decompress(decrypted)
if err != nil {
return nil, err
}
var msg Message
_, err = msg.UnmarshalMsg(bytes)
if err != nil {
return nil, err
}
return &msg, nil
}