| # Licensed under the Apache License, Version 2.0 (the "License"); |
| # you may not use this file except in compliance with the License. |
| # You may obtain a copy of the License at |
| # |
| # http://www.apache.org/licenses/LICENSE-2.0 |
| # |
| # Unless required by applicable law or agreed to in writing, software |
| # distributed under the License is distributed on an "AS IS" BASIS, |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| # implied. |
| # See the License for the specific language governing permissions and |
| # limitations under the License. |
| |
| from __future__ import absolute_import, division, print_function |
| |
| from cryptography import utils |
| from cryptography.exceptions import UnsupportedAlgorithm |
| from cryptography.hazmat.backends.interfaces import ( |
| CipherBackend, HashBackend, HMACBackend |
| ) |
| |
| |
| @utils.register_interface(CipherBackend) |
| @utils.register_interface(HashBackend) |
| @utils.register_interface(HMACBackend) |
| class PrioritizedMultiBackend(object): |
| name = "multibackend" |
| |
| def __init__(self, backends): |
| self._backends = backends |
| |
| def cipher_supported(self, algorithm, mode): |
| return any(b.cipher_supported(algorithm, mode) for b in self._backends) |
| |
| def create_symmetric_encryption_ctx(self, algorithm, mode): |
| for b in self._backends: |
| try: |
| return b.create_symmetric_encryption_ctx(algorithm, mode) |
| except UnsupportedAlgorithm: |
| pass |
| raise UnsupportedAlgorithm |
| |
| def create_symmetric_decryption_ctx(self, algorithm, mode): |
| for b in self._backends: |
| try: |
| return b.create_symmetric_decryption_ctx(algorithm, mode) |
| except UnsupportedAlgorithm: |
| pass |
| raise UnsupportedAlgorithm |
| |
| def hash_supported(self, algorithm): |
| return any(b.hash_supported(algorithm) for b in self._backends) |
| |
| def create_hash_ctx(self, algorithm): |
| for b in self._backends: |
| try: |
| return b.create_hash_ctx(algorithm) |
| except UnsupportedAlgorithm: |
| pass |
| raise UnsupportedAlgorithm |
| |
| def hmac_supported(self, algorithm): |
| return any(b.hmac_supported(algorithm) for b in self._backends) |
| |
| def create_hmac_ctx(self, key, algorithm): |
| for b in self._backends: |
| try: |
| return b.create_hmac_ctx(key, algorithm) |
| except UnsupportedAlgorithm: |
| pass |
| raise UnsupportedAlgorithm |