• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# This file is dual licensed under the terms of the Apache License, Version
2# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3# for complete details.
4
5from __future__ import absolute_import, division, print_function
6
7import abc
8
9import six
10
11from cryptography import utils
12from cryptography.hazmat.primitives import hashes
13from cryptography.hazmat.primitives.asymmetric import rsa
14
15
16@six.add_metaclass(abc.ABCMeta)
17class AsymmetricPadding(object):
18    @abc.abstractproperty
19    def name(self):
20        """
21        A string naming this padding (e.g. "PSS", "PKCS1").
22        """
23
24
25@utils.register_interface(AsymmetricPadding)
26class PKCS1v15(object):
27    name = "EMSA-PKCS1-v1_5"
28
29
30@utils.register_interface(AsymmetricPadding)
31class PSS(object):
32    MAX_LENGTH = object()
33    name = "EMSA-PSS"
34
35    def __init__(self, mgf, salt_length):
36        self._mgf = mgf
37
38        if (
39            not isinstance(salt_length, six.integer_types)
40            and salt_length is not self.MAX_LENGTH
41        ):
42            raise TypeError("salt_length must be an integer.")
43
44        if salt_length is not self.MAX_LENGTH and salt_length < 0:
45            raise ValueError("salt_length must be zero or greater.")
46
47        self._salt_length = salt_length
48
49
50@utils.register_interface(AsymmetricPadding)
51class OAEP(object):
52    name = "EME-OAEP"
53
54    def __init__(self, mgf, algorithm, label):
55        if not isinstance(algorithm, hashes.HashAlgorithm):
56            raise TypeError("Expected instance of hashes.HashAlgorithm.")
57
58        self._mgf = mgf
59        self._algorithm = algorithm
60        self._label = label
61
62
63class MGF1(object):
64    MAX_LENGTH = object()
65
66    def __init__(self, algorithm):
67        if not isinstance(algorithm, hashes.HashAlgorithm):
68            raise TypeError("Expected instance of hashes.HashAlgorithm.")
69
70        self._algorithm = algorithm
71
72
73def calculate_max_pss_salt_length(key, hash_algorithm):
74    if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)):
75        raise TypeError("key must be an RSA public or private key")
76    # bit length - 1 per RFC 3447
77    emlen = (key.key_size + 6) // 8
78    salt_length = emlen - hash_algorithm.digest_size - 2
79    assert salt_length >= 0
80    return salt_length
81