• 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
8import math
9
10import six
11
12from cryptography import utils
13from cryptography.hazmat.primitives import hashes
14from cryptography.hazmat.primitives.asymmetric import rsa
15
16
17@six.add_metaclass(abc.ABCMeta)
18class AsymmetricPadding(object):
19    @abc.abstractproperty
20    def name(self):
21        """
22        A string naming this padding (e.g. "PSS", "PKCS1").
23        """
24
25
26@utils.register_interface(AsymmetricPadding)
27class PKCS1v15(object):
28    name = "EMSA-PKCS1-v1_5"
29
30
31@utils.register_interface(AsymmetricPadding)
32class PSS(object):
33    MAX_LENGTH = object()
34    name = "EMSA-PSS"
35
36    def __init__(self, mgf, salt_length):
37        self._mgf = mgf
38
39        if (not isinstance(salt_length, six.integer_types) and
40                salt_length is not self.MAX_LENGTH):
41            raise TypeError("salt_length must be an integer.")
42
43        if salt_length is not self.MAX_LENGTH and salt_length < 0:
44            raise ValueError("salt_length must be zero or greater.")
45
46        self._salt_length = salt_length
47
48
49@utils.register_interface(AsymmetricPadding)
50class OAEP(object):
51    name = "EME-OAEP"
52
53    def __init__(self, mgf, algorithm, label):
54        if not isinstance(algorithm, hashes.HashAlgorithm):
55            raise TypeError("Expected instance of hashes.HashAlgorithm.")
56
57        self._mgf = mgf
58        self._algorithm = algorithm
59        self._label = label
60
61
62class MGF1(object):
63    MAX_LENGTH = object()
64
65    def __init__(self, algorithm):
66        if not isinstance(algorithm, hashes.HashAlgorithm):
67            raise TypeError("Expected instance of hashes.HashAlgorithm.")
68
69        self._algorithm = algorithm
70
71
72def calculate_max_pss_salt_length(key, hash_algorithm):
73    if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)):
74        raise TypeError("key must be an RSA public or private key")
75    # bit length - 1 per RFC 3447
76    emlen = int(math.ceil((key.key_size - 1) / 8.0))
77    salt_length = emlen - hash_algorithm.digest_size - 2
78    assert salt_length >= 0
79    return salt_length
80