Encrypt encrypts a token and returns it as a string.
(ctx context.Context, e EncryptKeyProvider, claims Claims)
| 25 | |
| 26 | // Encrypt encrypts a token and returns it as a string. |
| 27 | func Encrypt(ctx context.Context, e EncryptKeyProvider, claims Claims) (string, error) { |
| 28 | id, key, err := e.EncryptingKey(ctx) |
| 29 | if err != nil { |
| 30 | return "", xerrors.Errorf("encrypting key: %w", err) |
| 31 | } |
| 32 | |
| 33 | encrypter, err := jose.NewEncrypter( |
| 34 | encryptContentAlgo, |
| 35 | jose.Recipient{ |
| 36 | Algorithm: encryptKeyAlgo, |
| 37 | Key: key, |
| 38 | }, |
| 39 | &jose.EncrypterOptions{ |
| 40 | Compression: jose.DEFLATE, |
| 41 | ExtraHeaders: map[jose.HeaderKey]interface{}{ |
| 42 | keyIDHeaderKey: id, |
| 43 | }, |
| 44 | }, |
| 45 | ) |
| 46 | if err != nil { |
| 47 | return "", xerrors.Errorf("initialize encrypter: %w", err) |
| 48 | } |
| 49 | |
| 50 | payload, err := json.Marshal(claims) |
| 51 | if err != nil { |
| 52 | return "", xerrors.Errorf("marshal payload: %w", err) |
| 53 | } |
| 54 | |
| 55 | encrypted, err := encrypter.Encrypt(payload) |
| 56 | if err != nil { |
| 57 | return "", xerrors.Errorf("encrypt: %w", err) |
| 58 | } |
| 59 | |
| 60 | compact, err := encrypted.CompactSerialize() |
| 61 | if err != nil { |
| 62 | return "", xerrors.Errorf("compact serialize: %w", err) |
| 63 | } |
| 64 | |
| 65 | return compact, nil |
| 66 | } |
| 67 | |
| 68 | func WithDecryptExpected(expected jwt.Expected) func(*DecryptOptions) { |
| 69 | return func(opts *DecryptOptions) { |