decryptWithKeys decrypts encryptedEl, an element with an xenc:EncryptedData child such as saml:EncryptedID or saml:EncryptedAssertion, with the first of keys that can, and returns the root element of the plaintext. recipient is the entity ID of this party. The content key may be wrapped for several
(encryptedEl *etree.Element, keys []namedDecryptionKey, recipient string)
| 214 | // order, each with every one of keys. At most maxEncryptedKeyCandidates |
| 215 | // EncryptedKeys are tried. |
| 216 | func decryptWithKeys(encryptedEl *etree.Element, keys []namedDecryptionKey, recipient string) (*etree.Element, error) { |
| 217 | encryptedDataEl, err := findOneChild(encryptedEl, "http://www.w3.org/2001/04/xmlenc#", "EncryptedData") |
| 218 | if err != nil { |
| 219 | return nil, err |
| 220 | } |
| 221 | if len(keys) == 0 { |
| 222 | return nil, errors.New("no decryption key") |
| 223 | } |
| 224 | |
| 225 | encryptedKeyEls := encryptedKeyCandidates(encryptedEl, encryptedDataEl, recipient) |
| 226 | if len(encryptedKeyEls) > maxEncryptedKeyCandidates { |
| 227 | // Each candidate costs one private-key operation per key, and the |
| 228 | // element may come from an unsigned Response, so an attacker could |
| 229 | // otherwise make one request cost seconds of CPU. |
| 230 | encryptedKeyEls = encryptedKeyEls[:maxEncryptedKeyCandidates] |
| 231 | } |
| 232 | if len(encryptedKeyEls) == 0 { |
| 233 | // No EncryptedKey: the keys are used on the EncryptedData directly. |
| 234 | encryptedKeyEls = []*etree.Element{nil} |
| 235 | } |
| 236 | |
| 237 | // Only the failures of the first EncryptedKey tried are reported, so |
| 238 | // that the error says no more than it did when only that one was tried. |
| 239 | // Key transport is RSA-OAEP only, which fails the same way for every |
| 240 | // wrong key, so trying several keys reveals no more than trying one. |
| 241 | var errs []error |
| 242 | for i, encryptedKeyEl := range encryptedKeyEls { |
| 243 | for _, k := range keys { |
| 244 | plaintext, keyErr := decryptWithKey(k.key, encryptedEl, encryptedKeyEl, encryptedDataEl) |
| 245 | if keyErr == nil { |
| 246 | return parsePlaintext(plaintext) |
| 247 | } |
| 248 | if i == 0 { |
| 249 | errs = append(errs, fmt.Errorf("%s: %w", k.name, keyErr)) |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | if len(keys) == 1 { |
| 254 | return nil, errors.Unwrap(errs[0]) |
| 255 | } |
| 256 | return nil, fmt.Errorf("no decryption key could decrypt it: %w", errors.Join(errs...)) |
| 257 | } |
| 258 | |
| 259 | // encryptedKeyCandidates returns the xenc:EncryptedKey elements that may |
| 260 | // hold the content key of encryptedDataEl: those beside it in encryptedEl |
no test coverage detected