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 annotations
6
7import abc
8
9from cryptography import utils
10from cryptography.hazmat.bindings._rust import (
11 ANSIX923PaddingContext,
12 ANSIX923UnpaddingContext,
13 PKCS7PaddingContext,
14 PKCS7UnpaddingContext,
15)
16
17
18class PaddingContext(metaclass=abc.ABCMeta):
19 @abc.abstractmethod
20 def update(self, data: utils.Buffer) -> bytes:
21 """
22 Pads the provided bytes and returns any available data as bytes.
23 """
24
25 @abc.abstractmethod
26 def finalize(self) -> bytes:
27 """
28 Finalize the padding, returns bytes.
29 """
30
31
32def _byte_padding_check(block_size: int) -> None:
33 if not (0 <= block_size <= 2040):
34 raise ValueError("block_size must be in range(0, 2041).")
35
36 if block_size % 8 != 0:
37 raise ValueError("block_size must be a multiple of 8.")
38
39
40class PKCS7:
41 def __init__(self, block_size: int):
42 _byte_padding_check(block_size)
43 self.block_size = block_size
44
45 def padder(self) -> PaddingContext:
46 return PKCS7PaddingContext(self.block_size)
47
48 def unpadder(self) -> PaddingContext:
49 return PKCS7UnpaddingContext(self.block_size)
50
51
52PaddingContext.register(PKCS7PaddingContext)
53PaddingContext.register(PKCS7UnpaddingContext)
54
55
56class ANSIX923:
57 def __init__(self, block_size: int):
58 _byte_padding_check(block_size)
59 self.block_size = block_size
60
61 def padder(self) -> PaddingContext:
62 return ANSIX923PaddingContext(self.block_size)
63
64 def unpadder(self) -> PaddingContext:
65 return ANSIX923UnpaddingContext(self.block_size)
66
67
68PaddingContext.register(ANSIX923PaddingContext)
69PaddingContext.register(ANSIX923UnpaddingContext)