message.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. package jwe
  2. import (
  3. "context"
  4. "crypto/ecdsa"
  5. "fmt"
  6. "github.com/lestrrat-go/jwx/internal/json"
  7. "github.com/lestrrat-go/jwx/internal/pool"
  8. "github.com/lestrrat-go/jwx/jwk"
  9. "github.com/lestrrat-go/jwx/internal/base64"
  10. "github.com/lestrrat-go/jwx/jwa"
  11. "github.com/pkg/errors"
  12. )
  13. // NewRecipient creates a Recipient object
  14. func NewRecipient() Recipient {
  15. return &stdRecipient{
  16. headers: NewHeaders(),
  17. }
  18. }
  19. func (r *stdRecipient) SetHeaders(h Headers) error {
  20. r.headers = h
  21. return nil
  22. }
  23. func (r *stdRecipient) SetEncryptedKey(v []byte) error {
  24. r.encryptedKey = v
  25. return nil
  26. }
  27. func (r *stdRecipient) Headers() Headers {
  28. return r.headers
  29. }
  30. func (r *stdRecipient) EncryptedKey() []byte {
  31. return r.encryptedKey
  32. }
  33. type recipientMarshalProxy struct {
  34. Headers Headers `json:"header"`
  35. EncryptedKey string `json:"encrypted_key"`
  36. }
  37. func (r *stdRecipient) UnmarshalJSON(buf []byte) error {
  38. var proxy recipientMarshalProxy
  39. proxy.Headers = NewHeaders()
  40. if err := json.Unmarshal(buf, &proxy); err != nil {
  41. return errors.Wrap(err, `failed to unmarshal json into recipient`)
  42. }
  43. r.headers = proxy.Headers
  44. decoded, err := base64.DecodeString(proxy.EncryptedKey)
  45. if err != nil {
  46. return errors.Wrap(err, `failed to decode "encrypted_key"`)
  47. }
  48. r.encryptedKey = decoded
  49. return nil
  50. }
  51. func (r *stdRecipient) MarshalJSON() ([]byte, error) {
  52. buf := pool.GetBytesBuffer()
  53. defer pool.ReleaseBytesBuffer(buf)
  54. buf.WriteString(`{"header":`)
  55. hdrbuf, err := r.headers.MarshalJSON()
  56. if err != nil {
  57. return nil, errors.Wrap(err, `failed to marshal recipient header`)
  58. }
  59. buf.Write(hdrbuf)
  60. buf.WriteString(`,"encrypted_key":"`)
  61. buf.WriteString(base64.EncodeToString(r.encryptedKey))
  62. buf.WriteString(`"}`)
  63. ret := make([]byte, buf.Len())
  64. copy(ret, buf.Bytes())
  65. return ret, nil
  66. }
  67. // NewMessage creates a new message
  68. func NewMessage() *Message {
  69. return &Message{}
  70. }
  71. func (m *Message) AuthenticatedData() []byte {
  72. return m.authenticatedData
  73. }
  74. func (m *Message) CipherText() []byte {
  75. return m.cipherText
  76. }
  77. func (m *Message) InitializationVector() []byte {
  78. return m.initializationVector
  79. }
  80. func (m *Message) Tag() []byte {
  81. return m.tag
  82. }
  83. func (m *Message) ProtectedHeaders() Headers {
  84. return m.protectedHeaders
  85. }
  86. func (m *Message) Recipients() []Recipient {
  87. return m.recipients
  88. }
  89. func (m *Message) UnprotectedHeaders() Headers {
  90. return m.unprotectedHeaders
  91. }
  92. const (
  93. AuthenticatedDataKey = "aad"
  94. CipherTextKey = "ciphertext"
  95. CountKey = "p2c"
  96. InitializationVectorKey = "iv"
  97. ProtectedHeadersKey = "protected"
  98. RecipientsKey = "recipients"
  99. SaltKey = "p2s"
  100. TagKey = "tag"
  101. UnprotectedHeadersKey = "unprotected"
  102. HeadersKey = "header"
  103. EncryptedKeyKey = "encrypted_key"
  104. )
  105. func (m *Message) Set(k string, v interface{}) error {
  106. switch k {
  107. case AuthenticatedDataKey:
  108. buf, ok := v.([]byte)
  109. if !ok {
  110. return errors.Errorf(`invalid value %T for %s key`, v, AuthenticatedDataKey)
  111. }
  112. m.authenticatedData = buf
  113. case CipherTextKey:
  114. buf, ok := v.([]byte)
  115. if !ok {
  116. return errors.Errorf(`invalid value %T for %s key`, v, CipherTextKey)
  117. }
  118. m.cipherText = buf
  119. case InitializationVectorKey:
  120. buf, ok := v.([]byte)
  121. if !ok {
  122. return errors.Errorf(`invalid value %T for %s key`, v, InitializationVectorKey)
  123. }
  124. m.initializationVector = buf
  125. case ProtectedHeadersKey:
  126. cv, ok := v.(Headers)
  127. if !ok {
  128. return errors.Errorf(`invalid value %T for %s key`, v, ProtectedHeadersKey)
  129. }
  130. m.protectedHeaders = cv
  131. case RecipientsKey:
  132. cv, ok := v.([]Recipient)
  133. if !ok {
  134. return errors.Errorf(`invalid value %T for %s key`, v, RecipientsKey)
  135. }
  136. m.recipients = cv
  137. case TagKey:
  138. buf, ok := v.([]byte)
  139. if !ok {
  140. return errors.Errorf(`invalid value %T for %s key`, v, TagKey)
  141. }
  142. m.tag = buf
  143. case UnprotectedHeadersKey:
  144. cv, ok := v.(Headers)
  145. if !ok {
  146. return errors.Errorf(`invalid value %T for %s key`, v, UnprotectedHeadersKey)
  147. }
  148. m.unprotectedHeaders = cv
  149. default:
  150. if m.unprotectedHeaders == nil {
  151. m.unprotectedHeaders = NewHeaders()
  152. }
  153. return m.unprotectedHeaders.Set(k, v)
  154. }
  155. return nil
  156. }
  157. type messageMarshalProxy struct {
  158. AuthenticatedData string `json:"aad,omitempty"`
  159. CipherText string `json:"ciphertext"`
  160. InitializationVector string `json:"iv,omitempty"`
  161. ProtectedHeaders json.RawMessage `json:"protected"`
  162. Recipients []json.RawMessage `json:"recipients,omitempty"`
  163. Tag string `json:"tag,omitempty"`
  164. UnprotectedHeaders Headers `json:"unprotected,omitempty"`
  165. // For flattened structure. Headers is NOT a Headers type,
  166. // so that we can detect its presence by checking proxy.Headers != nil
  167. Headers json.RawMessage `json:"header,omitempty"`
  168. EncryptedKey string `json:"encrypted_key,omitempty"`
  169. }
  170. func (m *Message) MarshalJSON() ([]byte, error) {
  171. // This is slightly convoluted, but we need to encode the
  172. // protected headers, so we do it by hand
  173. buf := pool.GetBytesBuffer()
  174. defer pool.ReleaseBytesBuffer(buf)
  175. enc := json.NewEncoder(buf)
  176. fmt.Fprintf(buf, `{`)
  177. var wrote bool
  178. if aad := m.AuthenticatedData(); len(aad) > 0 {
  179. wrote = true
  180. fmt.Fprintf(buf, `%#v:`, AuthenticatedDataKey)
  181. if err := enc.Encode(base64.EncodeToString(aad)); err != nil {
  182. return nil, errors.Wrapf(err, `failed to encode %s field`, AuthenticatedDataKey)
  183. }
  184. }
  185. if cipherText := m.CipherText(); len(cipherText) > 0 {
  186. if wrote {
  187. fmt.Fprintf(buf, `,`)
  188. }
  189. wrote = true
  190. fmt.Fprintf(buf, `%#v:`, CipherTextKey)
  191. if err := enc.Encode(base64.EncodeToString(cipherText)); err != nil {
  192. return nil, errors.Wrapf(err, `failed to encode %s field`, CipherTextKey)
  193. }
  194. }
  195. if iv := m.InitializationVector(); len(iv) > 0 {
  196. if wrote {
  197. fmt.Fprintf(buf, `,`)
  198. }
  199. wrote = true
  200. fmt.Fprintf(buf, `%#v:`, InitializationVectorKey)
  201. if err := enc.Encode(base64.EncodeToString(iv)); err != nil {
  202. return nil, errors.Wrapf(err, `failed to encode %s field`, InitializationVectorKey)
  203. }
  204. }
  205. if h := m.ProtectedHeaders(); h != nil {
  206. encodedHeaders, err := h.Encode()
  207. if err != nil {
  208. return nil, errors.Wrap(err, `failed to encode protected headers`)
  209. }
  210. if len(encodedHeaders) > 2 {
  211. if wrote {
  212. fmt.Fprintf(buf, `,`)
  213. }
  214. wrote = true
  215. fmt.Fprintf(buf, `%#v:%#v`, ProtectedHeadersKey, string(encodedHeaders))
  216. }
  217. }
  218. if recipients := m.Recipients(); len(recipients) > 0 {
  219. if wrote {
  220. fmt.Fprintf(buf, `,`)
  221. }
  222. if len(recipients) == 1 { // Use flattened format
  223. fmt.Fprintf(buf, `%#v:`, HeadersKey)
  224. if err := enc.Encode(recipients[0].Headers()); err != nil {
  225. return nil, errors.Wrapf(err, `failed to encode %s field`, HeadersKey)
  226. }
  227. if ek := recipients[0].EncryptedKey(); len(ek) > 0 {
  228. fmt.Fprintf(buf, `,%#v:`, EncryptedKeyKey)
  229. if err := enc.Encode(base64.EncodeToString(ek)); err != nil {
  230. return nil, errors.Wrapf(err, `failed to encode %s field`, EncryptedKeyKey)
  231. }
  232. }
  233. } else {
  234. fmt.Fprintf(buf, `%#v:`, RecipientsKey)
  235. if err := enc.Encode(recipients); err != nil {
  236. return nil, errors.Wrapf(err, `failed to encode %s field`, RecipientsKey)
  237. }
  238. }
  239. }
  240. if tag := m.Tag(); len(tag) > 0 {
  241. if wrote {
  242. fmt.Fprintf(buf, `,`)
  243. }
  244. fmt.Fprintf(buf, `%#v:`, TagKey)
  245. if err := enc.Encode(base64.EncodeToString(tag)); err != nil {
  246. return nil, errors.Wrapf(err, `failed to encode %s field`, TagKey)
  247. }
  248. }
  249. if h := m.UnprotectedHeaders(); h != nil {
  250. unprotected, err := json.Marshal(h)
  251. if err != nil {
  252. return nil, errors.Wrap(err, `failed to encode unprotected headers`)
  253. }
  254. if len(unprotected) > 2 {
  255. fmt.Fprintf(buf, `,%#v:%#v`, UnprotectedHeadersKey, string(unprotected))
  256. }
  257. }
  258. fmt.Fprintf(buf, `}`)
  259. ret := make([]byte, buf.Len())
  260. copy(ret, buf.Bytes())
  261. return ret, nil
  262. }
  263. func (m *Message) UnmarshalJSON(buf []byte) error {
  264. var proxy messageMarshalProxy
  265. proxy.UnprotectedHeaders = NewHeaders()
  266. if err := json.Unmarshal(buf, &proxy); err != nil {
  267. return errors.Wrap(err, `failed to unmashal JSON into message`)
  268. }
  269. // Get the string value
  270. var protectedHeadersStr string
  271. if err := json.Unmarshal(proxy.ProtectedHeaders, &protectedHeadersStr); err != nil {
  272. return errors.Wrap(err, `failed to decode protected headers (1)`)
  273. }
  274. // It's now in _quoted_ base64 string. Decode it
  275. protectedHeadersRaw, err := base64.DecodeString(protectedHeadersStr)
  276. if err != nil {
  277. return errors.Wrap(err, "failed to base64 decoded protected headers buffer")
  278. }
  279. h := NewHeaders()
  280. if err := json.Unmarshal(protectedHeadersRaw, h); err != nil {
  281. return errors.Wrap(err, `failed to decode protected headers (2)`)
  282. }
  283. // if this were a flattened message, we would see a "header" and "ciphertext"
  284. // field. TODO: do both of these conditions need to meet, or just one?
  285. if proxy.Headers != nil || len(proxy.EncryptedKey) > 0 {
  286. recipient := NewRecipient()
  287. hdrs := NewHeaders()
  288. if err := json.Unmarshal(proxy.Headers, hdrs); err != nil {
  289. return errors.Wrap(err, `failed to decode headers field`)
  290. }
  291. if err := recipient.SetHeaders(hdrs); err != nil {
  292. return errors.Wrap(err, `failed to set new headers`)
  293. }
  294. if v := proxy.EncryptedKey; len(v) > 0 {
  295. buf, err := base64.DecodeString(v)
  296. if err != nil {
  297. return errors.Wrap(err, `failed to decode encrypted key`)
  298. }
  299. if err := recipient.SetEncryptedKey(buf); err != nil {
  300. return errors.Wrap(err, `failed to set encrypted key`)
  301. }
  302. }
  303. m.recipients = append(m.recipients, recipient)
  304. } else {
  305. for i, recipientbuf := range proxy.Recipients {
  306. recipient := NewRecipient()
  307. if err := json.Unmarshal(recipientbuf, recipient); err != nil {
  308. return errors.Wrapf(err, `failed to decode recipient at index %d`, i)
  309. }
  310. m.recipients = append(m.recipients, recipient)
  311. }
  312. }
  313. if src := proxy.AuthenticatedData; len(src) > 0 {
  314. v, err := base64.DecodeString(src)
  315. if err != nil {
  316. return errors.Wrap(err, `failed to decode "aad"`)
  317. }
  318. m.authenticatedData = v
  319. }
  320. if src := proxy.CipherText; len(src) > 0 {
  321. v, err := base64.DecodeString(src)
  322. if err != nil {
  323. return errors.Wrap(err, `failed to decode "ciphertext"`)
  324. }
  325. m.cipherText = v
  326. }
  327. if src := proxy.InitializationVector; len(src) > 0 {
  328. v, err := base64.DecodeString(src)
  329. if err != nil {
  330. return errors.Wrap(err, `failed to decode "iv"`)
  331. }
  332. m.initializationVector = v
  333. }
  334. if src := proxy.Tag; len(src) > 0 {
  335. v, err := base64.DecodeString(src)
  336. if err != nil {
  337. return errors.Wrap(err, `failed to decode "tag"`)
  338. }
  339. m.tag = v
  340. }
  341. m.protectedHeaders = h
  342. if m.storeProtectedHeaders {
  343. // this is later used for decryption
  344. m.rawProtectedHeaders = base64.Encode(protectedHeadersRaw)
  345. }
  346. if iz, ok := proxy.UnprotectedHeaders.(isZeroer); ok {
  347. if !iz.isZero() {
  348. m.unprotectedHeaders = proxy.UnprotectedHeaders
  349. }
  350. }
  351. if len(m.recipients) == 0 {
  352. if err := m.makeDummyRecipient(proxy.EncryptedKey, m.protectedHeaders); err != nil {
  353. return errors.Wrap(err, `failed to setup recipient`)
  354. }
  355. }
  356. return nil
  357. }
  358. func (m *Message) makeDummyRecipient(enckeybuf string, protected Headers) error {
  359. // Recipients in this case should not contain the content encryption key,
  360. // so move that out
  361. hdrs, err := protected.Clone(context.TODO())
  362. if err != nil {
  363. return errors.Wrap(err, `failed to clone headers`)
  364. }
  365. if err := hdrs.Remove(ContentEncryptionKey); err != nil {
  366. return errors.Wrapf(err, "failed to remove %#v from public header", ContentEncryptionKey)
  367. }
  368. enckey, err := base64.DecodeString(enckeybuf)
  369. if err != nil {
  370. return errors.Wrap(err, `failed to decode encrypted key`)
  371. }
  372. if err := m.Set(RecipientsKey, []Recipient{
  373. &stdRecipient{
  374. headers: hdrs,
  375. encryptedKey: enckey,
  376. },
  377. }); err != nil {
  378. return errors.Wrapf(err, `failed to set %s`, RecipientsKey)
  379. }
  380. return nil
  381. }
  382. // Decrypt decrypts the message using the specified algorithm and key.
  383. //
  384. // `key` must be a private key in its "raw" format (i.e. something like
  385. // *rsa.PrivateKey, instead of jwk.Key)
  386. //
  387. // This method is marked for deprecation. It will be removed from the API
  388. // in the next major release. You should not rely on this method
  389. // to work 100% of the time, especially when it was obtained via jwe.Parse
  390. // instead of being constructed from scratch by this library.
  391. func (m *Message) Decrypt(alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error) {
  392. var ctx decryptCtx
  393. ctx.alg = alg
  394. ctx.key = key
  395. ctx.msg = m
  396. return doDecryptCtx(&ctx)
  397. }
  398. func doDecryptCtx(dctx *decryptCtx) ([]byte, error) {
  399. m := dctx.msg
  400. alg := dctx.alg
  401. key := dctx.key
  402. if jwkKey, ok := key.(jwk.Key); ok {
  403. var raw interface{}
  404. if err := jwkKey.Raw(&raw); err != nil {
  405. return nil, errors.Wrapf(err, `failed to retrieve raw key from %T`, key)
  406. }
  407. key = raw
  408. }
  409. var err error
  410. ctx := context.TODO()
  411. h, err := m.protectedHeaders.Clone(ctx)
  412. if err != nil {
  413. return nil, errors.Wrap(err, `failed to copy protected headers`)
  414. }
  415. h, err = h.Merge(ctx, m.unprotectedHeaders)
  416. if err != nil {
  417. return nil, errors.Wrap(err, "failed to merge headers for message decryption")
  418. }
  419. enc := m.protectedHeaders.ContentEncryption()
  420. var aad []byte
  421. if aadContainer := m.authenticatedData; aadContainer != nil {
  422. aad = base64.Encode(aadContainer)
  423. }
  424. var computedAad []byte
  425. if len(m.rawProtectedHeaders) > 0 {
  426. computedAad = m.rawProtectedHeaders
  427. } else {
  428. // this is probably not required once msg.Decrypt is deprecated
  429. var err error
  430. computedAad, err = m.protectedHeaders.Encode()
  431. if err != nil {
  432. return nil, errors.Wrap(err, "failed to encode protected headers")
  433. }
  434. }
  435. dec := NewDecrypter(alg, enc, key).
  436. AuthenticatedData(aad).
  437. ComputedAuthenticatedData(computedAad).
  438. InitializationVector(m.initializationVector).
  439. Tag(m.tag)
  440. var plaintext []byte
  441. var lastError error
  442. // if we have no recipients, pretend like we only have one
  443. recipients := m.recipients
  444. if len(recipients) == 0 {
  445. r := NewRecipient()
  446. if err := r.SetHeaders(m.protectedHeaders); err != nil {
  447. return nil, errors.Wrap(err, `failed to set headers to recipient`)
  448. }
  449. recipients = append(recipients, r)
  450. }
  451. for _, recipient := range recipients {
  452. // strategy: try each recipient. If we fail in one of the steps,
  453. // keep looping because there might be another key with the same algo
  454. if recipient.Headers().Algorithm() != alg {
  455. // algorithms don't match
  456. continue
  457. }
  458. h2, err := h.Clone(ctx)
  459. if err != nil {
  460. lastError = errors.Wrap(err, `failed to copy headers (1)`)
  461. continue
  462. }
  463. h2, err = h2.Merge(ctx, recipient.Headers())
  464. if err != nil {
  465. lastError = errors.Wrap(err, `failed to copy headers (2)`)
  466. continue
  467. }
  468. switch alg {
  469. case jwa.ECDH_ES, jwa.ECDH_ES_A128KW, jwa.ECDH_ES_A192KW, jwa.ECDH_ES_A256KW:
  470. epkif, ok := h2.Get(EphemeralPublicKeyKey)
  471. if !ok {
  472. return nil, errors.New("failed to get 'epk' field")
  473. }
  474. switch epk := epkif.(type) {
  475. case jwk.ECDSAPublicKey:
  476. var pubkey ecdsa.PublicKey
  477. if err := epk.Raw(&pubkey); err != nil {
  478. return nil, errors.Wrap(err, "failed to get public key")
  479. }
  480. dec.PublicKey(&pubkey)
  481. case jwk.OKPPublicKey:
  482. var pubkey interface{}
  483. if err := epk.Raw(&pubkey); err != nil {
  484. return nil, errors.Wrap(err, "failed to get public key")
  485. }
  486. dec.PublicKey(pubkey)
  487. default:
  488. return nil, errors.Errorf("unexpected 'epk' type %T for alg %s", epkif, alg)
  489. }
  490. if apu := h2.AgreementPartyUInfo(); len(apu) > 0 {
  491. dec.AgreementPartyUInfo(apu)
  492. }
  493. if apv := h2.AgreementPartyVInfo(); len(apv) > 0 {
  494. dec.AgreementPartyVInfo(apv)
  495. }
  496. case jwa.A128GCMKW, jwa.A192GCMKW, jwa.A256GCMKW:
  497. ivB64, ok := h2.Get(InitializationVectorKey)
  498. if !ok {
  499. return nil, errors.New("failed to get 'iv' field")
  500. }
  501. ivB64Str, ok := ivB64.(string)
  502. if !ok {
  503. return nil, errors.Errorf("unexpected type for 'iv': %T", ivB64)
  504. }
  505. tagB64, ok := h2.Get(TagKey)
  506. if !ok {
  507. return nil, errors.New("failed to get 'tag' field")
  508. }
  509. tagB64Str, ok := tagB64.(string)
  510. if !ok {
  511. return nil, errors.Errorf("unexpected type for 'tag': %T", tagB64)
  512. }
  513. iv, err := base64.DecodeString(ivB64Str)
  514. if err != nil {
  515. return nil, errors.Wrap(err, "failed to b64-decode 'iv'")
  516. }
  517. tag, err := base64.DecodeString(tagB64Str)
  518. if err != nil {
  519. return nil, errors.Wrap(err, "failed to b64-decode 'tag'")
  520. }
  521. dec.KeyInitializationVector(iv)
  522. dec.KeyTag(tag)
  523. case jwa.PBES2_HS256_A128KW, jwa.PBES2_HS384_A192KW, jwa.PBES2_HS512_A256KW:
  524. saltB64, ok := h2.Get(SaltKey)
  525. if !ok {
  526. return nil, errors.New("failed to get 'p2s' field")
  527. }
  528. saltB64Str, ok := saltB64.(string)
  529. if !ok {
  530. return nil, errors.Errorf("unexpected type for 'p2s': %T", saltB64)
  531. }
  532. count, ok := h2.Get(CountKey)
  533. if !ok {
  534. return nil, errors.New("failed to get 'p2c' field")
  535. }
  536. countFlt, ok := count.(float64)
  537. if !ok {
  538. return nil, errors.Errorf("unexpected type for 'p2c': %T", count)
  539. }
  540. salt, err := base64.DecodeString(saltB64Str)
  541. if err != nil {
  542. return nil, errors.Wrap(err, "failed to b64-decode 'salt'")
  543. }
  544. dec.KeySalt(salt)
  545. dec.KeyCount(int(countFlt))
  546. }
  547. plaintext, err = dec.Decrypt(recipient.EncryptedKey(), m.cipherText)
  548. if err != nil {
  549. lastError = errors.Wrap(err, `failed to decrypt`)
  550. continue
  551. }
  552. if h2.Compression() == jwa.Deflate {
  553. buf, err := uncompress(plaintext)
  554. if err != nil {
  555. lastError = errors.Wrap(err, `failed to uncompress payload`)
  556. continue
  557. }
  558. plaintext = buf
  559. }
  560. break
  561. }
  562. if plaintext == nil {
  563. if lastError != nil {
  564. return nil, errors.Errorf(`failed to find matching recipient to decrypt key (last error = %s)`, lastError)
  565. }
  566. return nil, errors.New("failed to find matching recipient")
  567. }
  568. return plaintext, nil
  569. }