nnilayy commited on
Commit
ca942ce
·
verified ·
1 Parent(s): 6828dac

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. lib/python3.10/site-packages/colorama/tests/__init__.py +1 -0
  2. lib/python3.10/site-packages/colorama/tests/ansi_test.py +76 -0
  3. lib/python3.10/site-packages/colorama/tests/ansitowin32_test.py +294 -0
  4. lib/python3.10/site-packages/colorama/tests/initialise_test.py +189 -0
  5. lib/python3.10/site-packages/colorama/tests/isatty_test.py +57 -0
  6. lib/python3.10/site-packages/colorama/tests/utils.py +49 -0
  7. lib/python3.10/site-packages/colorama/tests/winterm_test.py +131 -0
  8. lib/python3.10/site-packages/cryptography/__about__.py +17 -0
  9. lib/python3.10/site-packages/cryptography/__init__.py +26 -0
  10. lib/python3.10/site-packages/cryptography/exceptions.py +52 -0
  11. lib/python3.10/site-packages/cryptography/fernet.py +223 -0
  12. lib/python3.10/site-packages/cryptography/hazmat/__init__.py +13 -0
  13. lib/python3.10/site-packages/cryptography/hazmat/_oid.py +315 -0
  14. lib/python3.10/site-packages/cryptography/hazmat/decrepit/__init__.py +5 -0
  15. lib/python3.10/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py +5 -0
  16. lib/python3.10/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py +107 -0
  17. lib/python3.10/site-packages/cryptography/hazmat/primitives/_serialization.py +169 -0
  18. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py +3 -0
  19. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py +135 -0
  20. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py +154 -0
  21. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py +403 -0
  22. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py +116 -0
  23. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py +113 -0
  24. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py +263 -0
  25. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/types.py +111 -0
  26. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py +24 -0
  27. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py +109 -0
  28. lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py +112 -0
  29. lib/python3.10/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py +27 -0
  30. lib/python3.10/site-packages/cryptography/hazmat/primitives/ciphers/aead.py +23 -0
  31. lib/python3.10/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py +183 -0
  32. lib/python3.10/site-packages/cryptography/hazmat/primitives/cmac.py +10 -0
  33. lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/__init__.py +23 -0
  34. lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/argon2.py +13 -0
  35. lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py +124 -0
  36. lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py +101 -0
  37. lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py +302 -0
  38. lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py +62 -0
  39. lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py +19 -0
  40. lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py +61 -0
  41. lib/python3.10/site-packages/cryptography/hazmat/primitives/padding.py +183 -0
  42. lib/python3.10/site-packages/cryptography/hazmat/primitives/serialization/__init__.py +63 -0
  43. lib/python3.10/site-packages/cryptography/hazmat/primitives/serialization/base.py +14 -0
  44. lib/python3.10/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py +369 -0
  45. lib/python3.10/site-packages/cryptography/hazmat/primitives/serialization/ssh.py +1569 -0
  46. lib/python3.10/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py +9 -0
  47. lib/python3.10/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py +100 -0
  48. lib/python3.10/site-packages/cryptography/hazmat/primitives/twofactor/totp.py +55 -0
  49. lib/python3.10/site-packages/cryptography/py.typed +0 -0
  50. lib/python3.10/site-packages/cryptography/utils.py +127 -0
lib/python3.10/site-packages/colorama/tests/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
lib/python3.10/site-packages/colorama/tests/ansi_test.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main
4
+
5
+ from ..ansi import Back, Fore, Style
6
+ from ..ansitowin32 import AnsiToWin32
7
+
8
+ stdout_orig = sys.stdout
9
+ stderr_orig = sys.stderr
10
+
11
+
12
+ class AnsiTest(TestCase):
13
+
14
+ def setUp(self):
15
+ # sanity check: stdout should be a file or StringIO object.
16
+ # It will only be AnsiToWin32 if init() has previously wrapped it
17
+ self.assertNotEqual(type(sys.stdout), AnsiToWin32)
18
+ self.assertNotEqual(type(sys.stderr), AnsiToWin32)
19
+
20
+ def tearDown(self):
21
+ sys.stdout = stdout_orig
22
+ sys.stderr = stderr_orig
23
+
24
+
25
+ def testForeAttributes(self):
26
+ self.assertEqual(Fore.BLACK, '\033[30m')
27
+ self.assertEqual(Fore.RED, '\033[31m')
28
+ self.assertEqual(Fore.GREEN, '\033[32m')
29
+ self.assertEqual(Fore.YELLOW, '\033[33m')
30
+ self.assertEqual(Fore.BLUE, '\033[34m')
31
+ self.assertEqual(Fore.MAGENTA, '\033[35m')
32
+ self.assertEqual(Fore.CYAN, '\033[36m')
33
+ self.assertEqual(Fore.WHITE, '\033[37m')
34
+ self.assertEqual(Fore.RESET, '\033[39m')
35
+
36
+ # Check the light, extended versions.
37
+ self.assertEqual(Fore.LIGHTBLACK_EX, '\033[90m')
38
+ self.assertEqual(Fore.LIGHTRED_EX, '\033[91m')
39
+ self.assertEqual(Fore.LIGHTGREEN_EX, '\033[92m')
40
+ self.assertEqual(Fore.LIGHTYELLOW_EX, '\033[93m')
41
+ self.assertEqual(Fore.LIGHTBLUE_EX, '\033[94m')
42
+ self.assertEqual(Fore.LIGHTMAGENTA_EX, '\033[95m')
43
+ self.assertEqual(Fore.LIGHTCYAN_EX, '\033[96m')
44
+ self.assertEqual(Fore.LIGHTWHITE_EX, '\033[97m')
45
+
46
+
47
+ def testBackAttributes(self):
48
+ self.assertEqual(Back.BLACK, '\033[40m')
49
+ self.assertEqual(Back.RED, '\033[41m')
50
+ self.assertEqual(Back.GREEN, '\033[42m')
51
+ self.assertEqual(Back.YELLOW, '\033[43m')
52
+ self.assertEqual(Back.BLUE, '\033[44m')
53
+ self.assertEqual(Back.MAGENTA, '\033[45m')
54
+ self.assertEqual(Back.CYAN, '\033[46m')
55
+ self.assertEqual(Back.WHITE, '\033[47m')
56
+ self.assertEqual(Back.RESET, '\033[49m')
57
+
58
+ # Check the light, extended versions.
59
+ self.assertEqual(Back.LIGHTBLACK_EX, '\033[100m')
60
+ self.assertEqual(Back.LIGHTRED_EX, '\033[101m')
61
+ self.assertEqual(Back.LIGHTGREEN_EX, '\033[102m')
62
+ self.assertEqual(Back.LIGHTYELLOW_EX, '\033[103m')
63
+ self.assertEqual(Back.LIGHTBLUE_EX, '\033[104m')
64
+ self.assertEqual(Back.LIGHTMAGENTA_EX, '\033[105m')
65
+ self.assertEqual(Back.LIGHTCYAN_EX, '\033[106m')
66
+ self.assertEqual(Back.LIGHTWHITE_EX, '\033[107m')
67
+
68
+
69
+ def testStyleAttributes(self):
70
+ self.assertEqual(Style.DIM, '\033[2m')
71
+ self.assertEqual(Style.NORMAL, '\033[22m')
72
+ self.assertEqual(Style.BRIGHT, '\033[1m')
73
+
74
+
75
+ if __name__ == '__main__':
76
+ main()
lib/python3.10/site-packages/colorama/tests/ansitowin32_test.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ from io import StringIO, TextIOWrapper
3
+ from unittest import TestCase, main
4
+ try:
5
+ from contextlib import ExitStack
6
+ except ImportError:
7
+ # python 2
8
+ from contextlib2 import ExitStack
9
+
10
+ try:
11
+ from unittest.mock import MagicMock, Mock, patch
12
+ except ImportError:
13
+ from mock import MagicMock, Mock, patch
14
+
15
+ from ..ansitowin32 import AnsiToWin32, StreamWrapper
16
+ from ..win32 import ENABLE_VIRTUAL_TERMINAL_PROCESSING
17
+ from .utils import osname
18
+
19
+
20
+ class StreamWrapperTest(TestCase):
21
+
22
+ def testIsAProxy(self):
23
+ mockStream = Mock()
24
+ wrapper = StreamWrapper(mockStream, None)
25
+ self.assertTrue( wrapper.random_attr is mockStream.random_attr )
26
+
27
+ def testDelegatesWrite(self):
28
+ mockStream = Mock()
29
+ mockConverter = Mock()
30
+ wrapper = StreamWrapper(mockStream, mockConverter)
31
+ wrapper.write('hello')
32
+ self.assertTrue(mockConverter.write.call_args, (('hello',), {}))
33
+
34
+ def testDelegatesContext(self):
35
+ mockConverter = Mock()
36
+ s = StringIO()
37
+ with StreamWrapper(s, mockConverter) as fp:
38
+ fp.write(u'hello')
39
+ self.assertTrue(s.closed)
40
+
41
+ def testProxyNoContextManager(self):
42
+ mockStream = MagicMock()
43
+ mockStream.__enter__.side_effect = AttributeError()
44
+ mockConverter = Mock()
45
+ with self.assertRaises(AttributeError) as excinfo:
46
+ with StreamWrapper(mockStream, mockConverter) as wrapper:
47
+ wrapper.write('hello')
48
+
49
+ def test_closed_shouldnt_raise_on_closed_stream(self):
50
+ stream = StringIO()
51
+ stream.close()
52
+ wrapper = StreamWrapper(stream, None)
53
+ self.assertEqual(wrapper.closed, True)
54
+
55
+ def test_closed_shouldnt_raise_on_detached_stream(self):
56
+ stream = TextIOWrapper(StringIO())
57
+ stream.detach()
58
+ wrapper = StreamWrapper(stream, None)
59
+ self.assertEqual(wrapper.closed, True)
60
+
61
+ class AnsiToWin32Test(TestCase):
62
+
63
+ def testInit(self):
64
+ mockStdout = Mock()
65
+ auto = Mock()
66
+ stream = AnsiToWin32(mockStdout, autoreset=auto)
67
+ self.assertEqual(stream.wrapped, mockStdout)
68
+ self.assertEqual(stream.autoreset, auto)
69
+
70
+ @patch('colorama.ansitowin32.winterm', None)
71
+ @patch('colorama.ansitowin32.winapi_test', lambda *_: True)
72
+ def testStripIsTrueOnWindows(self):
73
+ with osname('nt'):
74
+ mockStdout = Mock()
75
+ stream = AnsiToWin32(mockStdout)
76
+ self.assertTrue(stream.strip)
77
+
78
+ def testStripIsFalseOffWindows(self):
79
+ with osname('posix'):
80
+ mockStdout = Mock(closed=False)
81
+ stream = AnsiToWin32(mockStdout)
82
+ self.assertFalse(stream.strip)
83
+
84
+ def testWriteStripsAnsi(self):
85
+ mockStdout = Mock()
86
+ stream = AnsiToWin32(mockStdout)
87
+ stream.wrapped = Mock()
88
+ stream.write_and_convert = Mock()
89
+ stream.strip = True
90
+
91
+ stream.write('abc')
92
+
93
+ self.assertFalse(stream.wrapped.write.called)
94
+ self.assertEqual(stream.write_and_convert.call_args, (('abc',), {}))
95
+
96
+ def testWriteDoesNotStripAnsi(self):
97
+ mockStdout = Mock()
98
+ stream = AnsiToWin32(mockStdout)
99
+ stream.wrapped = Mock()
100
+ stream.write_and_convert = Mock()
101
+ stream.strip = False
102
+ stream.convert = False
103
+
104
+ stream.write('abc')
105
+
106
+ self.assertFalse(stream.write_and_convert.called)
107
+ self.assertEqual(stream.wrapped.write.call_args, (('abc',), {}))
108
+
109
+ def assert_autoresets(self, convert, autoreset=True):
110
+ stream = AnsiToWin32(Mock())
111
+ stream.convert = convert
112
+ stream.reset_all = Mock()
113
+ stream.autoreset = autoreset
114
+ stream.winterm = Mock()
115
+
116
+ stream.write('abc')
117
+
118
+ self.assertEqual(stream.reset_all.called, autoreset)
119
+
120
+ def testWriteAutoresets(self):
121
+ self.assert_autoresets(convert=True)
122
+ self.assert_autoresets(convert=False)
123
+ self.assert_autoresets(convert=True, autoreset=False)
124
+ self.assert_autoresets(convert=False, autoreset=False)
125
+
126
+ def testWriteAndConvertWritesPlainText(self):
127
+ stream = AnsiToWin32(Mock())
128
+ stream.write_and_convert( 'abc' )
129
+ self.assertEqual( stream.wrapped.write.call_args, (('abc',), {}) )
130
+
131
+ def testWriteAndConvertStripsAllValidAnsi(self):
132
+ stream = AnsiToWin32(Mock())
133
+ stream.call_win32 = Mock()
134
+ data = [
135
+ 'abc\033[mdef',
136
+ 'abc\033[0mdef',
137
+ 'abc\033[2mdef',
138
+ 'abc\033[02mdef',
139
+ 'abc\033[002mdef',
140
+ 'abc\033[40mdef',
141
+ 'abc\033[040mdef',
142
+ 'abc\033[0;1mdef',
143
+ 'abc\033[40;50mdef',
144
+ 'abc\033[50;30;40mdef',
145
+ 'abc\033[Adef',
146
+ 'abc\033[0Gdef',
147
+ 'abc\033[1;20;128Hdef',
148
+ ]
149
+ for datum in data:
150
+ stream.wrapped.write.reset_mock()
151
+ stream.write_and_convert( datum )
152
+ self.assertEqual(
153
+ [args[0] for args in stream.wrapped.write.call_args_list],
154
+ [ ('abc',), ('def',) ]
155
+ )
156
+
157
+ def testWriteAndConvertSkipsEmptySnippets(self):
158
+ stream = AnsiToWin32(Mock())
159
+ stream.call_win32 = Mock()
160
+ stream.write_and_convert( '\033[40m\033[41m' )
161
+ self.assertFalse( stream.wrapped.write.called )
162
+
163
+ def testWriteAndConvertCallsWin32WithParamsAndCommand(self):
164
+ stream = AnsiToWin32(Mock())
165
+ stream.convert = True
166
+ stream.call_win32 = Mock()
167
+ stream.extract_params = Mock(return_value='params')
168
+ data = {
169
+ 'abc\033[adef': ('a', 'params'),
170
+ 'abc\033[;;bdef': ('b', 'params'),
171
+ 'abc\033[0cdef': ('c', 'params'),
172
+ 'abc\033[;;0;;Gdef': ('G', 'params'),
173
+ 'abc\033[1;20;128Hdef': ('H', 'params'),
174
+ }
175
+ for datum, expected in data.items():
176
+ stream.call_win32.reset_mock()
177
+ stream.write_and_convert( datum )
178
+ self.assertEqual( stream.call_win32.call_args[0], expected )
179
+
180
+ def test_reset_all_shouldnt_raise_on_closed_orig_stdout(self):
181
+ stream = StringIO()
182
+ converter = AnsiToWin32(stream)
183
+ stream.close()
184
+
185
+ converter.reset_all()
186
+
187
+ def test_wrap_shouldnt_raise_on_closed_orig_stdout(self):
188
+ stream = StringIO()
189
+ stream.close()
190
+ with \
191
+ patch("colorama.ansitowin32.os.name", "nt"), \
192
+ patch("colorama.ansitowin32.winapi_test", lambda: True):
193
+ converter = AnsiToWin32(stream)
194
+ self.assertTrue(converter.strip)
195
+ self.assertFalse(converter.convert)
196
+
197
+ def test_wrap_shouldnt_raise_on_missing_closed_attr(self):
198
+ with \
199
+ patch("colorama.ansitowin32.os.name", "nt"), \
200
+ patch("colorama.ansitowin32.winapi_test", lambda: True):
201
+ converter = AnsiToWin32(object())
202
+ self.assertTrue(converter.strip)
203
+ self.assertFalse(converter.convert)
204
+
205
+ def testExtractParams(self):
206
+ stream = AnsiToWin32(Mock())
207
+ data = {
208
+ '': (0,),
209
+ ';;': (0,),
210
+ '2': (2,),
211
+ ';;002;;': (2,),
212
+ '0;1': (0, 1),
213
+ ';;003;;456;;': (3, 456),
214
+ '11;22;33;44;55': (11, 22, 33, 44, 55),
215
+ }
216
+ for datum, expected in data.items():
217
+ self.assertEqual(stream.extract_params('m', datum), expected)
218
+
219
+ def testCallWin32UsesLookup(self):
220
+ listener = Mock()
221
+ stream = AnsiToWin32(listener)
222
+ stream.win32_calls = {
223
+ 1: (lambda *_, **__: listener(11),),
224
+ 2: (lambda *_, **__: listener(22),),
225
+ 3: (lambda *_, **__: listener(33),),
226
+ }
227
+ stream.call_win32('m', (3, 1, 99, 2))
228
+ self.assertEqual(
229
+ [a[0][0] for a in listener.call_args_list],
230
+ [33, 11, 22] )
231
+
232
+ def test_osc_codes(self):
233
+ mockStdout = Mock()
234
+ stream = AnsiToWin32(mockStdout, convert=True)
235
+ with patch('colorama.ansitowin32.winterm') as winterm:
236
+ data = [
237
+ '\033]0\x07', # missing arguments
238
+ '\033]0;foo\x08', # wrong OSC command
239
+ '\033]0;colorama_test_title\x07', # should work
240
+ '\033]1;colorama_test_title\x07', # wrong set command
241
+ '\033]2;colorama_test_title\x07', # should work
242
+ '\033]' + ';' * 64 + '\x08', # see issue #247
243
+ ]
244
+ for code in data:
245
+ stream.write(code)
246
+ self.assertEqual(winterm.set_title.call_count, 2)
247
+
248
+ def test_native_windows_ansi(self):
249
+ with ExitStack() as stack:
250
+ def p(a, b):
251
+ stack.enter_context(patch(a, b, create=True))
252
+ # Pretend to be on Windows
253
+ p("colorama.ansitowin32.os.name", "nt")
254
+ p("colorama.ansitowin32.winapi_test", lambda: True)
255
+ p("colorama.win32.winapi_test", lambda: True)
256
+ p("colorama.winterm.win32.windll", "non-None")
257
+ p("colorama.winterm.get_osfhandle", lambda _: 1234)
258
+
259
+ # Pretend that our mock stream has native ANSI support
260
+ p(
261
+ "colorama.winterm.win32.GetConsoleMode",
262
+ lambda _: ENABLE_VIRTUAL_TERMINAL_PROCESSING,
263
+ )
264
+ SetConsoleMode = Mock()
265
+ p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode)
266
+
267
+ stdout = Mock()
268
+ stdout.closed = False
269
+ stdout.isatty.return_value = True
270
+ stdout.fileno.return_value = 1
271
+
272
+ # Our fake console says it has native vt support, so AnsiToWin32 should
273
+ # enable that support and do nothing else.
274
+ stream = AnsiToWin32(stdout)
275
+ SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING)
276
+ self.assertFalse(stream.strip)
277
+ self.assertFalse(stream.convert)
278
+ self.assertFalse(stream.should_wrap())
279
+
280
+ # Now let's pretend we're on an old Windows console, that doesn't have
281
+ # native ANSI support.
282
+ p("colorama.winterm.win32.GetConsoleMode", lambda _: 0)
283
+ SetConsoleMode = Mock()
284
+ p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode)
285
+
286
+ stream = AnsiToWin32(stdout)
287
+ SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING)
288
+ self.assertTrue(stream.strip)
289
+ self.assertTrue(stream.convert)
290
+ self.assertTrue(stream.should_wrap())
291
+
292
+
293
+ if __name__ == '__main__':
294
+ main()
lib/python3.10/site-packages/colorama/tests/initialise_test.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main, skipUnless
4
+
5
+ try:
6
+ from unittest.mock import patch, Mock
7
+ except ImportError:
8
+ from mock import patch, Mock
9
+
10
+ from ..ansitowin32 import StreamWrapper
11
+ from ..initialise import init, just_fix_windows_console, _wipe_internal_state_for_tests
12
+ from .utils import osname, replace_by
13
+
14
+ orig_stdout = sys.stdout
15
+ orig_stderr = sys.stderr
16
+
17
+
18
+ class InitTest(TestCase):
19
+
20
+ @skipUnless(sys.stdout.isatty(), "sys.stdout is not a tty")
21
+ def setUp(self):
22
+ # sanity check
23
+ self.assertNotWrapped()
24
+
25
+ def tearDown(self):
26
+ _wipe_internal_state_for_tests()
27
+ sys.stdout = orig_stdout
28
+ sys.stderr = orig_stderr
29
+
30
+ def assertWrapped(self):
31
+ self.assertIsNot(sys.stdout, orig_stdout, 'stdout should be wrapped')
32
+ self.assertIsNot(sys.stderr, orig_stderr, 'stderr should be wrapped')
33
+ self.assertTrue(isinstance(sys.stdout, StreamWrapper),
34
+ 'bad stdout wrapper')
35
+ self.assertTrue(isinstance(sys.stderr, StreamWrapper),
36
+ 'bad stderr wrapper')
37
+
38
+ def assertNotWrapped(self):
39
+ self.assertIs(sys.stdout, orig_stdout, 'stdout should not be wrapped')
40
+ self.assertIs(sys.stderr, orig_stderr, 'stderr should not be wrapped')
41
+
42
+ @patch('colorama.initialise.reset_all')
43
+ @patch('colorama.ansitowin32.winapi_test', lambda *_: True)
44
+ @patch('colorama.ansitowin32.enable_vt_processing', lambda *_: False)
45
+ def testInitWrapsOnWindows(self, _):
46
+ with osname("nt"):
47
+ init()
48
+ self.assertWrapped()
49
+
50
+ @patch('colorama.initialise.reset_all')
51
+ @patch('colorama.ansitowin32.winapi_test', lambda *_: False)
52
+ def testInitDoesntWrapOnEmulatedWindows(self, _):
53
+ with osname("nt"):
54
+ init()
55
+ self.assertNotWrapped()
56
+
57
+ def testInitDoesntWrapOnNonWindows(self):
58
+ with osname("posix"):
59
+ init()
60
+ self.assertNotWrapped()
61
+
62
+ def testInitDoesntWrapIfNone(self):
63
+ with replace_by(None):
64
+ init()
65
+ # We can't use assertNotWrapped here because replace_by(None)
66
+ # changes stdout/stderr already.
67
+ self.assertIsNone(sys.stdout)
68
+ self.assertIsNone(sys.stderr)
69
+
70
+ def testInitAutoresetOnWrapsOnAllPlatforms(self):
71
+ with osname("posix"):
72
+ init(autoreset=True)
73
+ self.assertWrapped()
74
+
75
+ def testInitWrapOffDoesntWrapOnWindows(self):
76
+ with osname("nt"):
77
+ init(wrap=False)
78
+ self.assertNotWrapped()
79
+
80
+ def testInitWrapOffIncompatibleWithAutoresetOn(self):
81
+ self.assertRaises(ValueError, lambda: init(autoreset=True, wrap=False))
82
+
83
+ @patch('colorama.win32.SetConsoleTextAttribute')
84
+ @patch('colorama.initialise.AnsiToWin32')
85
+ def testAutoResetPassedOn(self, mockATW32, _):
86
+ with osname("nt"):
87
+ init(autoreset=True)
88
+ self.assertEqual(len(mockATW32.call_args_list), 2)
89
+ self.assertEqual(mockATW32.call_args_list[1][1]['autoreset'], True)
90
+ self.assertEqual(mockATW32.call_args_list[0][1]['autoreset'], True)
91
+
92
+ @patch('colorama.initialise.AnsiToWin32')
93
+ def testAutoResetChangeable(self, mockATW32):
94
+ with osname("nt"):
95
+ init()
96
+
97
+ init(autoreset=True)
98
+ self.assertEqual(len(mockATW32.call_args_list), 4)
99
+ self.assertEqual(mockATW32.call_args_list[2][1]['autoreset'], True)
100
+ self.assertEqual(mockATW32.call_args_list[3][1]['autoreset'], True)
101
+
102
+ init()
103
+ self.assertEqual(len(mockATW32.call_args_list), 6)
104
+ self.assertEqual(
105
+ mockATW32.call_args_list[4][1]['autoreset'], False)
106
+ self.assertEqual(
107
+ mockATW32.call_args_list[5][1]['autoreset'], False)
108
+
109
+
110
+ @patch('colorama.initialise.atexit.register')
111
+ def testAtexitRegisteredOnlyOnce(self, mockRegister):
112
+ init()
113
+ self.assertTrue(mockRegister.called)
114
+ mockRegister.reset_mock()
115
+ init()
116
+ self.assertFalse(mockRegister.called)
117
+
118
+
119
+ class JustFixWindowsConsoleTest(TestCase):
120
+ def _reset(self):
121
+ _wipe_internal_state_for_tests()
122
+ sys.stdout = orig_stdout
123
+ sys.stderr = orig_stderr
124
+
125
+ def tearDown(self):
126
+ self._reset()
127
+
128
+ @patch("colorama.ansitowin32.winapi_test", lambda: True)
129
+ def testJustFixWindowsConsole(self):
130
+ if sys.platform != "win32":
131
+ # just_fix_windows_console should be a no-op
132
+ just_fix_windows_console()
133
+ self.assertIs(sys.stdout, orig_stdout)
134
+ self.assertIs(sys.stderr, orig_stderr)
135
+ else:
136
+ def fake_std():
137
+ # Emulate stdout=not a tty, stderr=tty
138
+ # to check that we handle both cases correctly
139
+ stdout = Mock()
140
+ stdout.closed = False
141
+ stdout.isatty.return_value = False
142
+ stdout.fileno.return_value = 1
143
+ sys.stdout = stdout
144
+
145
+ stderr = Mock()
146
+ stderr.closed = False
147
+ stderr.isatty.return_value = True
148
+ stderr.fileno.return_value = 2
149
+ sys.stderr = stderr
150
+
151
+ for native_ansi in [False, True]:
152
+ with patch(
153
+ 'colorama.ansitowin32.enable_vt_processing',
154
+ lambda *_: native_ansi
155
+ ):
156
+ self._reset()
157
+ fake_std()
158
+
159
+ # Regular single-call test
160
+ prev_stdout = sys.stdout
161
+ prev_stderr = sys.stderr
162
+ just_fix_windows_console()
163
+ self.assertIs(sys.stdout, prev_stdout)
164
+ if native_ansi:
165
+ self.assertIs(sys.stderr, prev_stderr)
166
+ else:
167
+ self.assertIsNot(sys.stderr, prev_stderr)
168
+
169
+ # second call without resetting is always a no-op
170
+ prev_stdout = sys.stdout
171
+ prev_stderr = sys.stderr
172
+ just_fix_windows_console()
173
+ self.assertIs(sys.stdout, prev_stdout)
174
+ self.assertIs(sys.stderr, prev_stderr)
175
+
176
+ self._reset()
177
+ fake_std()
178
+
179
+ # If init() runs first, just_fix_windows_console should be a no-op
180
+ init()
181
+ prev_stdout = sys.stdout
182
+ prev_stderr = sys.stderr
183
+ just_fix_windows_console()
184
+ self.assertIs(prev_stdout, sys.stdout)
185
+ self.assertIs(prev_stderr, sys.stderr)
186
+
187
+
188
+ if __name__ == '__main__':
189
+ main()
lib/python3.10/site-packages/colorama/tests/isatty_test.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main
4
+
5
+ from ..ansitowin32 import StreamWrapper, AnsiToWin32
6
+ from .utils import pycharm, replace_by, replace_original_by, StreamTTY, StreamNonTTY
7
+
8
+
9
+ def is_a_tty(stream):
10
+ return StreamWrapper(stream, None).isatty()
11
+
12
+ class IsattyTest(TestCase):
13
+
14
+ def test_TTY(self):
15
+ tty = StreamTTY()
16
+ self.assertTrue(is_a_tty(tty))
17
+ with pycharm():
18
+ self.assertTrue(is_a_tty(tty))
19
+
20
+ def test_nonTTY(self):
21
+ non_tty = StreamNonTTY()
22
+ self.assertFalse(is_a_tty(non_tty))
23
+ with pycharm():
24
+ self.assertFalse(is_a_tty(non_tty))
25
+
26
+ def test_withPycharm(self):
27
+ with pycharm():
28
+ self.assertTrue(is_a_tty(sys.stderr))
29
+ self.assertTrue(is_a_tty(sys.stdout))
30
+
31
+ def test_withPycharmTTYOverride(self):
32
+ tty = StreamTTY()
33
+ with pycharm(), replace_by(tty):
34
+ self.assertTrue(is_a_tty(tty))
35
+
36
+ def test_withPycharmNonTTYOverride(self):
37
+ non_tty = StreamNonTTY()
38
+ with pycharm(), replace_by(non_tty):
39
+ self.assertFalse(is_a_tty(non_tty))
40
+
41
+ def test_withPycharmNoneOverride(self):
42
+ with pycharm():
43
+ with replace_by(None), replace_original_by(None):
44
+ self.assertFalse(is_a_tty(None))
45
+ self.assertFalse(is_a_tty(StreamNonTTY()))
46
+ self.assertTrue(is_a_tty(StreamTTY()))
47
+
48
+ def test_withPycharmStreamWrapped(self):
49
+ with pycharm():
50
+ self.assertTrue(AnsiToWin32(StreamTTY()).stream.isatty())
51
+ self.assertFalse(AnsiToWin32(StreamNonTTY()).stream.isatty())
52
+ self.assertTrue(AnsiToWin32(sys.stdout).stream.isatty())
53
+ self.assertTrue(AnsiToWin32(sys.stderr).stream.isatty())
54
+
55
+
56
+ if __name__ == '__main__':
57
+ main()
lib/python3.10/site-packages/colorama/tests/utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ from contextlib import contextmanager
3
+ from io import StringIO
4
+ import sys
5
+ import os
6
+
7
+
8
+ class StreamTTY(StringIO):
9
+ def isatty(self):
10
+ return True
11
+
12
+ class StreamNonTTY(StringIO):
13
+ def isatty(self):
14
+ return False
15
+
16
+ @contextmanager
17
+ def osname(name):
18
+ orig = os.name
19
+ os.name = name
20
+ yield
21
+ os.name = orig
22
+
23
+ @contextmanager
24
+ def replace_by(stream):
25
+ orig_stdout = sys.stdout
26
+ orig_stderr = sys.stderr
27
+ sys.stdout = stream
28
+ sys.stderr = stream
29
+ yield
30
+ sys.stdout = orig_stdout
31
+ sys.stderr = orig_stderr
32
+
33
+ @contextmanager
34
+ def replace_original_by(stream):
35
+ orig_stdout = sys.__stdout__
36
+ orig_stderr = sys.__stderr__
37
+ sys.__stdout__ = stream
38
+ sys.__stderr__ = stream
39
+ yield
40
+ sys.__stdout__ = orig_stdout
41
+ sys.__stderr__ = orig_stderr
42
+
43
+ @contextmanager
44
+ def pycharm():
45
+ os.environ["PYCHARM_HOSTED"] = "1"
46
+ non_tty = StreamNonTTY()
47
+ with replace_by(non_tty), replace_original_by(non_tty):
48
+ yield
49
+ del os.environ["PYCHARM_HOSTED"]
lib/python3.10/site-packages/colorama/tests/winterm_test.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main, skipUnless
4
+
5
+ try:
6
+ from unittest.mock import Mock, patch
7
+ except ImportError:
8
+ from mock import Mock, patch
9
+
10
+ from ..winterm import WinColor, WinStyle, WinTerm
11
+
12
+
13
+ class WinTermTest(TestCase):
14
+
15
+ @patch('colorama.winterm.win32')
16
+ def testInit(self, mockWin32):
17
+ mockAttr = Mock()
18
+ mockAttr.wAttributes = 7 + 6 * 16 + 8
19
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
20
+ term = WinTerm()
21
+ self.assertEqual(term._fore, 7)
22
+ self.assertEqual(term._back, 6)
23
+ self.assertEqual(term._style, 8)
24
+
25
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
26
+ def testGetAttrs(self):
27
+ term = WinTerm()
28
+
29
+ term._fore = 0
30
+ term._back = 0
31
+ term._style = 0
32
+ self.assertEqual(term.get_attrs(), 0)
33
+
34
+ term._fore = WinColor.YELLOW
35
+ self.assertEqual(term.get_attrs(), WinColor.YELLOW)
36
+
37
+ term._back = WinColor.MAGENTA
38
+ self.assertEqual(
39
+ term.get_attrs(),
40
+ WinColor.YELLOW + WinColor.MAGENTA * 16)
41
+
42
+ term._style = WinStyle.BRIGHT
43
+ self.assertEqual(
44
+ term.get_attrs(),
45
+ WinColor.YELLOW + WinColor.MAGENTA * 16 + WinStyle.BRIGHT)
46
+
47
+ @patch('colorama.winterm.win32')
48
+ def testResetAll(self, mockWin32):
49
+ mockAttr = Mock()
50
+ mockAttr.wAttributes = 1 + 2 * 16 + 8
51
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
52
+ term = WinTerm()
53
+
54
+ term.set_console = Mock()
55
+ term._fore = -1
56
+ term._back = -1
57
+ term._style = -1
58
+
59
+ term.reset_all()
60
+
61
+ self.assertEqual(term._fore, 1)
62
+ self.assertEqual(term._back, 2)
63
+ self.assertEqual(term._style, 8)
64
+ self.assertEqual(term.set_console.called, True)
65
+
66
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
67
+ def testFore(self):
68
+ term = WinTerm()
69
+ term.set_console = Mock()
70
+ term._fore = 0
71
+
72
+ term.fore(5)
73
+
74
+ self.assertEqual(term._fore, 5)
75
+ self.assertEqual(term.set_console.called, True)
76
+
77
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
78
+ def testBack(self):
79
+ term = WinTerm()
80
+ term.set_console = Mock()
81
+ term._back = 0
82
+
83
+ term.back(5)
84
+
85
+ self.assertEqual(term._back, 5)
86
+ self.assertEqual(term.set_console.called, True)
87
+
88
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
89
+ def testStyle(self):
90
+ term = WinTerm()
91
+ term.set_console = Mock()
92
+ term._style = 0
93
+
94
+ term.style(22)
95
+
96
+ self.assertEqual(term._style, 22)
97
+ self.assertEqual(term.set_console.called, True)
98
+
99
+ @patch('colorama.winterm.win32')
100
+ def testSetConsole(self, mockWin32):
101
+ mockAttr = Mock()
102
+ mockAttr.wAttributes = 0
103
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
104
+ term = WinTerm()
105
+ term.windll = Mock()
106
+
107
+ term.set_console()
108
+
109
+ self.assertEqual(
110
+ mockWin32.SetConsoleTextAttribute.call_args,
111
+ ((mockWin32.STDOUT, term.get_attrs()), {})
112
+ )
113
+
114
+ @patch('colorama.winterm.win32')
115
+ def testSetConsoleOnStderr(self, mockWin32):
116
+ mockAttr = Mock()
117
+ mockAttr.wAttributes = 0
118
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
119
+ term = WinTerm()
120
+ term.windll = Mock()
121
+
122
+ term.set_console(on_stderr=True)
123
+
124
+ self.assertEqual(
125
+ mockWin32.SetConsoleTextAttribute.call_args,
126
+ ((mockWin32.STDERR, term.get_attrs()), {})
127
+ )
128
+
129
+
130
+ if __name__ == '__main__':
131
+ main()
lib/python3.10/site-packages/cryptography/__about__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ __all__ = [
8
+ "__author__",
9
+ "__copyright__",
10
+ "__version__",
11
+ ]
12
+
13
+ __version__ = "44.0.2"
14
+
15
+
16
+ __author__ = "The Python Cryptographic Authority and individual contributors"
17
+ __copyright__ = f"Copyright 2013-2024 {__author__}"
lib/python3.10/site-packages/cryptography/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import sys
8
+ import warnings
9
+
10
+ from cryptography import utils
11
+ from cryptography.__about__ import __author__, __copyright__, __version__
12
+
13
+ __all__ = [
14
+ "__author__",
15
+ "__copyright__",
16
+ "__version__",
17
+ ]
18
+
19
+ if sys.version_info[:2] == (3, 7):
20
+ warnings.warn(
21
+ "Python 3.7 is no longer supported by the Python core team "
22
+ "and support for it is deprecated in cryptography. A future "
23
+ "release of cryptography will remove support for Python 3.7.",
24
+ utils.CryptographyDeprecationWarning,
25
+ stacklevel=2,
26
+ )
lib/python3.10/site-packages/cryptography/exceptions.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from cryptography.hazmat.bindings._rust import exceptions as rust_exceptions
10
+
11
+ if typing.TYPE_CHECKING:
12
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
13
+
14
+ _Reasons = rust_exceptions._Reasons
15
+
16
+
17
+ class UnsupportedAlgorithm(Exception):
18
+ def __init__(self, message: str, reason: _Reasons | None = None) -> None:
19
+ super().__init__(message)
20
+ self._reason = reason
21
+
22
+
23
+ class AlreadyFinalized(Exception):
24
+ pass
25
+
26
+
27
+ class AlreadyUpdated(Exception):
28
+ pass
29
+
30
+
31
+ class NotYetFinalized(Exception):
32
+ pass
33
+
34
+
35
+ class InvalidTag(Exception):
36
+ pass
37
+
38
+
39
+ class InvalidSignature(Exception):
40
+ pass
41
+
42
+
43
+ class InternalError(Exception):
44
+ def __init__(
45
+ self, msg: str, err_code: list[rust_openssl.OpenSSLError]
46
+ ) -> None:
47
+ super().__init__(msg)
48
+ self.err_code = err_code
49
+
50
+
51
+ class InvalidKey(Exception):
52
+ pass
lib/python3.10/site-packages/cryptography/fernet.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+ import binascii
9
+ import os
10
+ import time
11
+ import typing
12
+
13
+ from cryptography import utils
14
+ from cryptography.exceptions import InvalidSignature
15
+ from cryptography.hazmat.primitives import hashes, padding
16
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
17
+ from cryptography.hazmat.primitives.hmac import HMAC
18
+
19
+
20
+ class InvalidToken(Exception):
21
+ pass
22
+
23
+
24
+ _MAX_CLOCK_SKEW = 60
25
+
26
+
27
+ class Fernet:
28
+ def __init__(
29
+ self,
30
+ key: bytes | str,
31
+ backend: typing.Any = None,
32
+ ) -> None:
33
+ try:
34
+ key = base64.urlsafe_b64decode(key)
35
+ except binascii.Error as exc:
36
+ raise ValueError(
37
+ "Fernet key must be 32 url-safe base64-encoded bytes."
38
+ ) from exc
39
+ if len(key) != 32:
40
+ raise ValueError(
41
+ "Fernet key must be 32 url-safe base64-encoded bytes."
42
+ )
43
+
44
+ self._signing_key = key[:16]
45
+ self._encryption_key = key[16:]
46
+
47
+ @classmethod
48
+ def generate_key(cls) -> bytes:
49
+ return base64.urlsafe_b64encode(os.urandom(32))
50
+
51
+ def encrypt(self, data: bytes) -> bytes:
52
+ return self.encrypt_at_time(data, int(time.time()))
53
+
54
+ def encrypt_at_time(self, data: bytes, current_time: int) -> bytes:
55
+ iv = os.urandom(16)
56
+ return self._encrypt_from_parts(data, current_time, iv)
57
+
58
+ def _encrypt_from_parts(
59
+ self, data: bytes, current_time: int, iv: bytes
60
+ ) -> bytes:
61
+ utils._check_bytes("data", data)
62
+
63
+ padder = padding.PKCS7(algorithms.AES.block_size).padder()
64
+ padded_data = padder.update(data) + padder.finalize()
65
+ encryptor = Cipher(
66
+ algorithms.AES(self._encryption_key),
67
+ modes.CBC(iv),
68
+ ).encryptor()
69
+ ciphertext = encryptor.update(padded_data) + encryptor.finalize()
70
+
71
+ basic_parts = (
72
+ b"\x80"
73
+ + current_time.to_bytes(length=8, byteorder="big")
74
+ + iv
75
+ + ciphertext
76
+ )
77
+
78
+ h = HMAC(self._signing_key, hashes.SHA256())
79
+ h.update(basic_parts)
80
+ hmac = h.finalize()
81
+ return base64.urlsafe_b64encode(basic_parts + hmac)
82
+
83
+ def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes:
84
+ timestamp, data = Fernet._get_unverified_token_data(token)
85
+ if ttl is None:
86
+ time_info = None
87
+ else:
88
+ time_info = (ttl, int(time.time()))
89
+ return self._decrypt_data(data, timestamp, time_info)
90
+
91
+ def decrypt_at_time(
92
+ self, token: bytes | str, ttl: int, current_time: int
93
+ ) -> bytes:
94
+ if ttl is None:
95
+ raise ValueError(
96
+ "decrypt_at_time() can only be used with a non-None ttl"
97
+ )
98
+ timestamp, data = Fernet._get_unverified_token_data(token)
99
+ return self._decrypt_data(data, timestamp, (ttl, current_time))
100
+
101
+ def extract_timestamp(self, token: bytes | str) -> int:
102
+ timestamp, data = Fernet._get_unverified_token_data(token)
103
+ # Verify the token was not tampered with.
104
+ self._verify_signature(data)
105
+ return timestamp
106
+
107
+ @staticmethod
108
+ def _get_unverified_token_data(token: bytes | str) -> tuple[int, bytes]:
109
+ if not isinstance(token, (str, bytes)):
110
+ raise TypeError("token must be bytes or str")
111
+
112
+ try:
113
+ data = base64.urlsafe_b64decode(token)
114
+ except (TypeError, binascii.Error):
115
+ raise InvalidToken
116
+
117
+ if not data or data[0] != 0x80:
118
+ raise InvalidToken
119
+
120
+ if len(data) < 9:
121
+ raise InvalidToken
122
+
123
+ timestamp = int.from_bytes(data[1:9], byteorder="big")
124
+ return timestamp, data
125
+
126
+ def _verify_signature(self, data: bytes) -> None:
127
+ h = HMAC(self._signing_key, hashes.SHA256())
128
+ h.update(data[:-32])
129
+ try:
130
+ h.verify(data[-32:])
131
+ except InvalidSignature:
132
+ raise InvalidToken
133
+
134
+ def _decrypt_data(
135
+ self,
136
+ data: bytes,
137
+ timestamp: int,
138
+ time_info: tuple[int, int] | None,
139
+ ) -> bytes:
140
+ if time_info is not None:
141
+ ttl, current_time = time_info
142
+ if timestamp + ttl < current_time:
143
+ raise InvalidToken
144
+
145
+ if current_time + _MAX_CLOCK_SKEW < timestamp:
146
+ raise InvalidToken
147
+
148
+ self._verify_signature(data)
149
+
150
+ iv = data[9:25]
151
+ ciphertext = data[25:-32]
152
+ decryptor = Cipher(
153
+ algorithms.AES(self._encryption_key), modes.CBC(iv)
154
+ ).decryptor()
155
+ plaintext_padded = decryptor.update(ciphertext)
156
+ try:
157
+ plaintext_padded += decryptor.finalize()
158
+ except ValueError:
159
+ raise InvalidToken
160
+ unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
161
+
162
+ unpadded = unpadder.update(plaintext_padded)
163
+ try:
164
+ unpadded += unpadder.finalize()
165
+ except ValueError:
166
+ raise InvalidToken
167
+ return unpadded
168
+
169
+
170
+ class MultiFernet:
171
+ def __init__(self, fernets: typing.Iterable[Fernet]):
172
+ fernets = list(fernets)
173
+ if not fernets:
174
+ raise ValueError(
175
+ "MultiFernet requires at least one Fernet instance"
176
+ )
177
+ self._fernets = fernets
178
+
179
+ def encrypt(self, msg: bytes) -> bytes:
180
+ return self.encrypt_at_time(msg, int(time.time()))
181
+
182
+ def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes:
183
+ return self._fernets[0].encrypt_at_time(msg, current_time)
184
+
185
+ def rotate(self, msg: bytes | str) -> bytes:
186
+ timestamp, data = Fernet._get_unverified_token_data(msg)
187
+ for f in self._fernets:
188
+ try:
189
+ p = f._decrypt_data(data, timestamp, None)
190
+ break
191
+ except InvalidToken:
192
+ pass
193
+ else:
194
+ raise InvalidToken
195
+
196
+ iv = os.urandom(16)
197
+ return self._fernets[0]._encrypt_from_parts(p, timestamp, iv)
198
+
199
+ def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes:
200
+ for f in self._fernets:
201
+ try:
202
+ return f.decrypt(msg, ttl)
203
+ except InvalidToken:
204
+ pass
205
+ raise InvalidToken
206
+
207
+ def decrypt_at_time(
208
+ self, msg: bytes | str, ttl: int, current_time: int
209
+ ) -> bytes:
210
+ for f in self._fernets:
211
+ try:
212
+ return f.decrypt_at_time(msg, ttl, current_time)
213
+ except InvalidToken:
214
+ pass
215
+ raise InvalidToken
216
+
217
+ def extract_timestamp(self, msg: bytes | str) -> int:
218
+ for f in self._fernets:
219
+ try:
220
+ return f.extract_timestamp(msg)
221
+ except InvalidToken:
222
+ pass
223
+ raise InvalidToken
lib/python3.10/site-packages/cryptography/hazmat/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ """
8
+ Hazardous Materials
9
+
10
+ This is a "Hazardous Materials" module. You should ONLY use it if you're
11
+ 100% absolutely sure that you know what you're doing because this module
12
+ is full of land mines, dragons, and dinosaurs with laser guns.
13
+ """
lib/python3.10/site-packages/cryptography/hazmat/_oid.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.bindings._rust import (
8
+ ObjectIdentifier as ObjectIdentifier,
9
+ )
10
+ from cryptography.hazmat.primitives import hashes
11
+
12
+
13
+ class ExtensionOID:
14
+ SUBJECT_DIRECTORY_ATTRIBUTES = ObjectIdentifier("2.5.29.9")
15
+ SUBJECT_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.14")
16
+ KEY_USAGE = ObjectIdentifier("2.5.29.15")
17
+ SUBJECT_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.17")
18
+ ISSUER_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.18")
19
+ BASIC_CONSTRAINTS = ObjectIdentifier("2.5.29.19")
20
+ NAME_CONSTRAINTS = ObjectIdentifier("2.5.29.30")
21
+ CRL_DISTRIBUTION_POINTS = ObjectIdentifier("2.5.29.31")
22
+ CERTIFICATE_POLICIES = ObjectIdentifier("2.5.29.32")
23
+ POLICY_MAPPINGS = ObjectIdentifier("2.5.29.33")
24
+ AUTHORITY_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.35")
25
+ POLICY_CONSTRAINTS = ObjectIdentifier("2.5.29.36")
26
+ EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37")
27
+ FRESHEST_CRL = ObjectIdentifier("2.5.29.46")
28
+ INHIBIT_ANY_POLICY = ObjectIdentifier("2.5.29.54")
29
+ ISSUING_DISTRIBUTION_POINT = ObjectIdentifier("2.5.29.28")
30
+ AUTHORITY_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.1")
31
+ SUBJECT_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.11")
32
+ OCSP_NO_CHECK = ObjectIdentifier("1.3.6.1.5.5.7.48.1.5")
33
+ TLS_FEATURE = ObjectIdentifier("1.3.6.1.5.5.7.1.24")
34
+ CRL_NUMBER = ObjectIdentifier("2.5.29.20")
35
+ DELTA_CRL_INDICATOR = ObjectIdentifier("2.5.29.27")
36
+ PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier(
37
+ "1.3.6.1.4.1.11129.2.4.2"
38
+ )
39
+ PRECERT_POISON = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.3")
40
+ SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.5")
41
+ MS_CERTIFICATE_TEMPLATE = ObjectIdentifier("1.3.6.1.4.1.311.21.7")
42
+ ADMISSIONS = ObjectIdentifier("1.3.36.8.3.3")
43
+
44
+
45
+ class OCSPExtensionOID:
46
+ NONCE = ObjectIdentifier("1.3.6.1.5.5.7.48.1.2")
47
+ ACCEPTABLE_RESPONSES = ObjectIdentifier("1.3.6.1.5.5.7.48.1.4")
48
+
49
+
50
+ class CRLEntryExtensionOID:
51
+ CERTIFICATE_ISSUER = ObjectIdentifier("2.5.29.29")
52
+ CRL_REASON = ObjectIdentifier("2.5.29.21")
53
+ INVALIDITY_DATE = ObjectIdentifier("2.5.29.24")
54
+
55
+
56
+ class NameOID:
57
+ COMMON_NAME = ObjectIdentifier("2.5.4.3")
58
+ COUNTRY_NAME = ObjectIdentifier("2.5.4.6")
59
+ LOCALITY_NAME = ObjectIdentifier("2.5.4.7")
60
+ STATE_OR_PROVINCE_NAME = ObjectIdentifier("2.5.4.8")
61
+ STREET_ADDRESS = ObjectIdentifier("2.5.4.9")
62
+ ORGANIZATION_IDENTIFIER = ObjectIdentifier("2.5.4.97")
63
+ ORGANIZATION_NAME = ObjectIdentifier("2.5.4.10")
64
+ ORGANIZATIONAL_UNIT_NAME = ObjectIdentifier("2.5.4.11")
65
+ SERIAL_NUMBER = ObjectIdentifier("2.5.4.5")
66
+ SURNAME = ObjectIdentifier("2.5.4.4")
67
+ GIVEN_NAME = ObjectIdentifier("2.5.4.42")
68
+ TITLE = ObjectIdentifier("2.5.4.12")
69
+ INITIALS = ObjectIdentifier("2.5.4.43")
70
+ GENERATION_QUALIFIER = ObjectIdentifier("2.5.4.44")
71
+ X500_UNIQUE_IDENTIFIER = ObjectIdentifier("2.5.4.45")
72
+ DN_QUALIFIER = ObjectIdentifier("2.5.4.46")
73
+ PSEUDONYM = ObjectIdentifier("2.5.4.65")
74
+ USER_ID = ObjectIdentifier("0.9.2342.19200300.100.1.1")
75
+ DOMAIN_COMPONENT = ObjectIdentifier("0.9.2342.19200300.100.1.25")
76
+ EMAIL_ADDRESS = ObjectIdentifier("1.2.840.113549.1.9.1")
77
+ JURISDICTION_COUNTRY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.3")
78
+ JURISDICTION_LOCALITY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.1")
79
+ JURISDICTION_STATE_OR_PROVINCE_NAME = ObjectIdentifier(
80
+ "1.3.6.1.4.1.311.60.2.1.2"
81
+ )
82
+ BUSINESS_CATEGORY = ObjectIdentifier("2.5.4.15")
83
+ POSTAL_ADDRESS = ObjectIdentifier("2.5.4.16")
84
+ POSTAL_CODE = ObjectIdentifier("2.5.4.17")
85
+ INN = ObjectIdentifier("1.2.643.3.131.1.1")
86
+ OGRN = ObjectIdentifier("1.2.643.100.1")
87
+ SNILS = ObjectIdentifier("1.2.643.100.3")
88
+ UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2")
89
+
90
+
91
+ class SignatureAlgorithmOID:
92
+ RSA_WITH_MD5 = ObjectIdentifier("1.2.840.113549.1.1.4")
93
+ RSA_WITH_SHA1 = ObjectIdentifier("1.2.840.113549.1.1.5")
94
+ # This is an alternate OID for RSA with SHA1 that is occasionally seen
95
+ _RSA_WITH_SHA1 = ObjectIdentifier("1.3.14.3.2.29")
96
+ RSA_WITH_SHA224 = ObjectIdentifier("1.2.840.113549.1.1.14")
97
+ RSA_WITH_SHA256 = ObjectIdentifier("1.2.840.113549.1.1.11")
98
+ RSA_WITH_SHA384 = ObjectIdentifier("1.2.840.113549.1.1.12")
99
+ RSA_WITH_SHA512 = ObjectIdentifier("1.2.840.113549.1.1.13")
100
+ RSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.13")
101
+ RSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.14")
102
+ RSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.15")
103
+ RSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.16")
104
+ RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10")
105
+ ECDSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10045.4.1")
106
+ ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1")
107
+ ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2")
108
+ ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3")
109
+ ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4")
110
+ ECDSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.9")
111
+ ECDSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.10")
112
+ ECDSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.11")
113
+ ECDSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.12")
114
+ DSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10040.4.3")
115
+ DSA_WITH_SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.3.1")
116
+ DSA_WITH_SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.3.2")
117
+ DSA_WITH_SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.3.3")
118
+ DSA_WITH_SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.3.4")
119
+ ED25519 = ObjectIdentifier("1.3.101.112")
120
+ ED448 = ObjectIdentifier("1.3.101.113")
121
+ GOSTR3411_94_WITH_3410_2001 = ObjectIdentifier("1.2.643.2.2.3")
122
+ GOSTR3410_2012_WITH_3411_2012_256 = ObjectIdentifier("1.2.643.7.1.1.3.2")
123
+ GOSTR3410_2012_WITH_3411_2012_512 = ObjectIdentifier("1.2.643.7.1.1.3.3")
124
+
125
+
126
+ _SIG_OIDS_TO_HASH: dict[ObjectIdentifier, hashes.HashAlgorithm | None] = {
127
+ SignatureAlgorithmOID.RSA_WITH_MD5: hashes.MD5(),
128
+ SignatureAlgorithmOID.RSA_WITH_SHA1: hashes.SHA1(),
129
+ SignatureAlgorithmOID._RSA_WITH_SHA1: hashes.SHA1(),
130
+ SignatureAlgorithmOID.RSA_WITH_SHA224: hashes.SHA224(),
131
+ SignatureAlgorithmOID.RSA_WITH_SHA256: hashes.SHA256(),
132
+ SignatureAlgorithmOID.RSA_WITH_SHA384: hashes.SHA384(),
133
+ SignatureAlgorithmOID.RSA_WITH_SHA512: hashes.SHA512(),
134
+ SignatureAlgorithmOID.RSA_WITH_SHA3_224: hashes.SHA3_224(),
135
+ SignatureAlgorithmOID.RSA_WITH_SHA3_256: hashes.SHA3_256(),
136
+ SignatureAlgorithmOID.RSA_WITH_SHA3_384: hashes.SHA3_384(),
137
+ SignatureAlgorithmOID.RSA_WITH_SHA3_512: hashes.SHA3_512(),
138
+ SignatureAlgorithmOID.ECDSA_WITH_SHA1: hashes.SHA1(),
139
+ SignatureAlgorithmOID.ECDSA_WITH_SHA224: hashes.SHA224(),
140
+ SignatureAlgorithmOID.ECDSA_WITH_SHA256: hashes.SHA256(),
141
+ SignatureAlgorithmOID.ECDSA_WITH_SHA384: hashes.SHA384(),
142
+ SignatureAlgorithmOID.ECDSA_WITH_SHA512: hashes.SHA512(),
143
+ SignatureAlgorithmOID.ECDSA_WITH_SHA3_224: hashes.SHA3_224(),
144
+ SignatureAlgorithmOID.ECDSA_WITH_SHA3_256: hashes.SHA3_256(),
145
+ SignatureAlgorithmOID.ECDSA_WITH_SHA3_384: hashes.SHA3_384(),
146
+ SignatureAlgorithmOID.ECDSA_WITH_SHA3_512: hashes.SHA3_512(),
147
+ SignatureAlgorithmOID.DSA_WITH_SHA1: hashes.SHA1(),
148
+ SignatureAlgorithmOID.DSA_WITH_SHA224: hashes.SHA224(),
149
+ SignatureAlgorithmOID.DSA_WITH_SHA256: hashes.SHA256(),
150
+ SignatureAlgorithmOID.ED25519: None,
151
+ SignatureAlgorithmOID.ED448: None,
152
+ SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: None,
153
+ SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: None,
154
+ SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: None,
155
+ }
156
+
157
+
158
+ class PublicKeyAlgorithmOID:
159
+ DSA = ObjectIdentifier("1.2.840.10040.4.1")
160
+ EC_PUBLIC_KEY = ObjectIdentifier("1.2.840.10045.2.1")
161
+ RSAES_PKCS1_v1_5 = ObjectIdentifier("1.2.840.113549.1.1.1")
162
+ RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10")
163
+ X25519 = ObjectIdentifier("1.3.101.110")
164
+ X448 = ObjectIdentifier("1.3.101.111")
165
+ ED25519 = ObjectIdentifier("1.3.101.112")
166
+ ED448 = ObjectIdentifier("1.3.101.113")
167
+
168
+
169
+ class ExtendedKeyUsageOID:
170
+ SERVER_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.1")
171
+ CLIENT_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.2")
172
+ CODE_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.3")
173
+ EMAIL_PROTECTION = ObjectIdentifier("1.3.6.1.5.5.7.3.4")
174
+ TIME_STAMPING = ObjectIdentifier("1.3.6.1.5.5.7.3.8")
175
+ OCSP_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.9")
176
+ ANY_EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37.0")
177
+ SMARTCARD_LOGON = ObjectIdentifier("1.3.6.1.4.1.311.20.2.2")
178
+ KERBEROS_PKINIT_KDC = ObjectIdentifier("1.3.6.1.5.2.3.5")
179
+ IPSEC_IKE = ObjectIdentifier("1.3.6.1.5.5.7.3.17")
180
+ CERTIFICATE_TRANSPARENCY = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.4")
181
+
182
+
183
+ class AuthorityInformationAccessOID:
184
+ CA_ISSUERS = ObjectIdentifier("1.3.6.1.5.5.7.48.2")
185
+ OCSP = ObjectIdentifier("1.3.6.1.5.5.7.48.1")
186
+
187
+
188
+ class SubjectInformationAccessOID:
189
+ CA_REPOSITORY = ObjectIdentifier("1.3.6.1.5.5.7.48.5")
190
+
191
+
192
+ class CertificatePoliciesOID:
193
+ CPS_QUALIFIER = ObjectIdentifier("1.3.6.1.5.5.7.2.1")
194
+ CPS_USER_NOTICE = ObjectIdentifier("1.3.6.1.5.5.7.2.2")
195
+ ANY_POLICY = ObjectIdentifier("2.5.29.32.0")
196
+
197
+
198
+ class AttributeOID:
199
+ CHALLENGE_PASSWORD = ObjectIdentifier("1.2.840.113549.1.9.7")
200
+ UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2")
201
+
202
+
203
+ _OID_NAMES = {
204
+ NameOID.COMMON_NAME: "commonName",
205
+ NameOID.COUNTRY_NAME: "countryName",
206
+ NameOID.LOCALITY_NAME: "localityName",
207
+ NameOID.STATE_OR_PROVINCE_NAME: "stateOrProvinceName",
208
+ NameOID.STREET_ADDRESS: "streetAddress",
209
+ NameOID.ORGANIZATION_NAME: "organizationName",
210
+ NameOID.ORGANIZATIONAL_UNIT_NAME: "organizationalUnitName",
211
+ NameOID.SERIAL_NUMBER: "serialNumber",
212
+ NameOID.SURNAME: "surname",
213
+ NameOID.GIVEN_NAME: "givenName",
214
+ NameOID.TITLE: "title",
215
+ NameOID.GENERATION_QUALIFIER: "generationQualifier",
216
+ NameOID.X500_UNIQUE_IDENTIFIER: "x500UniqueIdentifier",
217
+ NameOID.DN_QUALIFIER: "dnQualifier",
218
+ NameOID.PSEUDONYM: "pseudonym",
219
+ NameOID.USER_ID: "userID",
220
+ NameOID.DOMAIN_COMPONENT: "domainComponent",
221
+ NameOID.EMAIL_ADDRESS: "emailAddress",
222
+ NameOID.JURISDICTION_COUNTRY_NAME: "jurisdictionCountryName",
223
+ NameOID.JURISDICTION_LOCALITY_NAME: "jurisdictionLocalityName",
224
+ NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME: (
225
+ "jurisdictionStateOrProvinceName"
226
+ ),
227
+ NameOID.BUSINESS_CATEGORY: "businessCategory",
228
+ NameOID.POSTAL_ADDRESS: "postalAddress",
229
+ NameOID.POSTAL_CODE: "postalCode",
230
+ NameOID.INN: "INN",
231
+ NameOID.OGRN: "OGRN",
232
+ NameOID.SNILS: "SNILS",
233
+ NameOID.UNSTRUCTURED_NAME: "unstructuredName",
234
+ SignatureAlgorithmOID.RSA_WITH_MD5: "md5WithRSAEncryption",
235
+ SignatureAlgorithmOID.RSA_WITH_SHA1: "sha1WithRSAEncryption",
236
+ SignatureAlgorithmOID.RSA_WITH_SHA224: "sha224WithRSAEncryption",
237
+ SignatureAlgorithmOID.RSA_WITH_SHA256: "sha256WithRSAEncryption",
238
+ SignatureAlgorithmOID.RSA_WITH_SHA384: "sha384WithRSAEncryption",
239
+ SignatureAlgorithmOID.RSA_WITH_SHA512: "sha512WithRSAEncryption",
240
+ SignatureAlgorithmOID.RSASSA_PSS: "RSASSA-PSS",
241
+ SignatureAlgorithmOID.ECDSA_WITH_SHA1: "ecdsa-with-SHA1",
242
+ SignatureAlgorithmOID.ECDSA_WITH_SHA224: "ecdsa-with-SHA224",
243
+ SignatureAlgorithmOID.ECDSA_WITH_SHA256: "ecdsa-with-SHA256",
244
+ SignatureAlgorithmOID.ECDSA_WITH_SHA384: "ecdsa-with-SHA384",
245
+ SignatureAlgorithmOID.ECDSA_WITH_SHA512: "ecdsa-with-SHA512",
246
+ SignatureAlgorithmOID.DSA_WITH_SHA1: "dsa-with-sha1",
247
+ SignatureAlgorithmOID.DSA_WITH_SHA224: "dsa-with-sha224",
248
+ SignatureAlgorithmOID.DSA_WITH_SHA256: "dsa-with-sha256",
249
+ SignatureAlgorithmOID.ED25519: "ed25519",
250
+ SignatureAlgorithmOID.ED448: "ed448",
251
+ SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: (
252
+ "GOST R 34.11-94 with GOST R 34.10-2001"
253
+ ),
254
+ SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: (
255
+ "GOST R 34.10-2012 with GOST R 34.11-2012 (256 bit)"
256
+ ),
257
+ SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: (
258
+ "GOST R 34.10-2012 with GOST R 34.11-2012 (512 bit)"
259
+ ),
260
+ PublicKeyAlgorithmOID.DSA: "dsaEncryption",
261
+ PublicKeyAlgorithmOID.EC_PUBLIC_KEY: "id-ecPublicKey",
262
+ PublicKeyAlgorithmOID.RSAES_PKCS1_v1_5: "rsaEncryption",
263
+ PublicKeyAlgorithmOID.RSASSA_PSS: "rsassaPss",
264
+ PublicKeyAlgorithmOID.X25519: "X25519",
265
+ PublicKeyAlgorithmOID.X448: "X448",
266
+ ExtendedKeyUsageOID.SERVER_AUTH: "serverAuth",
267
+ ExtendedKeyUsageOID.CLIENT_AUTH: "clientAuth",
268
+ ExtendedKeyUsageOID.CODE_SIGNING: "codeSigning",
269
+ ExtendedKeyUsageOID.EMAIL_PROTECTION: "emailProtection",
270
+ ExtendedKeyUsageOID.TIME_STAMPING: "timeStamping",
271
+ ExtendedKeyUsageOID.OCSP_SIGNING: "OCSPSigning",
272
+ ExtendedKeyUsageOID.SMARTCARD_LOGON: "msSmartcardLogin",
273
+ ExtendedKeyUsageOID.KERBEROS_PKINIT_KDC: "pkInitKDC",
274
+ ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES: "subjectDirectoryAttributes",
275
+ ExtensionOID.SUBJECT_KEY_IDENTIFIER: "subjectKeyIdentifier",
276
+ ExtensionOID.KEY_USAGE: "keyUsage",
277
+ ExtensionOID.SUBJECT_ALTERNATIVE_NAME: "subjectAltName",
278
+ ExtensionOID.ISSUER_ALTERNATIVE_NAME: "issuerAltName",
279
+ ExtensionOID.BASIC_CONSTRAINTS: "basicConstraints",
280
+ ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: (
281
+ "signedCertificateTimestampList"
282
+ ),
283
+ ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS: (
284
+ "signedCertificateTimestampList"
285
+ ),
286
+ ExtensionOID.PRECERT_POISON: "ctPoison",
287
+ ExtensionOID.MS_CERTIFICATE_TEMPLATE: "msCertificateTemplate",
288
+ ExtensionOID.ADMISSIONS: "Admissions",
289
+ CRLEntryExtensionOID.CRL_REASON: "cRLReason",
290
+ CRLEntryExtensionOID.INVALIDITY_DATE: "invalidityDate",
291
+ CRLEntryExtensionOID.CERTIFICATE_ISSUER: "certificateIssuer",
292
+ ExtensionOID.NAME_CONSTRAINTS: "nameConstraints",
293
+ ExtensionOID.CRL_DISTRIBUTION_POINTS: "cRLDistributionPoints",
294
+ ExtensionOID.CERTIFICATE_POLICIES: "certificatePolicies",
295
+ ExtensionOID.POLICY_MAPPINGS: "policyMappings",
296
+ ExtensionOID.AUTHORITY_KEY_IDENTIFIER: "authorityKeyIdentifier",
297
+ ExtensionOID.POLICY_CONSTRAINTS: "policyConstraints",
298
+ ExtensionOID.EXTENDED_KEY_USAGE: "extendedKeyUsage",
299
+ ExtensionOID.FRESHEST_CRL: "freshestCRL",
300
+ ExtensionOID.INHIBIT_ANY_POLICY: "inhibitAnyPolicy",
301
+ ExtensionOID.ISSUING_DISTRIBUTION_POINT: "issuingDistributionPoint",
302
+ ExtensionOID.AUTHORITY_INFORMATION_ACCESS: "authorityInfoAccess",
303
+ ExtensionOID.SUBJECT_INFORMATION_ACCESS: "subjectInfoAccess",
304
+ ExtensionOID.OCSP_NO_CHECK: "OCSPNoCheck",
305
+ ExtensionOID.CRL_NUMBER: "cRLNumber",
306
+ ExtensionOID.DELTA_CRL_INDICATOR: "deltaCRLIndicator",
307
+ ExtensionOID.TLS_FEATURE: "TLSFeature",
308
+ AuthorityInformationAccessOID.OCSP: "OCSP",
309
+ AuthorityInformationAccessOID.CA_ISSUERS: "caIssuers",
310
+ SubjectInformationAccessOID.CA_REPOSITORY: "caRepository",
311
+ CertificatePoliciesOID.CPS_QUALIFIER: "id-qt-cps",
312
+ CertificatePoliciesOID.CPS_USER_NOTICE: "id-qt-unotice",
313
+ OCSPExtensionOID.NONCE: "OCSPNonce",
314
+ AttributeOID.CHALLENGE_PASSWORD: "challengePassword",
315
+ }
lib/python3.10/site-packages/cryptography/hazmat/decrepit/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
lib/python3.10/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
lib/python3.10/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.primitives._cipheralgorithm import (
8
+ BlockCipherAlgorithm,
9
+ CipherAlgorithm,
10
+ _verify_key_size,
11
+ )
12
+
13
+
14
+ class ARC4(CipherAlgorithm):
15
+ name = "RC4"
16
+ key_sizes = frozenset([40, 56, 64, 80, 128, 160, 192, 256])
17
+
18
+ def __init__(self, key: bytes):
19
+ self.key = _verify_key_size(self, key)
20
+
21
+ @property
22
+ def key_size(self) -> int:
23
+ return len(self.key) * 8
24
+
25
+
26
+ class TripleDES(BlockCipherAlgorithm):
27
+ name = "3DES"
28
+ block_size = 64
29
+ key_sizes = frozenset([64, 128, 192])
30
+
31
+ def __init__(self, key: bytes):
32
+ if len(key) == 8:
33
+ key += key + key
34
+ elif len(key) == 16:
35
+ key += key[:8]
36
+ self.key = _verify_key_size(self, key)
37
+
38
+ @property
39
+ def key_size(self) -> int:
40
+ return len(self.key) * 8
41
+
42
+
43
+ class Blowfish(BlockCipherAlgorithm):
44
+ name = "Blowfish"
45
+ block_size = 64
46
+ key_sizes = frozenset(range(32, 449, 8))
47
+
48
+ def __init__(self, key: bytes):
49
+ self.key = _verify_key_size(self, key)
50
+
51
+ @property
52
+ def key_size(self) -> int:
53
+ return len(self.key) * 8
54
+
55
+
56
+ class CAST5(BlockCipherAlgorithm):
57
+ name = "CAST5"
58
+ block_size = 64
59
+ key_sizes = frozenset(range(40, 129, 8))
60
+
61
+ def __init__(self, key: bytes):
62
+ self.key = _verify_key_size(self, key)
63
+
64
+ @property
65
+ def key_size(self) -> int:
66
+ return len(self.key) * 8
67
+
68
+
69
+ class SEED(BlockCipherAlgorithm):
70
+ name = "SEED"
71
+ block_size = 128
72
+ key_sizes = frozenset([128])
73
+
74
+ def __init__(self, key: bytes):
75
+ self.key = _verify_key_size(self, key)
76
+
77
+ @property
78
+ def key_size(self) -> int:
79
+ return len(self.key) * 8
80
+
81
+
82
+ class IDEA(BlockCipherAlgorithm):
83
+ name = "IDEA"
84
+ block_size = 64
85
+ key_sizes = frozenset([128])
86
+
87
+ def __init__(self, key: bytes):
88
+ self.key = _verify_key_size(self, key)
89
+
90
+ @property
91
+ def key_size(self) -> int:
92
+ return len(self.key) * 8
93
+
94
+
95
+ # This class only allows RC2 with a 128-bit key. No support for
96
+ # effective key bits or other key sizes is provided.
97
+ class RC2(BlockCipherAlgorithm):
98
+ name = "RC2"
99
+ block_size = 64
100
+ key_sizes = frozenset([128])
101
+
102
+ def __init__(self, key: bytes):
103
+ self.key = _verify_key_size(self, key)
104
+
105
+ @property
106
+ def key_size(self) -> int:
107
+ return len(self.key) * 8
lib/python3.10/site-packages/cryptography/hazmat/primitives/_serialization.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+
9
+ from cryptography import utils
10
+ from cryptography.hazmat.primitives.hashes import HashAlgorithm
11
+
12
+ # This exists to break an import cycle. These classes are normally accessible
13
+ # from the serialization module.
14
+
15
+
16
+ class PBES(utils.Enum):
17
+ PBESv1SHA1And3KeyTripleDESCBC = "PBESv1 using SHA1 and 3-Key TripleDES"
18
+ PBESv2SHA256AndAES256CBC = "PBESv2 using SHA256 PBKDF2 and AES256 CBC"
19
+
20
+
21
+ class Encoding(utils.Enum):
22
+ PEM = "PEM"
23
+ DER = "DER"
24
+ OpenSSH = "OpenSSH"
25
+ Raw = "Raw"
26
+ X962 = "ANSI X9.62"
27
+ SMIME = "S/MIME"
28
+
29
+
30
+ class PrivateFormat(utils.Enum):
31
+ PKCS8 = "PKCS8"
32
+ TraditionalOpenSSL = "TraditionalOpenSSL"
33
+ Raw = "Raw"
34
+ OpenSSH = "OpenSSH"
35
+ PKCS12 = "PKCS12"
36
+
37
+ def encryption_builder(self) -> KeySerializationEncryptionBuilder:
38
+ if self not in (PrivateFormat.OpenSSH, PrivateFormat.PKCS12):
39
+ raise ValueError(
40
+ "encryption_builder only supported with PrivateFormat.OpenSSH"
41
+ " and PrivateFormat.PKCS12"
42
+ )
43
+ return KeySerializationEncryptionBuilder(self)
44
+
45
+
46
+ class PublicFormat(utils.Enum):
47
+ SubjectPublicKeyInfo = "X.509 subjectPublicKeyInfo with PKCS#1"
48
+ PKCS1 = "Raw PKCS#1"
49
+ OpenSSH = "OpenSSH"
50
+ Raw = "Raw"
51
+ CompressedPoint = "X9.62 Compressed Point"
52
+ UncompressedPoint = "X9.62 Uncompressed Point"
53
+
54
+
55
+ class ParameterFormat(utils.Enum):
56
+ PKCS3 = "PKCS3"
57
+
58
+
59
+ class KeySerializationEncryption(metaclass=abc.ABCMeta):
60
+ pass
61
+
62
+
63
+ class BestAvailableEncryption(KeySerializationEncryption):
64
+ def __init__(self, password: bytes):
65
+ if not isinstance(password, bytes) or len(password) == 0:
66
+ raise ValueError("Password must be 1 or more bytes.")
67
+
68
+ self.password = password
69
+
70
+
71
+ class NoEncryption(KeySerializationEncryption):
72
+ pass
73
+
74
+
75
+ class KeySerializationEncryptionBuilder:
76
+ def __init__(
77
+ self,
78
+ format: PrivateFormat,
79
+ *,
80
+ _kdf_rounds: int | None = None,
81
+ _hmac_hash: HashAlgorithm | None = None,
82
+ _key_cert_algorithm: PBES | None = None,
83
+ ) -> None:
84
+ self._format = format
85
+
86
+ self._kdf_rounds = _kdf_rounds
87
+ self._hmac_hash = _hmac_hash
88
+ self._key_cert_algorithm = _key_cert_algorithm
89
+
90
+ def kdf_rounds(self, rounds: int) -> KeySerializationEncryptionBuilder:
91
+ if self._kdf_rounds is not None:
92
+ raise ValueError("kdf_rounds already set")
93
+
94
+ if not isinstance(rounds, int):
95
+ raise TypeError("kdf_rounds must be an integer")
96
+
97
+ if rounds < 1:
98
+ raise ValueError("kdf_rounds must be a positive integer")
99
+
100
+ return KeySerializationEncryptionBuilder(
101
+ self._format,
102
+ _kdf_rounds=rounds,
103
+ _hmac_hash=self._hmac_hash,
104
+ _key_cert_algorithm=self._key_cert_algorithm,
105
+ )
106
+
107
+ def hmac_hash(
108
+ self, algorithm: HashAlgorithm
109
+ ) -> KeySerializationEncryptionBuilder:
110
+ if self._format is not PrivateFormat.PKCS12:
111
+ raise TypeError(
112
+ "hmac_hash only supported with PrivateFormat.PKCS12"
113
+ )
114
+
115
+ if self._hmac_hash is not None:
116
+ raise ValueError("hmac_hash already set")
117
+ return KeySerializationEncryptionBuilder(
118
+ self._format,
119
+ _kdf_rounds=self._kdf_rounds,
120
+ _hmac_hash=algorithm,
121
+ _key_cert_algorithm=self._key_cert_algorithm,
122
+ )
123
+
124
+ def key_cert_algorithm(
125
+ self, algorithm: PBES
126
+ ) -> KeySerializationEncryptionBuilder:
127
+ if self._format is not PrivateFormat.PKCS12:
128
+ raise TypeError(
129
+ "key_cert_algorithm only supported with "
130
+ "PrivateFormat.PKCS12"
131
+ )
132
+ if self._key_cert_algorithm is not None:
133
+ raise ValueError("key_cert_algorithm already set")
134
+ return KeySerializationEncryptionBuilder(
135
+ self._format,
136
+ _kdf_rounds=self._kdf_rounds,
137
+ _hmac_hash=self._hmac_hash,
138
+ _key_cert_algorithm=algorithm,
139
+ )
140
+
141
+ def build(self, password: bytes) -> KeySerializationEncryption:
142
+ if not isinstance(password, bytes) or len(password) == 0:
143
+ raise ValueError("Password must be 1 or more bytes.")
144
+
145
+ return _KeySerializationEncryption(
146
+ self._format,
147
+ password,
148
+ kdf_rounds=self._kdf_rounds,
149
+ hmac_hash=self._hmac_hash,
150
+ key_cert_algorithm=self._key_cert_algorithm,
151
+ )
152
+
153
+
154
+ class _KeySerializationEncryption(KeySerializationEncryption):
155
+ def __init__(
156
+ self,
157
+ format: PrivateFormat,
158
+ password: bytes,
159
+ *,
160
+ kdf_rounds: int | None,
161
+ hmac_hash: HashAlgorithm | None,
162
+ key_cert_algorithm: PBES | None,
163
+ ):
164
+ self._format = format
165
+ self.password = password
166
+
167
+ self._kdf_rounds = kdf_rounds
168
+ self._hmac_hash = hmac_hash
169
+ self._key_cert_algorithm = key_cert_algorithm
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
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.
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+
9
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
10
+ from cryptography.hazmat.primitives import _serialization
11
+
12
+ generate_parameters = rust_openssl.dh.generate_parameters
13
+
14
+
15
+ DHPrivateNumbers = rust_openssl.dh.DHPrivateNumbers
16
+ DHPublicNumbers = rust_openssl.dh.DHPublicNumbers
17
+ DHParameterNumbers = rust_openssl.dh.DHParameterNumbers
18
+
19
+
20
+ class DHParameters(metaclass=abc.ABCMeta):
21
+ @abc.abstractmethod
22
+ def generate_private_key(self) -> DHPrivateKey:
23
+ """
24
+ Generates and returns a DHPrivateKey.
25
+ """
26
+
27
+ @abc.abstractmethod
28
+ def parameter_bytes(
29
+ self,
30
+ encoding: _serialization.Encoding,
31
+ format: _serialization.ParameterFormat,
32
+ ) -> bytes:
33
+ """
34
+ Returns the parameters serialized as bytes.
35
+ """
36
+
37
+ @abc.abstractmethod
38
+ def parameter_numbers(self) -> DHParameterNumbers:
39
+ """
40
+ Returns a DHParameterNumbers.
41
+ """
42
+
43
+
44
+ DHParametersWithSerialization = DHParameters
45
+ DHParameters.register(rust_openssl.dh.DHParameters)
46
+
47
+
48
+ class DHPublicKey(metaclass=abc.ABCMeta):
49
+ @property
50
+ @abc.abstractmethod
51
+ def key_size(self) -> int:
52
+ """
53
+ The bit length of the prime modulus.
54
+ """
55
+
56
+ @abc.abstractmethod
57
+ def parameters(self) -> DHParameters:
58
+ """
59
+ The DHParameters object associated with this public key.
60
+ """
61
+
62
+ @abc.abstractmethod
63
+ def public_numbers(self) -> DHPublicNumbers:
64
+ """
65
+ Returns a DHPublicNumbers.
66
+ """
67
+
68
+ @abc.abstractmethod
69
+ def public_bytes(
70
+ self,
71
+ encoding: _serialization.Encoding,
72
+ format: _serialization.PublicFormat,
73
+ ) -> bytes:
74
+ """
75
+ Returns the key serialized as bytes.
76
+ """
77
+
78
+ @abc.abstractmethod
79
+ def __eq__(self, other: object) -> bool:
80
+ """
81
+ Checks equality.
82
+ """
83
+
84
+
85
+ DHPublicKeyWithSerialization = DHPublicKey
86
+ DHPublicKey.register(rust_openssl.dh.DHPublicKey)
87
+
88
+
89
+ class DHPrivateKey(metaclass=abc.ABCMeta):
90
+ @property
91
+ @abc.abstractmethod
92
+ def key_size(self) -> int:
93
+ """
94
+ The bit length of the prime modulus.
95
+ """
96
+
97
+ @abc.abstractmethod
98
+ def public_key(self) -> DHPublicKey:
99
+ """
100
+ The DHPublicKey associated with this private key.
101
+ """
102
+
103
+ @abc.abstractmethod
104
+ def parameters(self) -> DHParameters:
105
+ """
106
+ The DHParameters object associated with this private key.
107
+ """
108
+
109
+ @abc.abstractmethod
110
+ def exchange(self, peer_public_key: DHPublicKey) -> bytes:
111
+ """
112
+ Given peer's DHPublicKey, carry out the key exchange and
113
+ return shared key as bytes.
114
+ """
115
+
116
+ @abc.abstractmethod
117
+ def private_numbers(self) -> DHPrivateNumbers:
118
+ """
119
+ Returns a DHPrivateNumbers.
120
+ """
121
+
122
+ @abc.abstractmethod
123
+ def private_bytes(
124
+ self,
125
+ encoding: _serialization.Encoding,
126
+ format: _serialization.PrivateFormat,
127
+ encryption_algorithm: _serialization.KeySerializationEncryption,
128
+ ) -> bytes:
129
+ """
130
+ Returns the key serialized as bytes.
131
+ """
132
+
133
+
134
+ DHPrivateKeyWithSerialization = DHPrivateKey
135
+ DHPrivateKey.register(rust_openssl.dh.DHPrivateKey)
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+ import typing
9
+
10
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
11
+ from cryptography.hazmat.primitives import _serialization, hashes
12
+ from cryptography.hazmat.primitives.asymmetric import utils as asym_utils
13
+
14
+
15
+ class DSAParameters(metaclass=abc.ABCMeta):
16
+ @abc.abstractmethod
17
+ def generate_private_key(self) -> DSAPrivateKey:
18
+ """
19
+ Generates and returns a DSAPrivateKey.
20
+ """
21
+
22
+ @abc.abstractmethod
23
+ def parameter_numbers(self) -> DSAParameterNumbers:
24
+ """
25
+ Returns a DSAParameterNumbers.
26
+ """
27
+
28
+
29
+ DSAParametersWithNumbers = DSAParameters
30
+ DSAParameters.register(rust_openssl.dsa.DSAParameters)
31
+
32
+
33
+ class DSAPrivateKey(metaclass=abc.ABCMeta):
34
+ @property
35
+ @abc.abstractmethod
36
+ def key_size(self) -> int:
37
+ """
38
+ The bit length of the prime modulus.
39
+ """
40
+
41
+ @abc.abstractmethod
42
+ def public_key(self) -> DSAPublicKey:
43
+ """
44
+ The DSAPublicKey associated with this private key.
45
+ """
46
+
47
+ @abc.abstractmethod
48
+ def parameters(self) -> DSAParameters:
49
+ """
50
+ The DSAParameters object associated with this private key.
51
+ """
52
+
53
+ @abc.abstractmethod
54
+ def sign(
55
+ self,
56
+ data: bytes,
57
+ algorithm: asym_utils.Prehashed | hashes.HashAlgorithm,
58
+ ) -> bytes:
59
+ """
60
+ Signs the data
61
+ """
62
+
63
+ @abc.abstractmethod
64
+ def private_numbers(self) -> DSAPrivateNumbers:
65
+ """
66
+ Returns a DSAPrivateNumbers.
67
+ """
68
+
69
+ @abc.abstractmethod
70
+ def private_bytes(
71
+ self,
72
+ encoding: _serialization.Encoding,
73
+ format: _serialization.PrivateFormat,
74
+ encryption_algorithm: _serialization.KeySerializationEncryption,
75
+ ) -> bytes:
76
+ """
77
+ Returns the key serialized as bytes.
78
+ """
79
+
80
+
81
+ DSAPrivateKeyWithSerialization = DSAPrivateKey
82
+ DSAPrivateKey.register(rust_openssl.dsa.DSAPrivateKey)
83
+
84
+
85
+ class DSAPublicKey(metaclass=abc.ABCMeta):
86
+ @property
87
+ @abc.abstractmethod
88
+ def key_size(self) -> int:
89
+ """
90
+ The bit length of the prime modulus.
91
+ """
92
+
93
+ @abc.abstractmethod
94
+ def parameters(self) -> DSAParameters:
95
+ """
96
+ The DSAParameters object associated with this public key.
97
+ """
98
+
99
+ @abc.abstractmethod
100
+ def public_numbers(self) -> DSAPublicNumbers:
101
+ """
102
+ Returns a DSAPublicNumbers.
103
+ """
104
+
105
+ @abc.abstractmethod
106
+ def public_bytes(
107
+ self,
108
+ encoding: _serialization.Encoding,
109
+ format: _serialization.PublicFormat,
110
+ ) -> bytes:
111
+ """
112
+ Returns the key serialized as bytes.
113
+ """
114
+
115
+ @abc.abstractmethod
116
+ def verify(
117
+ self,
118
+ signature: bytes,
119
+ data: bytes,
120
+ algorithm: asym_utils.Prehashed | hashes.HashAlgorithm,
121
+ ) -> None:
122
+ """
123
+ Verifies the signature of the data.
124
+ """
125
+
126
+ @abc.abstractmethod
127
+ def __eq__(self, other: object) -> bool:
128
+ """
129
+ Checks equality.
130
+ """
131
+
132
+
133
+ DSAPublicKeyWithSerialization = DSAPublicKey
134
+ DSAPublicKey.register(rust_openssl.dsa.DSAPublicKey)
135
+
136
+ DSAPrivateNumbers = rust_openssl.dsa.DSAPrivateNumbers
137
+ DSAPublicNumbers = rust_openssl.dsa.DSAPublicNumbers
138
+ DSAParameterNumbers = rust_openssl.dsa.DSAParameterNumbers
139
+
140
+
141
+ def generate_parameters(
142
+ key_size: int, backend: typing.Any = None
143
+ ) -> DSAParameters:
144
+ if key_size not in (1024, 2048, 3072, 4096):
145
+ raise ValueError("Key size must be 1024, 2048, 3072, or 4096 bits.")
146
+
147
+ return rust_openssl.dsa.generate_parameters(key_size)
148
+
149
+
150
+ def generate_private_key(
151
+ key_size: int, backend: typing.Any = None
152
+ ) -> DSAPrivateKey:
153
+ parameters = generate_parameters(key_size)
154
+ return parameters.generate_private_key()
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+ import typing
9
+
10
+ from cryptography import utils
11
+ from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
12
+ from cryptography.hazmat._oid import ObjectIdentifier
13
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
14
+ from cryptography.hazmat.primitives import _serialization, hashes
15
+ from cryptography.hazmat.primitives.asymmetric import utils as asym_utils
16
+
17
+
18
+ class EllipticCurveOID:
19
+ SECP192R1 = ObjectIdentifier("1.2.840.10045.3.1.1")
20
+ SECP224R1 = ObjectIdentifier("1.3.132.0.33")
21
+ SECP256K1 = ObjectIdentifier("1.3.132.0.10")
22
+ SECP256R1 = ObjectIdentifier("1.2.840.10045.3.1.7")
23
+ SECP384R1 = ObjectIdentifier("1.3.132.0.34")
24
+ SECP521R1 = ObjectIdentifier("1.3.132.0.35")
25
+ BRAINPOOLP256R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.7")
26
+ BRAINPOOLP384R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.11")
27
+ BRAINPOOLP512R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.13")
28
+ SECT163K1 = ObjectIdentifier("1.3.132.0.1")
29
+ SECT163R2 = ObjectIdentifier("1.3.132.0.15")
30
+ SECT233K1 = ObjectIdentifier("1.3.132.0.26")
31
+ SECT233R1 = ObjectIdentifier("1.3.132.0.27")
32
+ SECT283K1 = ObjectIdentifier("1.3.132.0.16")
33
+ SECT283R1 = ObjectIdentifier("1.3.132.0.17")
34
+ SECT409K1 = ObjectIdentifier("1.3.132.0.36")
35
+ SECT409R1 = ObjectIdentifier("1.3.132.0.37")
36
+ SECT571K1 = ObjectIdentifier("1.3.132.0.38")
37
+ SECT571R1 = ObjectIdentifier("1.3.132.0.39")
38
+
39
+
40
+ class EllipticCurve(metaclass=abc.ABCMeta):
41
+ @property
42
+ @abc.abstractmethod
43
+ def name(self) -> str:
44
+ """
45
+ The name of the curve. e.g. secp256r1.
46
+ """
47
+
48
+ @property
49
+ @abc.abstractmethod
50
+ def key_size(self) -> int:
51
+ """
52
+ Bit size of a secret scalar for the curve.
53
+ """
54
+
55
+
56
+ class EllipticCurveSignatureAlgorithm(metaclass=abc.ABCMeta):
57
+ @property
58
+ @abc.abstractmethod
59
+ def algorithm(
60
+ self,
61
+ ) -> asym_utils.Prehashed | hashes.HashAlgorithm:
62
+ """
63
+ The digest algorithm used with this signature.
64
+ """
65
+
66
+
67
+ class EllipticCurvePrivateKey(metaclass=abc.ABCMeta):
68
+ @abc.abstractmethod
69
+ def exchange(
70
+ self, algorithm: ECDH, peer_public_key: EllipticCurvePublicKey
71
+ ) -> bytes:
72
+ """
73
+ Performs a key exchange operation using the provided algorithm with the
74
+ provided peer's public key.
75
+ """
76
+
77
+ @abc.abstractmethod
78
+ def public_key(self) -> EllipticCurvePublicKey:
79
+ """
80
+ The EllipticCurvePublicKey for this private key.
81
+ """
82
+
83
+ @property
84
+ @abc.abstractmethod
85
+ def curve(self) -> EllipticCurve:
86
+ """
87
+ The EllipticCurve that this key is on.
88
+ """
89
+
90
+ @property
91
+ @abc.abstractmethod
92
+ def key_size(self) -> int:
93
+ """
94
+ Bit size of a secret scalar for the curve.
95
+ """
96
+
97
+ @abc.abstractmethod
98
+ def sign(
99
+ self,
100
+ data: bytes,
101
+ signature_algorithm: EllipticCurveSignatureAlgorithm,
102
+ ) -> bytes:
103
+ """
104
+ Signs the data
105
+ """
106
+
107
+ @abc.abstractmethod
108
+ def private_numbers(self) -> EllipticCurvePrivateNumbers:
109
+ """
110
+ Returns an EllipticCurvePrivateNumbers.
111
+ """
112
+
113
+ @abc.abstractmethod
114
+ def private_bytes(
115
+ self,
116
+ encoding: _serialization.Encoding,
117
+ format: _serialization.PrivateFormat,
118
+ encryption_algorithm: _serialization.KeySerializationEncryption,
119
+ ) -> bytes:
120
+ """
121
+ Returns the key serialized as bytes.
122
+ """
123
+
124
+
125
+ EllipticCurvePrivateKeyWithSerialization = EllipticCurvePrivateKey
126
+ EllipticCurvePrivateKey.register(rust_openssl.ec.ECPrivateKey)
127
+
128
+
129
+ class EllipticCurvePublicKey(metaclass=abc.ABCMeta):
130
+ @property
131
+ @abc.abstractmethod
132
+ def curve(self) -> EllipticCurve:
133
+ """
134
+ The EllipticCurve that this key is on.
135
+ """
136
+
137
+ @property
138
+ @abc.abstractmethod
139
+ def key_size(self) -> int:
140
+ """
141
+ Bit size of a secret scalar for the curve.
142
+ """
143
+
144
+ @abc.abstractmethod
145
+ def public_numbers(self) -> EllipticCurvePublicNumbers:
146
+ """
147
+ Returns an EllipticCurvePublicNumbers.
148
+ """
149
+
150
+ @abc.abstractmethod
151
+ def public_bytes(
152
+ self,
153
+ encoding: _serialization.Encoding,
154
+ format: _serialization.PublicFormat,
155
+ ) -> bytes:
156
+ """
157
+ Returns the key serialized as bytes.
158
+ """
159
+
160
+ @abc.abstractmethod
161
+ def verify(
162
+ self,
163
+ signature: bytes,
164
+ data: bytes,
165
+ signature_algorithm: EllipticCurveSignatureAlgorithm,
166
+ ) -> None:
167
+ """
168
+ Verifies the signature of the data.
169
+ """
170
+
171
+ @classmethod
172
+ def from_encoded_point(
173
+ cls, curve: EllipticCurve, data: bytes
174
+ ) -> EllipticCurvePublicKey:
175
+ utils._check_bytes("data", data)
176
+
177
+ if len(data) == 0:
178
+ raise ValueError("data must not be an empty byte string")
179
+
180
+ if data[0] not in [0x02, 0x03, 0x04]:
181
+ raise ValueError("Unsupported elliptic curve point type")
182
+
183
+ return rust_openssl.ec.from_public_bytes(curve, data)
184
+
185
+ @abc.abstractmethod
186
+ def __eq__(self, other: object) -> bool:
187
+ """
188
+ Checks equality.
189
+ """
190
+
191
+
192
+ EllipticCurvePublicKeyWithSerialization = EllipticCurvePublicKey
193
+ EllipticCurvePublicKey.register(rust_openssl.ec.ECPublicKey)
194
+
195
+ EllipticCurvePrivateNumbers = rust_openssl.ec.EllipticCurvePrivateNumbers
196
+ EllipticCurvePublicNumbers = rust_openssl.ec.EllipticCurvePublicNumbers
197
+
198
+
199
+ class SECT571R1(EllipticCurve):
200
+ name = "sect571r1"
201
+ key_size = 570
202
+
203
+
204
+ class SECT409R1(EllipticCurve):
205
+ name = "sect409r1"
206
+ key_size = 409
207
+
208
+
209
+ class SECT283R1(EllipticCurve):
210
+ name = "sect283r1"
211
+ key_size = 283
212
+
213
+
214
+ class SECT233R1(EllipticCurve):
215
+ name = "sect233r1"
216
+ key_size = 233
217
+
218
+
219
+ class SECT163R2(EllipticCurve):
220
+ name = "sect163r2"
221
+ key_size = 163
222
+
223
+
224
+ class SECT571K1(EllipticCurve):
225
+ name = "sect571k1"
226
+ key_size = 571
227
+
228
+
229
+ class SECT409K1(EllipticCurve):
230
+ name = "sect409k1"
231
+ key_size = 409
232
+
233
+
234
+ class SECT283K1(EllipticCurve):
235
+ name = "sect283k1"
236
+ key_size = 283
237
+
238
+
239
+ class SECT233K1(EllipticCurve):
240
+ name = "sect233k1"
241
+ key_size = 233
242
+
243
+
244
+ class SECT163K1(EllipticCurve):
245
+ name = "sect163k1"
246
+ key_size = 163
247
+
248
+
249
+ class SECP521R1(EllipticCurve):
250
+ name = "secp521r1"
251
+ key_size = 521
252
+
253
+
254
+ class SECP384R1(EllipticCurve):
255
+ name = "secp384r1"
256
+ key_size = 384
257
+
258
+
259
+ class SECP256R1(EllipticCurve):
260
+ name = "secp256r1"
261
+ key_size = 256
262
+
263
+
264
+ class SECP256K1(EllipticCurve):
265
+ name = "secp256k1"
266
+ key_size = 256
267
+
268
+
269
+ class SECP224R1(EllipticCurve):
270
+ name = "secp224r1"
271
+ key_size = 224
272
+
273
+
274
+ class SECP192R1(EllipticCurve):
275
+ name = "secp192r1"
276
+ key_size = 192
277
+
278
+
279
+ class BrainpoolP256R1(EllipticCurve):
280
+ name = "brainpoolP256r1"
281
+ key_size = 256
282
+
283
+
284
+ class BrainpoolP384R1(EllipticCurve):
285
+ name = "brainpoolP384r1"
286
+ key_size = 384
287
+
288
+
289
+ class BrainpoolP512R1(EllipticCurve):
290
+ name = "brainpoolP512r1"
291
+ key_size = 512
292
+
293
+
294
+ _CURVE_TYPES: dict[str, EllipticCurve] = {
295
+ "prime192v1": SECP192R1(),
296
+ "prime256v1": SECP256R1(),
297
+ "secp192r1": SECP192R1(),
298
+ "secp224r1": SECP224R1(),
299
+ "secp256r1": SECP256R1(),
300
+ "secp384r1": SECP384R1(),
301
+ "secp521r1": SECP521R1(),
302
+ "secp256k1": SECP256K1(),
303
+ "sect163k1": SECT163K1(),
304
+ "sect233k1": SECT233K1(),
305
+ "sect283k1": SECT283K1(),
306
+ "sect409k1": SECT409K1(),
307
+ "sect571k1": SECT571K1(),
308
+ "sect163r2": SECT163R2(),
309
+ "sect233r1": SECT233R1(),
310
+ "sect283r1": SECT283R1(),
311
+ "sect409r1": SECT409R1(),
312
+ "sect571r1": SECT571R1(),
313
+ "brainpoolP256r1": BrainpoolP256R1(),
314
+ "brainpoolP384r1": BrainpoolP384R1(),
315
+ "brainpoolP512r1": BrainpoolP512R1(),
316
+ }
317
+
318
+
319
+ class ECDSA(EllipticCurveSignatureAlgorithm):
320
+ def __init__(
321
+ self,
322
+ algorithm: asym_utils.Prehashed | hashes.HashAlgorithm,
323
+ deterministic_signing: bool = False,
324
+ ):
325
+ from cryptography.hazmat.backends.openssl.backend import backend
326
+
327
+ if (
328
+ deterministic_signing
329
+ and not backend.ecdsa_deterministic_supported()
330
+ ):
331
+ raise UnsupportedAlgorithm(
332
+ "ECDSA with deterministic signature (RFC 6979) is not "
333
+ "supported by this version of OpenSSL.",
334
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
335
+ )
336
+ self._algorithm = algorithm
337
+ self._deterministic_signing = deterministic_signing
338
+
339
+ @property
340
+ def algorithm(
341
+ self,
342
+ ) -> asym_utils.Prehashed | hashes.HashAlgorithm:
343
+ return self._algorithm
344
+
345
+ @property
346
+ def deterministic_signing(
347
+ self,
348
+ ) -> bool:
349
+ return self._deterministic_signing
350
+
351
+
352
+ generate_private_key = rust_openssl.ec.generate_private_key
353
+
354
+
355
+ def derive_private_key(
356
+ private_value: int,
357
+ curve: EllipticCurve,
358
+ backend: typing.Any = None,
359
+ ) -> EllipticCurvePrivateKey:
360
+ if not isinstance(private_value, int):
361
+ raise TypeError("private_value must be an integer type.")
362
+
363
+ if private_value <= 0:
364
+ raise ValueError("private_value must be a positive integer.")
365
+
366
+ return rust_openssl.ec.derive_private_key(private_value, curve)
367
+
368
+
369
+ class ECDH:
370
+ pass
371
+
372
+
373
+ _OID_TO_CURVE = {
374
+ EllipticCurveOID.SECP192R1: SECP192R1,
375
+ EllipticCurveOID.SECP224R1: SECP224R1,
376
+ EllipticCurveOID.SECP256K1: SECP256K1,
377
+ EllipticCurveOID.SECP256R1: SECP256R1,
378
+ EllipticCurveOID.SECP384R1: SECP384R1,
379
+ EllipticCurveOID.SECP521R1: SECP521R1,
380
+ EllipticCurveOID.BRAINPOOLP256R1: BrainpoolP256R1,
381
+ EllipticCurveOID.BRAINPOOLP384R1: BrainpoolP384R1,
382
+ EllipticCurveOID.BRAINPOOLP512R1: BrainpoolP512R1,
383
+ EllipticCurveOID.SECT163K1: SECT163K1,
384
+ EllipticCurveOID.SECT163R2: SECT163R2,
385
+ EllipticCurveOID.SECT233K1: SECT233K1,
386
+ EllipticCurveOID.SECT233R1: SECT233R1,
387
+ EllipticCurveOID.SECT283K1: SECT283K1,
388
+ EllipticCurveOID.SECT283R1: SECT283R1,
389
+ EllipticCurveOID.SECT409K1: SECT409K1,
390
+ EllipticCurveOID.SECT409R1: SECT409R1,
391
+ EllipticCurveOID.SECT571K1: SECT571K1,
392
+ EllipticCurveOID.SECT571R1: SECT571R1,
393
+ }
394
+
395
+
396
+ def get_curve_for_oid(oid: ObjectIdentifier) -> type[EllipticCurve]:
397
+ try:
398
+ return _OID_TO_CURVE[oid]
399
+ except KeyError:
400
+ raise LookupError(
401
+ "The provided object identifier has no matching elliptic "
402
+ "curve class"
403
+ )
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+
9
+ from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
10
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
11
+ from cryptography.hazmat.primitives import _serialization
12
+
13
+
14
+ class Ed25519PublicKey(metaclass=abc.ABCMeta):
15
+ @classmethod
16
+ def from_public_bytes(cls, data: bytes) -> Ed25519PublicKey:
17
+ from cryptography.hazmat.backends.openssl.backend import backend
18
+
19
+ if not backend.ed25519_supported():
20
+ raise UnsupportedAlgorithm(
21
+ "ed25519 is not supported by this version of OpenSSL.",
22
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
23
+ )
24
+
25
+ return rust_openssl.ed25519.from_public_bytes(data)
26
+
27
+ @abc.abstractmethod
28
+ def public_bytes(
29
+ self,
30
+ encoding: _serialization.Encoding,
31
+ format: _serialization.PublicFormat,
32
+ ) -> bytes:
33
+ """
34
+ The serialized bytes of the public key.
35
+ """
36
+
37
+ @abc.abstractmethod
38
+ def public_bytes_raw(self) -> bytes:
39
+ """
40
+ The raw bytes of the public key.
41
+ Equivalent to public_bytes(Raw, Raw).
42
+ """
43
+
44
+ @abc.abstractmethod
45
+ def verify(self, signature: bytes, data: bytes) -> None:
46
+ """
47
+ Verify the signature.
48
+ """
49
+
50
+ @abc.abstractmethod
51
+ def __eq__(self, other: object) -> bool:
52
+ """
53
+ Checks equality.
54
+ """
55
+
56
+
57
+ Ed25519PublicKey.register(rust_openssl.ed25519.Ed25519PublicKey)
58
+
59
+
60
+ class Ed25519PrivateKey(metaclass=abc.ABCMeta):
61
+ @classmethod
62
+ def generate(cls) -> Ed25519PrivateKey:
63
+ from cryptography.hazmat.backends.openssl.backend import backend
64
+
65
+ if not backend.ed25519_supported():
66
+ raise UnsupportedAlgorithm(
67
+ "ed25519 is not supported by this version of OpenSSL.",
68
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
69
+ )
70
+
71
+ return rust_openssl.ed25519.generate_key()
72
+
73
+ @classmethod
74
+ def from_private_bytes(cls, data: bytes) -> Ed25519PrivateKey:
75
+ from cryptography.hazmat.backends.openssl.backend import backend
76
+
77
+ if not backend.ed25519_supported():
78
+ raise UnsupportedAlgorithm(
79
+ "ed25519 is not supported by this version of OpenSSL.",
80
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
81
+ )
82
+
83
+ return rust_openssl.ed25519.from_private_bytes(data)
84
+
85
+ @abc.abstractmethod
86
+ def public_key(self) -> Ed25519PublicKey:
87
+ """
88
+ The Ed25519PublicKey derived from the private key.
89
+ """
90
+
91
+ @abc.abstractmethod
92
+ def private_bytes(
93
+ self,
94
+ encoding: _serialization.Encoding,
95
+ format: _serialization.PrivateFormat,
96
+ encryption_algorithm: _serialization.KeySerializationEncryption,
97
+ ) -> bytes:
98
+ """
99
+ The serialized bytes of the private key.
100
+ """
101
+
102
+ @abc.abstractmethod
103
+ def private_bytes_raw(self) -> bytes:
104
+ """
105
+ The raw bytes of the private key.
106
+ Equivalent to private_bytes(Raw, Raw, NoEncryption()).
107
+ """
108
+
109
+ @abc.abstractmethod
110
+ def sign(self, data: bytes) -> bytes:
111
+ """
112
+ Signs the data.
113
+ """
114
+
115
+
116
+ Ed25519PrivateKey.register(rust_openssl.ed25519.Ed25519PrivateKey)
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+
9
+ from cryptography.hazmat.primitives import hashes
10
+ from cryptography.hazmat.primitives._asymmetric import (
11
+ AsymmetricPadding as AsymmetricPadding,
12
+ )
13
+ from cryptography.hazmat.primitives.asymmetric import rsa
14
+
15
+
16
+ class PKCS1v15(AsymmetricPadding):
17
+ name = "EMSA-PKCS1-v1_5"
18
+
19
+
20
+ class _MaxLength:
21
+ "Sentinel value for `MAX_LENGTH`."
22
+
23
+
24
+ class _Auto:
25
+ "Sentinel value for `AUTO`."
26
+
27
+
28
+ class _DigestLength:
29
+ "Sentinel value for `DIGEST_LENGTH`."
30
+
31
+
32
+ class PSS(AsymmetricPadding):
33
+ MAX_LENGTH = _MaxLength()
34
+ AUTO = _Auto()
35
+ DIGEST_LENGTH = _DigestLength()
36
+ name = "EMSA-PSS"
37
+ _salt_length: int | _MaxLength | _Auto | _DigestLength
38
+
39
+ def __init__(
40
+ self,
41
+ mgf: MGF,
42
+ salt_length: int | _MaxLength | _Auto | _DigestLength,
43
+ ) -> None:
44
+ self._mgf = mgf
45
+
46
+ if not isinstance(
47
+ salt_length, (int, _MaxLength, _Auto, _DigestLength)
48
+ ):
49
+ raise TypeError(
50
+ "salt_length must be an integer, MAX_LENGTH, "
51
+ "DIGEST_LENGTH, or AUTO"
52
+ )
53
+
54
+ if isinstance(salt_length, int) and salt_length < 0:
55
+ raise ValueError("salt_length must be zero or greater.")
56
+
57
+ self._salt_length = salt_length
58
+
59
+ @property
60
+ def mgf(self) -> MGF:
61
+ return self._mgf
62
+
63
+
64
+ class OAEP(AsymmetricPadding):
65
+ name = "EME-OAEP"
66
+
67
+ def __init__(
68
+ self,
69
+ mgf: MGF,
70
+ algorithm: hashes.HashAlgorithm,
71
+ label: bytes | None,
72
+ ):
73
+ if not isinstance(algorithm, hashes.HashAlgorithm):
74
+ raise TypeError("Expected instance of hashes.HashAlgorithm.")
75
+
76
+ self._mgf = mgf
77
+ self._algorithm = algorithm
78
+ self._label = label
79
+
80
+ @property
81
+ def algorithm(self) -> hashes.HashAlgorithm:
82
+ return self._algorithm
83
+
84
+ @property
85
+ def mgf(self) -> MGF:
86
+ return self._mgf
87
+
88
+
89
+ class MGF(metaclass=abc.ABCMeta):
90
+ _algorithm: hashes.HashAlgorithm
91
+
92
+
93
+ class MGF1(MGF):
94
+ MAX_LENGTH = _MaxLength()
95
+
96
+ def __init__(self, algorithm: hashes.HashAlgorithm):
97
+ if not isinstance(algorithm, hashes.HashAlgorithm):
98
+ raise TypeError("Expected instance of hashes.HashAlgorithm.")
99
+
100
+ self._algorithm = algorithm
101
+
102
+
103
+ def calculate_max_pss_salt_length(
104
+ key: rsa.RSAPrivateKey | rsa.RSAPublicKey,
105
+ hash_algorithm: hashes.HashAlgorithm,
106
+ ) -> int:
107
+ if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)):
108
+ raise TypeError("key must be an RSA public or private key")
109
+ # bit length - 1 per RFC 3447
110
+ emlen = (key.key_size + 6) // 8
111
+ salt_length = emlen - hash_algorithm.digest_size - 2
112
+ assert salt_length >= 0
113
+ return salt_length
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+ import random
9
+ import typing
10
+ from math import gcd
11
+
12
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
13
+ from cryptography.hazmat.primitives import _serialization, hashes
14
+ from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding
15
+ from cryptography.hazmat.primitives.asymmetric import utils as asym_utils
16
+
17
+
18
+ class RSAPrivateKey(metaclass=abc.ABCMeta):
19
+ @abc.abstractmethod
20
+ def decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes:
21
+ """
22
+ Decrypts the provided ciphertext.
23
+ """
24
+
25
+ @property
26
+ @abc.abstractmethod
27
+ def key_size(self) -> int:
28
+ """
29
+ The bit length of the public modulus.
30
+ """
31
+
32
+ @abc.abstractmethod
33
+ def public_key(self) -> RSAPublicKey:
34
+ """
35
+ The RSAPublicKey associated with this private key.
36
+ """
37
+
38
+ @abc.abstractmethod
39
+ def sign(
40
+ self,
41
+ data: bytes,
42
+ padding: AsymmetricPadding,
43
+ algorithm: asym_utils.Prehashed | hashes.HashAlgorithm,
44
+ ) -> bytes:
45
+ """
46
+ Signs the data.
47
+ """
48
+
49
+ @abc.abstractmethod
50
+ def private_numbers(self) -> RSAPrivateNumbers:
51
+ """
52
+ Returns an RSAPrivateNumbers.
53
+ """
54
+
55
+ @abc.abstractmethod
56
+ def private_bytes(
57
+ self,
58
+ encoding: _serialization.Encoding,
59
+ format: _serialization.PrivateFormat,
60
+ encryption_algorithm: _serialization.KeySerializationEncryption,
61
+ ) -> bytes:
62
+ """
63
+ Returns the key serialized as bytes.
64
+ """
65
+
66
+
67
+ RSAPrivateKeyWithSerialization = RSAPrivateKey
68
+ RSAPrivateKey.register(rust_openssl.rsa.RSAPrivateKey)
69
+
70
+
71
+ class RSAPublicKey(metaclass=abc.ABCMeta):
72
+ @abc.abstractmethod
73
+ def encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes:
74
+ """
75
+ Encrypts the given plaintext.
76
+ """
77
+
78
+ @property
79
+ @abc.abstractmethod
80
+ def key_size(self) -> int:
81
+ """
82
+ The bit length of the public modulus.
83
+ """
84
+
85
+ @abc.abstractmethod
86
+ def public_numbers(self) -> RSAPublicNumbers:
87
+ """
88
+ Returns an RSAPublicNumbers
89
+ """
90
+
91
+ @abc.abstractmethod
92
+ def public_bytes(
93
+ self,
94
+ encoding: _serialization.Encoding,
95
+ format: _serialization.PublicFormat,
96
+ ) -> bytes:
97
+ """
98
+ Returns the key serialized as bytes.
99
+ """
100
+
101
+ @abc.abstractmethod
102
+ def verify(
103
+ self,
104
+ signature: bytes,
105
+ data: bytes,
106
+ padding: AsymmetricPadding,
107
+ algorithm: asym_utils.Prehashed | hashes.HashAlgorithm,
108
+ ) -> None:
109
+ """
110
+ Verifies the signature of the data.
111
+ """
112
+
113
+ @abc.abstractmethod
114
+ def recover_data_from_signature(
115
+ self,
116
+ signature: bytes,
117
+ padding: AsymmetricPadding,
118
+ algorithm: hashes.HashAlgorithm | None,
119
+ ) -> bytes:
120
+ """
121
+ Recovers the original data from the signature.
122
+ """
123
+
124
+ @abc.abstractmethod
125
+ def __eq__(self, other: object) -> bool:
126
+ """
127
+ Checks equality.
128
+ """
129
+
130
+
131
+ RSAPublicKeyWithSerialization = RSAPublicKey
132
+ RSAPublicKey.register(rust_openssl.rsa.RSAPublicKey)
133
+
134
+ RSAPrivateNumbers = rust_openssl.rsa.RSAPrivateNumbers
135
+ RSAPublicNumbers = rust_openssl.rsa.RSAPublicNumbers
136
+
137
+
138
+ def generate_private_key(
139
+ public_exponent: int,
140
+ key_size: int,
141
+ backend: typing.Any = None,
142
+ ) -> RSAPrivateKey:
143
+ _verify_rsa_parameters(public_exponent, key_size)
144
+ return rust_openssl.rsa.generate_private_key(public_exponent, key_size)
145
+
146
+
147
+ def _verify_rsa_parameters(public_exponent: int, key_size: int) -> None:
148
+ if public_exponent not in (3, 65537):
149
+ raise ValueError(
150
+ "public_exponent must be either 3 (for legacy compatibility) or "
151
+ "65537. Almost everyone should choose 65537 here!"
152
+ )
153
+
154
+ if key_size < 1024:
155
+ raise ValueError("key_size must be at least 1024-bits.")
156
+
157
+
158
+ def _modinv(e: int, m: int) -> int:
159
+ """
160
+ Modular Multiplicative Inverse. Returns x such that: (x*e) mod m == 1
161
+ """
162
+ x1, x2 = 1, 0
163
+ a, b = e, m
164
+ while b > 0:
165
+ q, r = divmod(a, b)
166
+ xn = x1 - q * x2
167
+ a, b, x1, x2 = b, r, x2, xn
168
+ return x1 % m
169
+
170
+
171
+ def rsa_crt_iqmp(p: int, q: int) -> int:
172
+ """
173
+ Compute the CRT (q ** -1) % p value from RSA primes p and q.
174
+ """
175
+ return _modinv(q, p)
176
+
177
+
178
+ def rsa_crt_dmp1(private_exponent: int, p: int) -> int:
179
+ """
180
+ Compute the CRT private_exponent % (p - 1) value from the RSA
181
+ private_exponent (d) and p.
182
+ """
183
+ return private_exponent % (p - 1)
184
+
185
+
186
+ def rsa_crt_dmq1(private_exponent: int, q: int) -> int:
187
+ """
188
+ Compute the CRT private_exponent % (q - 1) value from the RSA
189
+ private_exponent (d) and q.
190
+ """
191
+ return private_exponent % (q - 1)
192
+
193
+
194
+ def rsa_recover_private_exponent(e: int, p: int, q: int) -> int:
195
+ """
196
+ Compute the RSA private_exponent (d) given the public exponent (e)
197
+ and the RSA primes p and q.
198
+
199
+ This uses the Carmichael totient function to generate the
200
+ smallest possible working value of the private exponent.
201
+ """
202
+ # This lambda_n is the Carmichael totient function.
203
+ # The original RSA paper uses the Euler totient function
204
+ # here: phi_n = (p - 1) * (q - 1)
205
+ # Either version of the private exponent will work, but the
206
+ # one generated by the older formulation may be larger
207
+ # than necessary. (lambda_n always divides phi_n)
208
+ #
209
+ # TODO: Replace with lcm(p - 1, q - 1) once the minimum
210
+ # supported Python version is >= 3.9.
211
+ lambda_n = (p - 1) * (q - 1) // gcd(p - 1, q - 1)
212
+ return _modinv(e, lambda_n)
213
+
214
+
215
+ # Controls the number of iterations rsa_recover_prime_factors will perform
216
+ # to obtain the prime factors.
217
+ _MAX_RECOVERY_ATTEMPTS = 500
218
+
219
+
220
+ def rsa_recover_prime_factors(n: int, e: int, d: int) -> tuple[int, int]:
221
+ """
222
+ Compute factors p and q from the private exponent d. We assume that n has
223
+ no more than two factors. This function is adapted from code in PyCrypto.
224
+ """
225
+ # reject invalid values early
226
+ if 17 != pow(17, e * d, n):
227
+ raise ValueError("n, d, e don't match")
228
+ # See 8.2.2(i) in Handbook of Applied Cryptography.
229
+ ktot = d * e - 1
230
+ # The quantity d*e-1 is a multiple of phi(n), even,
231
+ # and can be represented as t*2^s.
232
+ t = ktot
233
+ while t % 2 == 0:
234
+ t = t // 2
235
+ # Cycle through all multiplicative inverses in Zn.
236
+ # The algorithm is non-deterministic, but there is a 50% chance
237
+ # any candidate a leads to successful factoring.
238
+ # See "Digitalized Signatures and Public Key Functions as Intractable
239
+ # as Factorization", M. Rabin, 1979
240
+ spotted = False
241
+ tries = 0
242
+ while not spotted and tries < _MAX_RECOVERY_ATTEMPTS:
243
+ a = random.randint(2, n - 1)
244
+ tries += 1
245
+ k = t
246
+ # Cycle through all values a^{t*2^i}=a^k
247
+ while k < ktot:
248
+ cand = pow(a, k, n)
249
+ # Check if a^k is a non-trivial root of unity (mod n)
250
+ if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
251
+ # We have found a number such that (cand-1)(cand+1)=0 (mod n).
252
+ # Either of the terms divides n.
253
+ p = gcd(cand + 1, n)
254
+ spotted = True
255
+ break
256
+ k *= 2
257
+ if not spotted:
258
+ raise ValueError("Unable to compute factors p and q from exponent d.")
259
+ # Found !
260
+ q, r = divmod(n, p)
261
+ assert r == 0
262
+ p, q = sorted((p, q), reverse=True)
263
+ return (p, q)
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/types.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from cryptography import utils
10
+ from cryptography.hazmat.primitives.asymmetric import (
11
+ dh,
12
+ dsa,
13
+ ec,
14
+ ed448,
15
+ ed25519,
16
+ rsa,
17
+ x448,
18
+ x25519,
19
+ )
20
+
21
+ # Every asymmetric key type
22
+ PublicKeyTypes = typing.Union[
23
+ dh.DHPublicKey,
24
+ dsa.DSAPublicKey,
25
+ rsa.RSAPublicKey,
26
+ ec.EllipticCurvePublicKey,
27
+ ed25519.Ed25519PublicKey,
28
+ ed448.Ed448PublicKey,
29
+ x25519.X25519PublicKey,
30
+ x448.X448PublicKey,
31
+ ]
32
+ PUBLIC_KEY_TYPES = PublicKeyTypes
33
+ utils.deprecated(
34
+ PUBLIC_KEY_TYPES,
35
+ __name__,
36
+ "Use PublicKeyTypes instead",
37
+ utils.DeprecatedIn40,
38
+ name="PUBLIC_KEY_TYPES",
39
+ )
40
+ # Every asymmetric key type
41
+ PrivateKeyTypes = typing.Union[
42
+ dh.DHPrivateKey,
43
+ ed25519.Ed25519PrivateKey,
44
+ ed448.Ed448PrivateKey,
45
+ rsa.RSAPrivateKey,
46
+ dsa.DSAPrivateKey,
47
+ ec.EllipticCurvePrivateKey,
48
+ x25519.X25519PrivateKey,
49
+ x448.X448PrivateKey,
50
+ ]
51
+ PRIVATE_KEY_TYPES = PrivateKeyTypes
52
+ utils.deprecated(
53
+ PRIVATE_KEY_TYPES,
54
+ __name__,
55
+ "Use PrivateKeyTypes instead",
56
+ utils.DeprecatedIn40,
57
+ name="PRIVATE_KEY_TYPES",
58
+ )
59
+ # Just the key types we allow to be used for x509 signing. This mirrors
60
+ # the certificate public key types
61
+ CertificateIssuerPrivateKeyTypes = typing.Union[
62
+ ed25519.Ed25519PrivateKey,
63
+ ed448.Ed448PrivateKey,
64
+ rsa.RSAPrivateKey,
65
+ dsa.DSAPrivateKey,
66
+ ec.EllipticCurvePrivateKey,
67
+ ]
68
+ CERTIFICATE_PRIVATE_KEY_TYPES = CertificateIssuerPrivateKeyTypes
69
+ utils.deprecated(
70
+ CERTIFICATE_PRIVATE_KEY_TYPES,
71
+ __name__,
72
+ "Use CertificateIssuerPrivateKeyTypes instead",
73
+ utils.DeprecatedIn40,
74
+ name="CERTIFICATE_PRIVATE_KEY_TYPES",
75
+ )
76
+ # Just the key types we allow to be used for x509 signing. This mirrors
77
+ # the certificate private key types
78
+ CertificateIssuerPublicKeyTypes = typing.Union[
79
+ dsa.DSAPublicKey,
80
+ rsa.RSAPublicKey,
81
+ ec.EllipticCurvePublicKey,
82
+ ed25519.Ed25519PublicKey,
83
+ ed448.Ed448PublicKey,
84
+ ]
85
+ CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES = CertificateIssuerPublicKeyTypes
86
+ utils.deprecated(
87
+ CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES,
88
+ __name__,
89
+ "Use CertificateIssuerPublicKeyTypes instead",
90
+ utils.DeprecatedIn40,
91
+ name="CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES",
92
+ )
93
+ # This type removes DHPublicKey. x448/x25519 can be a public key
94
+ # but cannot be used in signing so they are allowed here.
95
+ CertificatePublicKeyTypes = typing.Union[
96
+ dsa.DSAPublicKey,
97
+ rsa.RSAPublicKey,
98
+ ec.EllipticCurvePublicKey,
99
+ ed25519.Ed25519PublicKey,
100
+ ed448.Ed448PublicKey,
101
+ x25519.X25519PublicKey,
102
+ x448.X448PublicKey,
103
+ ]
104
+ CERTIFICATE_PUBLIC_KEY_TYPES = CertificatePublicKeyTypes
105
+ utils.deprecated(
106
+ CERTIFICATE_PUBLIC_KEY_TYPES,
107
+ __name__,
108
+ "Use CertificatePublicKeyTypes instead",
109
+ utils.DeprecatedIn40,
110
+ name="CERTIFICATE_PUBLIC_KEY_TYPES",
111
+ )
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.bindings._rust import asn1
8
+ from cryptography.hazmat.primitives import hashes
9
+
10
+ decode_dss_signature = asn1.decode_dss_signature
11
+ encode_dss_signature = asn1.encode_dss_signature
12
+
13
+
14
+ class Prehashed:
15
+ def __init__(self, algorithm: hashes.HashAlgorithm):
16
+ if not isinstance(algorithm, hashes.HashAlgorithm):
17
+ raise TypeError("Expected instance of HashAlgorithm.")
18
+
19
+ self._algorithm = algorithm
20
+ self._digest_size = algorithm.digest_size
21
+
22
+ @property
23
+ def digest_size(self) -> int:
24
+ return self._digest_size
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+
9
+ from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
10
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
11
+ from cryptography.hazmat.primitives import _serialization
12
+
13
+
14
+ class X25519PublicKey(metaclass=abc.ABCMeta):
15
+ @classmethod
16
+ def from_public_bytes(cls, data: bytes) -> X25519PublicKey:
17
+ from cryptography.hazmat.backends.openssl.backend import backend
18
+
19
+ if not backend.x25519_supported():
20
+ raise UnsupportedAlgorithm(
21
+ "X25519 is not supported by this version of OpenSSL.",
22
+ _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,
23
+ )
24
+
25
+ return rust_openssl.x25519.from_public_bytes(data)
26
+
27
+ @abc.abstractmethod
28
+ def public_bytes(
29
+ self,
30
+ encoding: _serialization.Encoding,
31
+ format: _serialization.PublicFormat,
32
+ ) -> bytes:
33
+ """
34
+ The serialized bytes of the public key.
35
+ """
36
+
37
+ @abc.abstractmethod
38
+ def public_bytes_raw(self) -> bytes:
39
+ """
40
+ The raw bytes of the public key.
41
+ Equivalent to public_bytes(Raw, Raw).
42
+ """
43
+
44
+ @abc.abstractmethod
45
+ def __eq__(self, other: object) -> bool:
46
+ """
47
+ Checks equality.
48
+ """
49
+
50
+
51
+ X25519PublicKey.register(rust_openssl.x25519.X25519PublicKey)
52
+
53
+
54
+ class X25519PrivateKey(metaclass=abc.ABCMeta):
55
+ @classmethod
56
+ def generate(cls) -> X25519PrivateKey:
57
+ from cryptography.hazmat.backends.openssl.backend import backend
58
+
59
+ if not backend.x25519_supported():
60
+ raise UnsupportedAlgorithm(
61
+ "X25519 is not supported by this version of OpenSSL.",
62
+ _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,
63
+ )
64
+ return rust_openssl.x25519.generate_key()
65
+
66
+ @classmethod
67
+ def from_private_bytes(cls, data: bytes) -> X25519PrivateKey:
68
+ from cryptography.hazmat.backends.openssl.backend import backend
69
+
70
+ if not backend.x25519_supported():
71
+ raise UnsupportedAlgorithm(
72
+ "X25519 is not supported by this version of OpenSSL.",
73
+ _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,
74
+ )
75
+
76
+ return rust_openssl.x25519.from_private_bytes(data)
77
+
78
+ @abc.abstractmethod
79
+ def public_key(self) -> X25519PublicKey:
80
+ """
81
+ Returns the public key associated with this private key
82
+ """
83
+
84
+ @abc.abstractmethod
85
+ def private_bytes(
86
+ self,
87
+ encoding: _serialization.Encoding,
88
+ format: _serialization.PrivateFormat,
89
+ encryption_algorithm: _serialization.KeySerializationEncryption,
90
+ ) -> bytes:
91
+ """
92
+ The serialized bytes of the private key.
93
+ """
94
+
95
+ @abc.abstractmethod
96
+ def private_bytes_raw(self) -> bytes:
97
+ """
98
+ The raw bytes of the private key.
99
+ Equivalent to private_bytes(Raw, Raw, NoEncryption()).
100
+ """
101
+
102
+ @abc.abstractmethod
103
+ def exchange(self, peer_public_key: X25519PublicKey) -> bytes:
104
+ """
105
+ Performs a key exchange operation using the provided peer's public key.
106
+ """
107
+
108
+
109
+ X25519PrivateKey.register(rust_openssl.x25519.X25519PrivateKey)
lib/python3.10/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+
9
+ from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
10
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
11
+ from cryptography.hazmat.primitives import _serialization
12
+
13
+
14
+ class X448PublicKey(metaclass=abc.ABCMeta):
15
+ @classmethod
16
+ def from_public_bytes(cls, data: bytes) -> X448PublicKey:
17
+ from cryptography.hazmat.backends.openssl.backend import backend
18
+
19
+ if not backend.x448_supported():
20
+ raise UnsupportedAlgorithm(
21
+ "X448 is not supported by this version of OpenSSL.",
22
+ _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,
23
+ )
24
+
25
+ return rust_openssl.x448.from_public_bytes(data)
26
+
27
+ @abc.abstractmethod
28
+ def public_bytes(
29
+ self,
30
+ encoding: _serialization.Encoding,
31
+ format: _serialization.PublicFormat,
32
+ ) -> bytes:
33
+ """
34
+ The serialized bytes of the public key.
35
+ """
36
+
37
+ @abc.abstractmethod
38
+ def public_bytes_raw(self) -> bytes:
39
+ """
40
+ The raw bytes of the public key.
41
+ Equivalent to public_bytes(Raw, Raw).
42
+ """
43
+
44
+ @abc.abstractmethod
45
+ def __eq__(self, other: object) -> bool:
46
+ """
47
+ Checks equality.
48
+ """
49
+
50
+
51
+ if hasattr(rust_openssl, "x448"):
52
+ X448PublicKey.register(rust_openssl.x448.X448PublicKey)
53
+
54
+
55
+ class X448PrivateKey(metaclass=abc.ABCMeta):
56
+ @classmethod
57
+ def generate(cls) -> X448PrivateKey:
58
+ from cryptography.hazmat.backends.openssl.backend import backend
59
+
60
+ if not backend.x448_supported():
61
+ raise UnsupportedAlgorithm(
62
+ "X448 is not supported by this version of OpenSSL.",
63
+ _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,
64
+ )
65
+
66
+ return rust_openssl.x448.generate_key()
67
+
68
+ @classmethod
69
+ def from_private_bytes(cls, data: bytes) -> X448PrivateKey:
70
+ from cryptography.hazmat.backends.openssl.backend import backend
71
+
72
+ if not backend.x448_supported():
73
+ raise UnsupportedAlgorithm(
74
+ "X448 is not supported by this version of OpenSSL.",
75
+ _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,
76
+ )
77
+
78
+ return rust_openssl.x448.from_private_bytes(data)
79
+
80
+ @abc.abstractmethod
81
+ def public_key(self) -> X448PublicKey:
82
+ """
83
+ Returns the public key associated with this private key
84
+ """
85
+
86
+ @abc.abstractmethod
87
+ def private_bytes(
88
+ self,
89
+ encoding: _serialization.Encoding,
90
+ format: _serialization.PrivateFormat,
91
+ encryption_algorithm: _serialization.KeySerializationEncryption,
92
+ ) -> bytes:
93
+ """
94
+ The serialized bytes of the private key.
95
+ """
96
+
97
+ @abc.abstractmethod
98
+ def private_bytes_raw(self) -> bytes:
99
+ """
100
+ The raw bytes of the private key.
101
+ Equivalent to private_bytes(Raw, Raw, NoEncryption()).
102
+ """
103
+
104
+ @abc.abstractmethod
105
+ def exchange(self, peer_public_key: X448PublicKey) -> bytes:
106
+ """
107
+ Performs a key exchange operation using the provided peer's public key.
108
+ """
109
+
110
+
111
+ if hasattr(rust_openssl, "x448"):
112
+ X448PrivateKey.register(rust_openssl.x448.X448PrivateKey)
lib/python3.10/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.primitives._cipheralgorithm import (
8
+ BlockCipherAlgorithm,
9
+ CipherAlgorithm,
10
+ )
11
+ from cryptography.hazmat.primitives.ciphers.base import (
12
+ AEADCipherContext,
13
+ AEADDecryptionContext,
14
+ AEADEncryptionContext,
15
+ Cipher,
16
+ CipherContext,
17
+ )
18
+
19
+ __all__ = [
20
+ "AEADCipherContext",
21
+ "AEADDecryptionContext",
22
+ "AEADEncryptionContext",
23
+ "BlockCipherAlgorithm",
24
+ "Cipher",
25
+ "CipherAlgorithm",
26
+ "CipherContext",
27
+ ]
lib/python3.10/site-packages/cryptography/hazmat/primitives/ciphers/aead.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
8
+
9
+ __all__ = [
10
+ "AESCCM",
11
+ "AESGCM",
12
+ "AESGCMSIV",
13
+ "AESOCB3",
14
+ "AESSIV",
15
+ "ChaCha20Poly1305",
16
+ ]
17
+
18
+ AESGCM = rust_openssl.aead.AESGCM
19
+ ChaCha20Poly1305 = rust_openssl.aead.ChaCha20Poly1305
20
+ AESCCM = rust_openssl.aead.AESCCM
21
+ AESSIV = rust_openssl.aead.AESSIV
22
+ AESOCB3 = rust_openssl.aead.AESOCB3
23
+ AESGCMSIV = rust_openssl.aead.AESGCMSIV
lib/python3.10/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography import utils
8
+ from cryptography.hazmat.decrepit.ciphers.algorithms import (
9
+ ARC4 as ARC4,
10
+ )
11
+ from cryptography.hazmat.decrepit.ciphers.algorithms import (
12
+ CAST5 as CAST5,
13
+ )
14
+ from cryptography.hazmat.decrepit.ciphers.algorithms import (
15
+ IDEA as IDEA,
16
+ )
17
+ from cryptography.hazmat.decrepit.ciphers.algorithms import (
18
+ SEED as SEED,
19
+ )
20
+ from cryptography.hazmat.decrepit.ciphers.algorithms import (
21
+ Blowfish as Blowfish,
22
+ )
23
+ from cryptography.hazmat.decrepit.ciphers.algorithms import (
24
+ TripleDES as TripleDES,
25
+ )
26
+ from cryptography.hazmat.primitives._cipheralgorithm import _verify_key_size
27
+ from cryptography.hazmat.primitives.ciphers import (
28
+ BlockCipherAlgorithm,
29
+ CipherAlgorithm,
30
+ )
31
+
32
+
33
+ class AES(BlockCipherAlgorithm):
34
+ name = "AES"
35
+ block_size = 128
36
+ # 512 added to support AES-256-XTS, which uses 512-bit keys
37
+ key_sizes = frozenset([128, 192, 256, 512])
38
+
39
+ def __init__(self, key: bytes):
40
+ self.key = _verify_key_size(self, key)
41
+
42
+ @property
43
+ def key_size(self) -> int:
44
+ return len(self.key) * 8
45
+
46
+
47
+ class AES128(BlockCipherAlgorithm):
48
+ name = "AES"
49
+ block_size = 128
50
+ key_sizes = frozenset([128])
51
+ key_size = 128
52
+
53
+ def __init__(self, key: bytes):
54
+ self.key = _verify_key_size(self, key)
55
+
56
+
57
+ class AES256(BlockCipherAlgorithm):
58
+ name = "AES"
59
+ block_size = 128
60
+ key_sizes = frozenset([256])
61
+ key_size = 256
62
+
63
+ def __init__(self, key: bytes):
64
+ self.key = _verify_key_size(self, key)
65
+
66
+
67
+ class Camellia(BlockCipherAlgorithm):
68
+ name = "camellia"
69
+ block_size = 128
70
+ key_sizes = frozenset([128, 192, 256])
71
+
72
+ def __init__(self, key: bytes):
73
+ self.key = _verify_key_size(self, key)
74
+
75
+ @property
76
+ def key_size(self) -> int:
77
+ return len(self.key) * 8
78
+
79
+
80
+ utils.deprecated(
81
+ ARC4,
82
+ __name__,
83
+ "ARC4 has been moved to "
84
+ "cryptography.hazmat.decrepit.ciphers.algorithms.ARC4 and "
85
+ "will be removed from "
86
+ "cryptography.hazmat.primitives.ciphers.algorithms in 48.0.0.",
87
+ utils.DeprecatedIn43,
88
+ name="ARC4",
89
+ )
90
+
91
+
92
+ utils.deprecated(
93
+ TripleDES,
94
+ __name__,
95
+ "TripleDES has been moved to "
96
+ "cryptography.hazmat.decrepit.ciphers.algorithms.TripleDES and "
97
+ "will be removed from "
98
+ "cryptography.hazmat.primitives.ciphers.algorithms in 48.0.0.",
99
+ utils.DeprecatedIn43,
100
+ name="TripleDES",
101
+ )
102
+
103
+ utils.deprecated(
104
+ Blowfish,
105
+ __name__,
106
+ "Blowfish has been moved to "
107
+ "cryptography.hazmat.decrepit.ciphers.algorithms.Blowfish and "
108
+ "will be removed from "
109
+ "cryptography.hazmat.primitives.ciphers.algorithms in 45.0.0.",
110
+ utils.DeprecatedIn37,
111
+ name="Blowfish",
112
+ )
113
+
114
+
115
+ utils.deprecated(
116
+ CAST5,
117
+ __name__,
118
+ "CAST5 has been moved to "
119
+ "cryptography.hazmat.decrepit.ciphers.algorithms.CAST5 and "
120
+ "will be removed from "
121
+ "cryptography.hazmat.primitives.ciphers.algorithms in 45.0.0.",
122
+ utils.DeprecatedIn37,
123
+ name="CAST5",
124
+ )
125
+
126
+
127
+ utils.deprecated(
128
+ IDEA,
129
+ __name__,
130
+ "IDEA has been moved to "
131
+ "cryptography.hazmat.decrepit.ciphers.algorithms.IDEA and "
132
+ "will be removed from "
133
+ "cryptography.hazmat.primitives.ciphers.algorithms in 45.0.0.",
134
+ utils.DeprecatedIn37,
135
+ name="IDEA",
136
+ )
137
+
138
+
139
+ utils.deprecated(
140
+ SEED,
141
+ __name__,
142
+ "SEED has been moved to "
143
+ "cryptography.hazmat.decrepit.ciphers.algorithms.SEED and "
144
+ "will be removed from "
145
+ "cryptography.hazmat.primitives.ciphers.algorithms in 45.0.0.",
146
+ utils.DeprecatedIn37,
147
+ name="SEED",
148
+ )
149
+
150
+
151
+ class ChaCha20(CipherAlgorithm):
152
+ name = "ChaCha20"
153
+ key_sizes = frozenset([256])
154
+
155
+ def __init__(self, key: bytes, nonce: bytes):
156
+ self.key = _verify_key_size(self, key)
157
+ utils._check_byteslike("nonce", nonce)
158
+
159
+ if len(nonce) != 16:
160
+ raise ValueError("nonce must be 128-bits (16 bytes)")
161
+
162
+ self._nonce = nonce
163
+
164
+ @property
165
+ def nonce(self) -> bytes:
166
+ return self._nonce
167
+
168
+ @property
169
+ def key_size(self) -> int:
170
+ return len(self.key) * 8
171
+
172
+
173
+ class SM4(BlockCipherAlgorithm):
174
+ name = "SM4"
175
+ block_size = 128
176
+ key_sizes = frozenset([128])
177
+
178
+ def __init__(self, key: bytes):
179
+ self.key = _verify_key_size(self, key)
180
+
181
+ @property
182
+ def key_size(self) -> int:
183
+ return len(self.key) * 8
lib/python3.10/site-packages/cryptography/hazmat/primitives/cmac.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
8
+
9
+ __all__ = ["CMAC"]
10
+ CMAC = rust_openssl.cmac.CMAC
lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+
9
+
10
+ class KeyDerivationFunction(metaclass=abc.ABCMeta):
11
+ @abc.abstractmethod
12
+ def derive(self, key_material: bytes) -> bytes:
13
+ """
14
+ Deterministically generates and returns a new key based on the existing
15
+ key material.
16
+ """
17
+
18
+ @abc.abstractmethod
19
+ def verify(self, key_material: bytes, expected_key: bytes) -> None:
20
+ """
21
+ Checks whether the key generated by the key material matches the
22
+ expected derived key. Raises an exception if they do not match.
23
+ """
lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/argon2.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
8
+ from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
9
+
10
+ Argon2id = rust_openssl.kdf.Argon2id
11
+ KeyDerivationFunction.register(Argon2id)
12
+
13
+ __all__ = ["Argon2id"]
lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from cryptography import utils
10
+ from cryptography.exceptions import AlreadyFinalized, InvalidKey
11
+ from cryptography.hazmat.primitives import constant_time, hashes, hmac
12
+ from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
13
+
14
+
15
+ def _int_to_u32be(n: int) -> bytes:
16
+ return n.to_bytes(length=4, byteorder="big")
17
+
18
+
19
+ def _common_args_checks(
20
+ algorithm: hashes.HashAlgorithm,
21
+ length: int,
22
+ otherinfo: bytes | None,
23
+ ) -> None:
24
+ max_length = algorithm.digest_size * (2**32 - 1)
25
+ if length > max_length:
26
+ raise ValueError(f"Cannot derive keys larger than {max_length} bits.")
27
+ if otherinfo is not None:
28
+ utils._check_bytes("otherinfo", otherinfo)
29
+
30
+
31
+ def _concatkdf_derive(
32
+ key_material: bytes,
33
+ length: int,
34
+ auxfn: typing.Callable[[], hashes.HashContext],
35
+ otherinfo: bytes,
36
+ ) -> bytes:
37
+ utils._check_byteslike("key_material", key_material)
38
+ output = [b""]
39
+ outlen = 0
40
+ counter = 1
41
+
42
+ while length > outlen:
43
+ h = auxfn()
44
+ h.update(_int_to_u32be(counter))
45
+ h.update(key_material)
46
+ h.update(otherinfo)
47
+ output.append(h.finalize())
48
+ outlen += len(output[-1])
49
+ counter += 1
50
+
51
+ return b"".join(output)[:length]
52
+
53
+
54
+ class ConcatKDFHash(KeyDerivationFunction):
55
+ def __init__(
56
+ self,
57
+ algorithm: hashes.HashAlgorithm,
58
+ length: int,
59
+ otherinfo: bytes | None,
60
+ backend: typing.Any = None,
61
+ ):
62
+ _common_args_checks(algorithm, length, otherinfo)
63
+ self._algorithm = algorithm
64
+ self._length = length
65
+ self._otherinfo: bytes = otherinfo if otherinfo is not None else b""
66
+
67
+ self._used = False
68
+
69
+ def _hash(self) -> hashes.Hash:
70
+ return hashes.Hash(self._algorithm)
71
+
72
+ def derive(self, key_material: bytes) -> bytes:
73
+ if self._used:
74
+ raise AlreadyFinalized
75
+ self._used = True
76
+ return _concatkdf_derive(
77
+ key_material, self._length, self._hash, self._otherinfo
78
+ )
79
+
80
+ def verify(self, key_material: bytes, expected_key: bytes) -> None:
81
+ if not constant_time.bytes_eq(self.derive(key_material), expected_key):
82
+ raise InvalidKey
83
+
84
+
85
+ class ConcatKDFHMAC(KeyDerivationFunction):
86
+ def __init__(
87
+ self,
88
+ algorithm: hashes.HashAlgorithm,
89
+ length: int,
90
+ salt: bytes | None,
91
+ otherinfo: bytes | None,
92
+ backend: typing.Any = None,
93
+ ):
94
+ _common_args_checks(algorithm, length, otherinfo)
95
+ self._algorithm = algorithm
96
+ self._length = length
97
+ self._otherinfo: bytes = otherinfo if otherinfo is not None else b""
98
+
99
+ if algorithm.block_size is None:
100
+ raise TypeError(f"{algorithm.name} is unsupported for ConcatKDF")
101
+
102
+ if salt is None:
103
+ salt = b"\x00" * algorithm.block_size
104
+ else:
105
+ utils._check_bytes("salt", salt)
106
+
107
+ self._salt = salt
108
+
109
+ self._used = False
110
+
111
+ def _hmac(self) -> hmac.HMAC:
112
+ return hmac.HMAC(self._salt, self._algorithm)
113
+
114
+ def derive(self, key_material: bytes) -> bytes:
115
+ if self._used:
116
+ raise AlreadyFinalized
117
+ self._used = True
118
+ return _concatkdf_derive(
119
+ key_material, self._length, self._hmac, self._otherinfo
120
+ )
121
+
122
+ def verify(self, key_material: bytes, expected_key: bytes) -> None:
123
+ if not constant_time.bytes_eq(self.derive(key_material), expected_key):
124
+ raise InvalidKey
lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from cryptography import utils
10
+ from cryptography.exceptions import AlreadyFinalized, InvalidKey
11
+ from cryptography.hazmat.primitives import constant_time, hashes, hmac
12
+ from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
13
+
14
+
15
+ class HKDF(KeyDerivationFunction):
16
+ def __init__(
17
+ self,
18
+ algorithm: hashes.HashAlgorithm,
19
+ length: int,
20
+ salt: bytes | None,
21
+ info: bytes | None,
22
+ backend: typing.Any = None,
23
+ ):
24
+ self._algorithm = algorithm
25
+
26
+ if salt is None:
27
+ salt = b"\x00" * self._algorithm.digest_size
28
+ else:
29
+ utils._check_bytes("salt", salt)
30
+
31
+ self._salt = salt
32
+
33
+ self._hkdf_expand = HKDFExpand(self._algorithm, length, info)
34
+
35
+ def _extract(self, key_material: bytes) -> bytes:
36
+ h = hmac.HMAC(self._salt, self._algorithm)
37
+ h.update(key_material)
38
+ return h.finalize()
39
+
40
+ def derive(self, key_material: bytes) -> bytes:
41
+ utils._check_byteslike("key_material", key_material)
42
+ return self._hkdf_expand.derive(self._extract(key_material))
43
+
44
+ def verify(self, key_material: bytes, expected_key: bytes) -> None:
45
+ if not constant_time.bytes_eq(self.derive(key_material), expected_key):
46
+ raise InvalidKey
47
+
48
+
49
+ class HKDFExpand(KeyDerivationFunction):
50
+ def __init__(
51
+ self,
52
+ algorithm: hashes.HashAlgorithm,
53
+ length: int,
54
+ info: bytes | None,
55
+ backend: typing.Any = None,
56
+ ):
57
+ self._algorithm = algorithm
58
+
59
+ max_length = 255 * algorithm.digest_size
60
+
61
+ if length > max_length:
62
+ raise ValueError(
63
+ f"Cannot derive keys larger than {max_length} octets."
64
+ )
65
+
66
+ self._length = length
67
+
68
+ if info is None:
69
+ info = b""
70
+ else:
71
+ utils._check_bytes("info", info)
72
+
73
+ self._info = info
74
+
75
+ self._used = False
76
+
77
+ def _expand(self, key_material: bytes) -> bytes:
78
+ output = [b""]
79
+ counter = 1
80
+
81
+ while self._algorithm.digest_size * (len(output) - 1) < self._length:
82
+ h = hmac.HMAC(key_material, self._algorithm)
83
+ h.update(output[-1])
84
+ h.update(self._info)
85
+ h.update(bytes([counter]))
86
+ output.append(h.finalize())
87
+ counter += 1
88
+
89
+ return b"".join(output)[: self._length]
90
+
91
+ def derive(self, key_material: bytes) -> bytes:
92
+ utils._check_byteslike("key_material", key_material)
93
+ if self._used:
94
+ raise AlreadyFinalized
95
+
96
+ self._used = True
97
+ return self._expand(key_material)
98
+
99
+ def verify(self, key_material: bytes, expected_key: bytes) -> None:
100
+ if not constant_time.bytes_eq(self.derive(key_material), expected_key):
101
+ raise InvalidKey
lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from cryptography import utils
10
+ from cryptography.exceptions import (
11
+ AlreadyFinalized,
12
+ InvalidKey,
13
+ UnsupportedAlgorithm,
14
+ _Reasons,
15
+ )
16
+ from cryptography.hazmat.primitives import (
17
+ ciphers,
18
+ cmac,
19
+ constant_time,
20
+ hashes,
21
+ hmac,
22
+ )
23
+ from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
24
+
25
+
26
+ class Mode(utils.Enum):
27
+ CounterMode = "ctr"
28
+
29
+
30
+ class CounterLocation(utils.Enum):
31
+ BeforeFixed = "before_fixed"
32
+ AfterFixed = "after_fixed"
33
+ MiddleFixed = "middle_fixed"
34
+
35
+
36
+ class _KBKDFDeriver:
37
+ def __init__(
38
+ self,
39
+ prf: typing.Callable,
40
+ mode: Mode,
41
+ length: int,
42
+ rlen: int,
43
+ llen: int | None,
44
+ location: CounterLocation,
45
+ break_location: int | None,
46
+ label: bytes | None,
47
+ context: bytes | None,
48
+ fixed: bytes | None,
49
+ ):
50
+ assert callable(prf)
51
+
52
+ if not isinstance(mode, Mode):
53
+ raise TypeError("mode must be of type Mode")
54
+
55
+ if not isinstance(location, CounterLocation):
56
+ raise TypeError("location must be of type CounterLocation")
57
+
58
+ if break_location is None and location is CounterLocation.MiddleFixed:
59
+ raise ValueError("Please specify a break_location")
60
+
61
+ if (
62
+ break_location is not None
63
+ and location != CounterLocation.MiddleFixed
64
+ ):
65
+ raise ValueError(
66
+ "break_location is ignored when location is not"
67
+ " CounterLocation.MiddleFixed"
68
+ )
69
+
70
+ if break_location is not None and not isinstance(break_location, int):
71
+ raise TypeError("break_location must be an integer")
72
+
73
+ if break_location is not None and break_location < 0:
74
+ raise ValueError("break_location must be a positive integer")
75
+
76
+ if (label or context) and fixed:
77
+ raise ValueError(
78
+ "When supplying fixed data, label and context are ignored."
79
+ )
80
+
81
+ if rlen is None or not self._valid_byte_length(rlen):
82
+ raise ValueError("rlen must be between 1 and 4")
83
+
84
+ if llen is None and fixed is None:
85
+ raise ValueError("Please specify an llen")
86
+
87
+ if llen is not None and not isinstance(llen, int):
88
+ raise TypeError("llen must be an integer")
89
+
90
+ if llen == 0:
91
+ raise ValueError("llen must be non-zero")
92
+
93
+ if label is None:
94
+ label = b""
95
+
96
+ if context is None:
97
+ context = b""
98
+
99
+ utils._check_bytes("label", label)
100
+ utils._check_bytes("context", context)
101
+ self._prf = prf
102
+ self._mode = mode
103
+ self._length = length
104
+ self._rlen = rlen
105
+ self._llen = llen
106
+ self._location = location
107
+ self._break_location = break_location
108
+ self._label = label
109
+ self._context = context
110
+ self._used = False
111
+ self._fixed_data = fixed
112
+
113
+ @staticmethod
114
+ def _valid_byte_length(value: int) -> bool:
115
+ if not isinstance(value, int):
116
+ raise TypeError("value must be of type int")
117
+
118
+ value_bin = utils.int_to_bytes(1, value)
119
+ if not 1 <= len(value_bin) <= 4:
120
+ return False
121
+ return True
122
+
123
+ def derive(self, key_material: bytes, prf_output_size: int) -> bytes:
124
+ if self._used:
125
+ raise AlreadyFinalized
126
+
127
+ utils._check_byteslike("key_material", key_material)
128
+ self._used = True
129
+
130
+ # inverse floor division (equivalent to ceiling)
131
+ rounds = -(-self._length // prf_output_size)
132
+
133
+ output = [b""]
134
+
135
+ # For counter mode, the number of iterations shall not be
136
+ # larger than 2^r-1, where r <= 32 is the binary length of the counter
137
+ # This ensures that the counter values used as an input to the
138
+ # PRF will not repeat during a particular call to the KDF function.
139
+ r_bin = utils.int_to_bytes(1, self._rlen)
140
+ if rounds > pow(2, len(r_bin) * 8) - 1:
141
+ raise ValueError("There are too many iterations.")
142
+
143
+ fixed = self._generate_fixed_input()
144
+
145
+ if self._location == CounterLocation.BeforeFixed:
146
+ data_before_ctr = b""
147
+ data_after_ctr = fixed
148
+ elif self._location == CounterLocation.AfterFixed:
149
+ data_before_ctr = fixed
150
+ data_after_ctr = b""
151
+ else:
152
+ if isinstance(
153
+ self._break_location, int
154
+ ) and self._break_location > len(fixed):
155
+ raise ValueError("break_location offset > len(fixed)")
156
+ data_before_ctr = fixed[: self._break_location]
157
+ data_after_ctr = fixed[self._break_location :]
158
+
159
+ for i in range(1, rounds + 1):
160
+ h = self._prf(key_material)
161
+
162
+ counter = utils.int_to_bytes(i, self._rlen)
163
+ input_data = data_before_ctr + counter + data_after_ctr
164
+
165
+ h.update(input_data)
166
+
167
+ output.append(h.finalize())
168
+
169
+ return b"".join(output)[: self._length]
170
+
171
+ def _generate_fixed_input(self) -> bytes:
172
+ if self._fixed_data and isinstance(self._fixed_data, bytes):
173
+ return self._fixed_data
174
+
175
+ l_val = utils.int_to_bytes(self._length * 8, self._llen)
176
+
177
+ return b"".join([self._label, b"\x00", self._context, l_val])
178
+
179
+
180
+ class KBKDFHMAC(KeyDerivationFunction):
181
+ def __init__(
182
+ self,
183
+ algorithm: hashes.HashAlgorithm,
184
+ mode: Mode,
185
+ length: int,
186
+ rlen: int,
187
+ llen: int | None,
188
+ location: CounterLocation,
189
+ label: bytes | None,
190
+ context: bytes | None,
191
+ fixed: bytes | None,
192
+ backend: typing.Any = None,
193
+ *,
194
+ break_location: int | None = None,
195
+ ):
196
+ if not isinstance(algorithm, hashes.HashAlgorithm):
197
+ raise UnsupportedAlgorithm(
198
+ "Algorithm supplied is not a supported hash algorithm.",
199
+ _Reasons.UNSUPPORTED_HASH,
200
+ )
201
+
202
+ from cryptography.hazmat.backends.openssl.backend import (
203
+ backend as ossl,
204
+ )
205
+
206
+ if not ossl.hmac_supported(algorithm):
207
+ raise UnsupportedAlgorithm(
208
+ "Algorithm supplied is not a supported hmac algorithm.",
209
+ _Reasons.UNSUPPORTED_HASH,
210
+ )
211
+
212
+ self._algorithm = algorithm
213
+
214
+ self._deriver = _KBKDFDeriver(
215
+ self._prf,
216
+ mode,
217
+ length,
218
+ rlen,
219
+ llen,
220
+ location,
221
+ break_location,
222
+ label,
223
+ context,
224
+ fixed,
225
+ )
226
+
227
+ def _prf(self, key_material: bytes) -> hmac.HMAC:
228
+ return hmac.HMAC(key_material, self._algorithm)
229
+
230
+ def derive(self, key_material: bytes) -> bytes:
231
+ return self._deriver.derive(key_material, self._algorithm.digest_size)
232
+
233
+ def verify(self, key_material: bytes, expected_key: bytes) -> None:
234
+ if not constant_time.bytes_eq(self.derive(key_material), expected_key):
235
+ raise InvalidKey
236
+
237
+
238
+ class KBKDFCMAC(KeyDerivationFunction):
239
+ def __init__(
240
+ self,
241
+ algorithm,
242
+ mode: Mode,
243
+ length: int,
244
+ rlen: int,
245
+ llen: int | None,
246
+ location: CounterLocation,
247
+ label: bytes | None,
248
+ context: bytes | None,
249
+ fixed: bytes | None,
250
+ backend: typing.Any = None,
251
+ *,
252
+ break_location: int | None = None,
253
+ ):
254
+ if not issubclass(
255
+ algorithm, ciphers.BlockCipherAlgorithm
256
+ ) or not issubclass(algorithm, ciphers.CipherAlgorithm):
257
+ raise UnsupportedAlgorithm(
258
+ "Algorithm supplied is not a supported cipher algorithm.",
259
+ _Reasons.UNSUPPORTED_CIPHER,
260
+ )
261
+
262
+ self._algorithm = algorithm
263
+ self._cipher: ciphers.BlockCipherAlgorithm | None = None
264
+
265
+ self._deriver = _KBKDFDeriver(
266
+ self._prf,
267
+ mode,
268
+ length,
269
+ rlen,
270
+ llen,
271
+ location,
272
+ break_location,
273
+ label,
274
+ context,
275
+ fixed,
276
+ )
277
+
278
+ def _prf(self, _: bytes) -> cmac.CMAC:
279
+ assert self._cipher is not None
280
+
281
+ return cmac.CMAC(self._cipher)
282
+
283
+ def derive(self, key_material: bytes) -> bytes:
284
+ self._cipher = self._algorithm(key_material)
285
+
286
+ assert self._cipher is not None
287
+
288
+ from cryptography.hazmat.backends.openssl.backend import (
289
+ backend as ossl,
290
+ )
291
+
292
+ if not ossl.cmac_algorithm_supported(self._cipher):
293
+ raise UnsupportedAlgorithm(
294
+ "Algorithm supplied is not a supported cipher algorithm.",
295
+ _Reasons.UNSUPPORTED_CIPHER,
296
+ )
297
+
298
+ return self._deriver.derive(key_material, self._cipher.block_size // 8)
299
+
300
+ def verify(self, key_material: bytes, expected_key: bytes) -> None:
301
+ if not constant_time.bytes_eq(self.derive(key_material), expected_key):
302
+ raise InvalidKey
lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from cryptography import utils
10
+ from cryptography.exceptions import (
11
+ AlreadyFinalized,
12
+ InvalidKey,
13
+ UnsupportedAlgorithm,
14
+ _Reasons,
15
+ )
16
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
17
+ from cryptography.hazmat.primitives import constant_time, hashes
18
+ from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
19
+
20
+
21
+ class PBKDF2HMAC(KeyDerivationFunction):
22
+ def __init__(
23
+ self,
24
+ algorithm: hashes.HashAlgorithm,
25
+ length: int,
26
+ salt: bytes,
27
+ iterations: int,
28
+ backend: typing.Any = None,
29
+ ):
30
+ from cryptography.hazmat.backends.openssl.backend import (
31
+ backend as ossl,
32
+ )
33
+
34
+ if not ossl.pbkdf2_hmac_supported(algorithm):
35
+ raise UnsupportedAlgorithm(
36
+ f"{algorithm.name} is not supported for PBKDF2.",
37
+ _Reasons.UNSUPPORTED_HASH,
38
+ )
39
+ self._used = False
40
+ self._algorithm = algorithm
41
+ self._length = length
42
+ utils._check_bytes("salt", salt)
43
+ self._salt = salt
44
+ self._iterations = iterations
45
+
46
+ def derive(self, key_material: bytes) -> bytes:
47
+ if self._used:
48
+ raise AlreadyFinalized("PBKDF2 instances can only be used once.")
49
+ self._used = True
50
+
51
+ return rust_openssl.kdf.derive_pbkdf2_hmac(
52
+ key_material,
53
+ self._algorithm,
54
+ self._salt,
55
+ self._iterations,
56
+ self._length,
57
+ )
58
+
59
+ def verify(self, key_material: bytes, expected_key: bytes) -> None:
60
+ derived_key = self.derive(key_material)
61
+ if not constant_time.bytes_eq(derived_key, expected_key):
62
+ raise InvalidKey("Keys do not match.")
lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import sys
8
+
9
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
10
+ from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
11
+
12
+ # This is used by the scrypt tests to skip tests that require more memory
13
+ # than the MEM_LIMIT
14
+ _MEM_LIMIT = sys.maxsize // 2
15
+
16
+ Scrypt = rust_openssl.kdf.Scrypt
17
+ KeyDerivationFunction.register(Scrypt)
18
+
19
+ __all__ = ["Scrypt"]
lib/python3.10/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from cryptography import utils
10
+ from cryptography.exceptions import AlreadyFinalized, InvalidKey
11
+ from cryptography.hazmat.primitives import constant_time, hashes
12
+ from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
13
+
14
+
15
+ def _int_to_u32be(n: int) -> bytes:
16
+ return n.to_bytes(length=4, byteorder="big")
17
+
18
+
19
+ class X963KDF(KeyDerivationFunction):
20
+ def __init__(
21
+ self,
22
+ algorithm: hashes.HashAlgorithm,
23
+ length: int,
24
+ sharedinfo: bytes | None,
25
+ backend: typing.Any = None,
26
+ ):
27
+ max_len = algorithm.digest_size * (2**32 - 1)
28
+ if length > max_len:
29
+ raise ValueError(f"Cannot derive keys larger than {max_len} bits.")
30
+ if sharedinfo is not None:
31
+ utils._check_bytes("sharedinfo", sharedinfo)
32
+
33
+ self._algorithm = algorithm
34
+ self._length = length
35
+ self._sharedinfo = sharedinfo
36
+ self._used = False
37
+
38
+ def derive(self, key_material: bytes) -> bytes:
39
+ if self._used:
40
+ raise AlreadyFinalized
41
+ self._used = True
42
+ utils._check_byteslike("key_material", key_material)
43
+ output = [b""]
44
+ outlen = 0
45
+ counter = 1
46
+
47
+ while self._length > outlen:
48
+ h = hashes.Hash(self._algorithm)
49
+ h.update(key_material)
50
+ h.update(_int_to_u32be(counter))
51
+ if self._sharedinfo is not None:
52
+ h.update(self._sharedinfo)
53
+ output.append(h.finalize())
54
+ outlen += len(output[-1])
55
+ counter += 1
56
+
57
+ return b"".join(output)[: self._length]
58
+
59
+ def verify(self, key_material: bytes, expected_key: bytes) -> None:
60
+ if not constant_time.bytes_eq(self.derive(key_material), expected_key):
61
+ raise InvalidKey
lib/python3.10/site-packages/cryptography/hazmat/primitives/padding.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import abc
8
+ import typing
9
+
10
+ from cryptography import utils
11
+ from cryptography.exceptions import AlreadyFinalized
12
+ from cryptography.hazmat.bindings._rust import (
13
+ PKCS7PaddingContext,
14
+ PKCS7UnpaddingContext,
15
+ check_ansix923_padding,
16
+ )
17
+
18
+
19
+ class PaddingContext(metaclass=abc.ABCMeta):
20
+ @abc.abstractmethod
21
+ def update(self, data: bytes) -> bytes:
22
+ """
23
+ Pads the provided bytes and returns any available data as bytes.
24
+ """
25
+
26
+ @abc.abstractmethod
27
+ def finalize(self) -> bytes:
28
+ """
29
+ Finalize the padding, returns bytes.
30
+ """
31
+
32
+
33
+ def _byte_padding_check(block_size: int) -> None:
34
+ if not (0 <= block_size <= 2040):
35
+ raise ValueError("block_size must be in range(0, 2041).")
36
+
37
+ if block_size % 8 != 0:
38
+ raise ValueError("block_size must be a multiple of 8.")
39
+
40
+
41
+ def _byte_padding_update(
42
+ buffer_: bytes | None, data: bytes, block_size: int
43
+ ) -> tuple[bytes, bytes]:
44
+ if buffer_ is None:
45
+ raise AlreadyFinalized("Context was already finalized.")
46
+
47
+ utils._check_byteslike("data", data)
48
+
49
+ buffer_ += bytes(data)
50
+
51
+ finished_blocks = len(buffer_) // (block_size // 8)
52
+
53
+ result = buffer_[: finished_blocks * (block_size // 8)]
54
+ buffer_ = buffer_[finished_blocks * (block_size // 8) :]
55
+
56
+ return buffer_, result
57
+
58
+
59
+ def _byte_padding_pad(
60
+ buffer_: bytes | None,
61
+ block_size: int,
62
+ paddingfn: typing.Callable[[int], bytes],
63
+ ) -> bytes:
64
+ if buffer_ is None:
65
+ raise AlreadyFinalized("Context was already finalized.")
66
+
67
+ pad_size = block_size // 8 - len(buffer_)
68
+ return buffer_ + paddingfn(pad_size)
69
+
70
+
71
+ def _byte_unpadding_update(
72
+ buffer_: bytes | None, data: bytes, block_size: int
73
+ ) -> tuple[bytes, bytes]:
74
+ if buffer_ is None:
75
+ raise AlreadyFinalized("Context was already finalized.")
76
+
77
+ utils._check_byteslike("data", data)
78
+
79
+ buffer_ += bytes(data)
80
+
81
+ finished_blocks = max(len(buffer_) // (block_size // 8) - 1, 0)
82
+
83
+ result = buffer_[: finished_blocks * (block_size // 8)]
84
+ buffer_ = buffer_[finished_blocks * (block_size // 8) :]
85
+
86
+ return buffer_, result
87
+
88
+
89
+ def _byte_unpadding_check(
90
+ buffer_: bytes | None,
91
+ block_size: int,
92
+ checkfn: typing.Callable[[bytes], int],
93
+ ) -> bytes:
94
+ if buffer_ is None:
95
+ raise AlreadyFinalized("Context was already finalized.")
96
+
97
+ if len(buffer_) != block_size // 8:
98
+ raise ValueError("Invalid padding bytes.")
99
+
100
+ valid = checkfn(buffer_)
101
+
102
+ if not valid:
103
+ raise ValueError("Invalid padding bytes.")
104
+
105
+ pad_size = buffer_[-1]
106
+ return buffer_[:-pad_size]
107
+
108
+
109
+ class PKCS7:
110
+ def __init__(self, block_size: int):
111
+ _byte_padding_check(block_size)
112
+ self.block_size = block_size
113
+
114
+ def padder(self) -> PaddingContext:
115
+ return PKCS7PaddingContext(self.block_size)
116
+
117
+ def unpadder(self) -> PaddingContext:
118
+ return PKCS7UnpaddingContext(self.block_size)
119
+
120
+
121
+ PaddingContext.register(PKCS7PaddingContext)
122
+ PaddingContext.register(PKCS7UnpaddingContext)
123
+
124
+
125
+ class ANSIX923:
126
+ def __init__(self, block_size: int):
127
+ _byte_padding_check(block_size)
128
+ self.block_size = block_size
129
+
130
+ def padder(self) -> PaddingContext:
131
+ return _ANSIX923PaddingContext(self.block_size)
132
+
133
+ def unpadder(self) -> PaddingContext:
134
+ return _ANSIX923UnpaddingContext(self.block_size)
135
+
136
+
137
+ class _ANSIX923PaddingContext(PaddingContext):
138
+ _buffer: bytes | None
139
+
140
+ def __init__(self, block_size: int):
141
+ self.block_size = block_size
142
+ # TODO: more copies than necessary, we should use zero-buffer (#193)
143
+ self._buffer = b""
144
+
145
+ def update(self, data: bytes) -> bytes:
146
+ self._buffer, result = _byte_padding_update(
147
+ self._buffer, data, self.block_size
148
+ )
149
+ return result
150
+
151
+ def _padding(self, size: int) -> bytes:
152
+ return bytes([0]) * (size - 1) + bytes([size])
153
+
154
+ def finalize(self) -> bytes:
155
+ result = _byte_padding_pad(
156
+ self._buffer, self.block_size, self._padding
157
+ )
158
+ self._buffer = None
159
+ return result
160
+
161
+
162
+ class _ANSIX923UnpaddingContext(PaddingContext):
163
+ _buffer: bytes | None
164
+
165
+ def __init__(self, block_size: int):
166
+ self.block_size = block_size
167
+ # TODO: more copies than necessary, we should use zero-buffer (#193)
168
+ self._buffer = b""
169
+
170
+ def update(self, data: bytes) -> bytes:
171
+ self._buffer, result = _byte_unpadding_update(
172
+ self._buffer, data, self.block_size
173
+ )
174
+ return result
175
+
176
+ def finalize(self) -> bytes:
177
+ result = _byte_unpadding_check(
178
+ self._buffer,
179
+ self.block_size,
180
+ check_ansix923_padding,
181
+ )
182
+ self._buffer = None
183
+ return result
lib/python3.10/site-packages/cryptography/hazmat/primitives/serialization/__init__.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.primitives._serialization import (
8
+ BestAvailableEncryption,
9
+ Encoding,
10
+ KeySerializationEncryption,
11
+ NoEncryption,
12
+ ParameterFormat,
13
+ PrivateFormat,
14
+ PublicFormat,
15
+ _KeySerializationEncryption,
16
+ )
17
+ from cryptography.hazmat.primitives.serialization.base import (
18
+ load_der_parameters,
19
+ load_der_private_key,
20
+ load_der_public_key,
21
+ load_pem_parameters,
22
+ load_pem_private_key,
23
+ load_pem_public_key,
24
+ )
25
+ from cryptography.hazmat.primitives.serialization.ssh import (
26
+ SSHCertificate,
27
+ SSHCertificateBuilder,
28
+ SSHCertificateType,
29
+ SSHCertPrivateKeyTypes,
30
+ SSHCertPublicKeyTypes,
31
+ SSHPrivateKeyTypes,
32
+ SSHPublicKeyTypes,
33
+ load_ssh_private_key,
34
+ load_ssh_public_identity,
35
+ load_ssh_public_key,
36
+ )
37
+
38
+ __all__ = [
39
+ "BestAvailableEncryption",
40
+ "Encoding",
41
+ "KeySerializationEncryption",
42
+ "NoEncryption",
43
+ "ParameterFormat",
44
+ "PrivateFormat",
45
+ "PublicFormat",
46
+ "SSHCertPrivateKeyTypes",
47
+ "SSHCertPublicKeyTypes",
48
+ "SSHCertificate",
49
+ "SSHCertificateBuilder",
50
+ "SSHCertificateType",
51
+ "SSHPrivateKeyTypes",
52
+ "SSHPublicKeyTypes",
53
+ "_KeySerializationEncryption",
54
+ "load_der_parameters",
55
+ "load_der_private_key",
56
+ "load_der_public_key",
57
+ "load_pem_parameters",
58
+ "load_pem_private_key",
59
+ "load_pem_public_key",
60
+ "load_ssh_private_key",
61
+ "load_ssh_public_identity",
62
+ "load_ssh_public_key",
63
+ ]
lib/python3.10/site-packages/cryptography/hazmat/primitives/serialization/base.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
6
+
7
+ load_pem_private_key = rust_openssl.keys.load_pem_private_key
8
+ load_der_private_key = rust_openssl.keys.load_der_private_key
9
+
10
+ load_pem_public_key = rust_openssl.keys.load_pem_public_key
11
+ load_der_public_key = rust_openssl.keys.load_der_public_key
12
+
13
+ load_pem_parameters = rust_openssl.dh.from_pem_parameters
14
+ load_der_parameters = rust_openssl.dh.from_der_parameters
lib/python3.10/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import email.base64mime
8
+ import email.generator
9
+ import email.message
10
+ import email.policy
11
+ import io
12
+ import typing
13
+
14
+ from cryptography import utils, x509
15
+ from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
16
+ from cryptography.hazmat.bindings._rust import pkcs7 as rust_pkcs7
17
+ from cryptography.hazmat.primitives import hashes, serialization
18
+ from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
19
+ from cryptography.utils import _check_byteslike
20
+
21
+ load_pem_pkcs7_certificates = rust_pkcs7.load_pem_pkcs7_certificates
22
+
23
+ load_der_pkcs7_certificates = rust_pkcs7.load_der_pkcs7_certificates
24
+
25
+ serialize_certificates = rust_pkcs7.serialize_certificates
26
+
27
+ PKCS7HashTypes = typing.Union[
28
+ hashes.SHA224,
29
+ hashes.SHA256,
30
+ hashes.SHA384,
31
+ hashes.SHA512,
32
+ ]
33
+
34
+ PKCS7PrivateKeyTypes = typing.Union[
35
+ rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey
36
+ ]
37
+
38
+
39
+ class PKCS7Options(utils.Enum):
40
+ Text = "Add text/plain MIME type"
41
+ Binary = "Don't translate input data into canonical MIME format"
42
+ DetachedSignature = "Don't embed data in the PKCS7 structure"
43
+ NoCapabilities = "Don't embed SMIME capabilities"
44
+ NoAttributes = "Don't embed authenticatedAttributes"
45
+ NoCerts = "Don't embed signer certificate"
46
+
47
+
48
+ class PKCS7SignatureBuilder:
49
+ def __init__(
50
+ self,
51
+ data: bytes | None = None,
52
+ signers: list[
53
+ tuple[
54
+ x509.Certificate,
55
+ PKCS7PrivateKeyTypes,
56
+ PKCS7HashTypes,
57
+ padding.PSS | padding.PKCS1v15 | None,
58
+ ]
59
+ ] = [],
60
+ additional_certs: list[x509.Certificate] = [],
61
+ ):
62
+ self._data = data
63
+ self._signers = signers
64
+ self._additional_certs = additional_certs
65
+
66
+ def set_data(self, data: bytes) -> PKCS7SignatureBuilder:
67
+ _check_byteslike("data", data)
68
+ if self._data is not None:
69
+ raise ValueError("data may only be set once")
70
+
71
+ return PKCS7SignatureBuilder(data, self._signers)
72
+
73
+ def add_signer(
74
+ self,
75
+ certificate: x509.Certificate,
76
+ private_key: PKCS7PrivateKeyTypes,
77
+ hash_algorithm: PKCS7HashTypes,
78
+ *,
79
+ rsa_padding: padding.PSS | padding.PKCS1v15 | None = None,
80
+ ) -> PKCS7SignatureBuilder:
81
+ if not isinstance(
82
+ hash_algorithm,
83
+ (
84
+ hashes.SHA224,
85
+ hashes.SHA256,
86
+ hashes.SHA384,
87
+ hashes.SHA512,
88
+ ),
89
+ ):
90
+ raise TypeError(
91
+ "hash_algorithm must be one of hashes.SHA224, "
92
+ "SHA256, SHA384, or SHA512"
93
+ )
94
+ if not isinstance(certificate, x509.Certificate):
95
+ raise TypeError("certificate must be a x509.Certificate")
96
+
97
+ if not isinstance(
98
+ private_key, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey)
99
+ ):
100
+ raise TypeError("Only RSA & EC keys are supported at this time.")
101
+
102
+ if rsa_padding is not None:
103
+ if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)):
104
+ raise TypeError("Padding must be PSS or PKCS1v15")
105
+ if not isinstance(private_key, rsa.RSAPrivateKey):
106
+ raise TypeError("Padding is only supported for RSA keys")
107
+
108
+ return PKCS7SignatureBuilder(
109
+ self._data,
110
+ [
111
+ *self._signers,
112
+ (certificate, private_key, hash_algorithm, rsa_padding),
113
+ ],
114
+ )
115
+
116
+ def add_certificate(
117
+ self, certificate: x509.Certificate
118
+ ) -> PKCS7SignatureBuilder:
119
+ if not isinstance(certificate, x509.Certificate):
120
+ raise TypeError("certificate must be a x509.Certificate")
121
+
122
+ return PKCS7SignatureBuilder(
123
+ self._data, self._signers, [*self._additional_certs, certificate]
124
+ )
125
+
126
+ def sign(
127
+ self,
128
+ encoding: serialization.Encoding,
129
+ options: typing.Iterable[PKCS7Options],
130
+ backend: typing.Any = None,
131
+ ) -> bytes:
132
+ if len(self._signers) == 0:
133
+ raise ValueError("Must have at least one signer")
134
+ if self._data is None:
135
+ raise ValueError("You must add data to sign")
136
+ options = list(options)
137
+ if not all(isinstance(x, PKCS7Options) for x in options):
138
+ raise ValueError("options must be from the PKCS7Options enum")
139
+ if encoding not in (
140
+ serialization.Encoding.PEM,
141
+ serialization.Encoding.DER,
142
+ serialization.Encoding.SMIME,
143
+ ):
144
+ raise ValueError(
145
+ "Must be PEM, DER, or SMIME from the Encoding enum"
146
+ )
147
+
148
+ # Text is a meaningless option unless it is accompanied by
149
+ # DetachedSignature
150
+ if (
151
+ PKCS7Options.Text in options
152
+ and PKCS7Options.DetachedSignature not in options
153
+ ):
154
+ raise ValueError(
155
+ "When passing the Text option you must also pass "
156
+ "DetachedSignature"
157
+ )
158
+
159
+ if PKCS7Options.Text in options and encoding in (
160
+ serialization.Encoding.DER,
161
+ serialization.Encoding.PEM,
162
+ ):
163
+ raise ValueError(
164
+ "The Text option is only available for SMIME serialization"
165
+ )
166
+
167
+ # No attributes implies no capabilities so we'll error if you try to
168
+ # pass both.
169
+ if (
170
+ PKCS7Options.NoAttributes in options
171
+ and PKCS7Options.NoCapabilities in options
172
+ ):
173
+ raise ValueError(
174
+ "NoAttributes is a superset of NoCapabilities. Do not pass "
175
+ "both values."
176
+ )
177
+
178
+ return rust_pkcs7.sign_and_serialize(self, encoding, options)
179
+
180
+
181
+ class PKCS7EnvelopeBuilder:
182
+ def __init__(
183
+ self,
184
+ *,
185
+ _data: bytes | None = None,
186
+ _recipients: list[x509.Certificate] | None = None,
187
+ ):
188
+ from cryptography.hazmat.backends.openssl.backend import (
189
+ backend as ossl,
190
+ )
191
+
192
+ if not ossl.rsa_encryption_supported(padding=padding.PKCS1v15()):
193
+ raise UnsupportedAlgorithm(
194
+ "RSA with PKCS1 v1.5 padding is not supported by this version"
195
+ " of OpenSSL.",
196
+ _Reasons.UNSUPPORTED_PADDING,
197
+ )
198
+ self._data = _data
199
+ self._recipients = _recipients if _recipients is not None else []
200
+
201
+ def set_data(self, data: bytes) -> PKCS7EnvelopeBuilder:
202
+ _check_byteslike("data", data)
203
+ if self._data is not None:
204
+ raise ValueError("data may only be set once")
205
+
206
+ return PKCS7EnvelopeBuilder(_data=data, _recipients=self._recipients)
207
+
208
+ def add_recipient(
209
+ self,
210
+ certificate: x509.Certificate,
211
+ ) -> PKCS7EnvelopeBuilder:
212
+ if not isinstance(certificate, x509.Certificate):
213
+ raise TypeError("certificate must be a x509.Certificate")
214
+
215
+ if not isinstance(certificate.public_key(), rsa.RSAPublicKey):
216
+ raise TypeError("Only RSA keys are supported at this time.")
217
+
218
+ return PKCS7EnvelopeBuilder(
219
+ _data=self._data,
220
+ _recipients=[
221
+ *self._recipients,
222
+ certificate,
223
+ ],
224
+ )
225
+
226
+ def encrypt(
227
+ self,
228
+ encoding: serialization.Encoding,
229
+ options: typing.Iterable[PKCS7Options],
230
+ ) -> bytes:
231
+ if len(self._recipients) == 0:
232
+ raise ValueError("Must have at least one recipient")
233
+ if self._data is None:
234
+ raise ValueError("You must add data to encrypt")
235
+ options = list(options)
236
+ if not all(isinstance(x, PKCS7Options) for x in options):
237
+ raise ValueError("options must be from the PKCS7Options enum")
238
+ if encoding not in (
239
+ serialization.Encoding.PEM,
240
+ serialization.Encoding.DER,
241
+ serialization.Encoding.SMIME,
242
+ ):
243
+ raise ValueError(
244
+ "Must be PEM, DER, or SMIME from the Encoding enum"
245
+ )
246
+
247
+ # Only allow options that make sense for encryption
248
+ if any(
249
+ opt not in [PKCS7Options.Text, PKCS7Options.Binary]
250
+ for opt in options
251
+ ):
252
+ raise ValueError(
253
+ "Only the following options are supported for encryption: "
254
+ "Text, Binary"
255
+ )
256
+ elif PKCS7Options.Text in options and PKCS7Options.Binary in options:
257
+ # OpenSSL accepts both options at the same time, but ignores Text.
258
+ # We fail defensively to avoid unexpected outputs.
259
+ raise ValueError(
260
+ "Cannot use Binary and Text options at the same time"
261
+ )
262
+
263
+ return rust_pkcs7.encrypt_and_serialize(self, encoding, options)
264
+
265
+
266
+ pkcs7_decrypt_der = rust_pkcs7.decrypt_der
267
+ pkcs7_decrypt_pem = rust_pkcs7.decrypt_pem
268
+ pkcs7_decrypt_smime = rust_pkcs7.decrypt_smime
269
+
270
+
271
+ def _smime_signed_encode(
272
+ data: bytes, signature: bytes, micalg: str, text_mode: bool
273
+ ) -> bytes:
274
+ # This function works pretty hard to replicate what OpenSSL does
275
+ # precisely. For good and for ill.
276
+
277
+ m = email.message.Message()
278
+ m.add_header("MIME-Version", "1.0")
279
+ m.add_header(
280
+ "Content-Type",
281
+ "multipart/signed",
282
+ protocol="application/x-pkcs7-signature",
283
+ micalg=micalg,
284
+ )
285
+
286
+ m.preamble = "This is an S/MIME signed message\n"
287
+
288
+ msg_part = OpenSSLMimePart()
289
+ msg_part.set_payload(data)
290
+ if text_mode:
291
+ msg_part.add_header("Content-Type", "text/plain")
292
+ m.attach(msg_part)
293
+
294
+ sig_part = email.message.MIMEPart()
295
+ sig_part.add_header(
296
+ "Content-Type", "application/x-pkcs7-signature", name="smime.p7s"
297
+ )
298
+ sig_part.add_header("Content-Transfer-Encoding", "base64")
299
+ sig_part.add_header(
300
+ "Content-Disposition", "attachment", filename="smime.p7s"
301
+ )
302
+ sig_part.set_payload(
303
+ email.base64mime.body_encode(signature, maxlinelen=65)
304
+ )
305
+ del sig_part["MIME-Version"]
306
+ m.attach(sig_part)
307
+
308
+ fp = io.BytesIO()
309
+ g = email.generator.BytesGenerator(
310
+ fp,
311
+ maxheaderlen=0,
312
+ mangle_from_=False,
313
+ policy=m.policy.clone(linesep="\r\n"),
314
+ )
315
+ g.flatten(m)
316
+ return fp.getvalue()
317
+
318
+
319
+ def _smime_enveloped_encode(data: bytes) -> bytes:
320
+ m = email.message.Message()
321
+ m.add_header("MIME-Version", "1.0")
322
+ m.add_header("Content-Disposition", "attachment", filename="smime.p7m")
323
+ m.add_header(
324
+ "Content-Type",
325
+ "application/pkcs7-mime",
326
+ smime_type="enveloped-data",
327
+ name="smime.p7m",
328
+ )
329
+ m.add_header("Content-Transfer-Encoding", "base64")
330
+
331
+ m.set_payload(email.base64mime.body_encode(data, maxlinelen=65))
332
+
333
+ return m.as_bytes(policy=m.policy.clone(linesep="\n", max_line_length=0))
334
+
335
+
336
+ def _smime_enveloped_decode(data: bytes) -> bytes:
337
+ m = email.message_from_bytes(data)
338
+ if m.get_content_type() not in {
339
+ "application/x-pkcs7-mime",
340
+ "application/pkcs7-mime",
341
+ }:
342
+ raise ValueError("Not an S/MIME enveloped message")
343
+ return bytes(m.get_payload(decode=True))
344
+
345
+
346
+ def _smime_remove_text_headers(data: bytes) -> bytes:
347
+ m = email.message_from_bytes(data)
348
+ # Using get() instead of get_content_type() since it has None as default,
349
+ # where the latter has "text/plain". Both methods are case-insensitive.
350
+ content_type = m.get("content-type")
351
+ if content_type is None:
352
+ raise ValueError(
353
+ "Decrypted MIME data has no 'Content-Type' header. "
354
+ "Please remove the 'Text' option to parse it manually."
355
+ )
356
+ if "text/plain" not in content_type:
357
+ raise ValueError(
358
+ f"Decrypted MIME data content type is '{content_type}', not "
359
+ "'text/plain'. Remove the 'Text' option to parse it manually."
360
+ )
361
+ return bytes(m.get_payload(decode=True))
362
+
363
+
364
+ class OpenSSLMimePart(email.message.MIMEPart):
365
+ # A MIMEPart subclass that replicates OpenSSL's behavior of not including
366
+ # a newline if there are no headers.
367
+ def _write_headers(self, generator) -> None:
368
+ if list(self.raw_items()):
369
+ generator._write_headers(self)
lib/python3.10/site-packages/cryptography/hazmat/primitives/serialization/ssh.py ADDED
@@ -0,0 +1,1569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import binascii
8
+ import enum
9
+ import os
10
+ import re
11
+ import typing
12
+ import warnings
13
+ from base64 import encodebytes as _base64_encode
14
+ from dataclasses import dataclass
15
+
16
+ from cryptography import utils
17
+ from cryptography.exceptions import UnsupportedAlgorithm
18
+ from cryptography.hazmat.primitives import hashes
19
+ from cryptography.hazmat.primitives.asymmetric import (
20
+ dsa,
21
+ ec,
22
+ ed25519,
23
+ padding,
24
+ rsa,
25
+ )
26
+ from cryptography.hazmat.primitives.asymmetric import utils as asym_utils
27
+ from cryptography.hazmat.primitives.ciphers import (
28
+ AEADDecryptionContext,
29
+ Cipher,
30
+ algorithms,
31
+ modes,
32
+ )
33
+ from cryptography.hazmat.primitives.serialization import (
34
+ Encoding,
35
+ KeySerializationEncryption,
36
+ NoEncryption,
37
+ PrivateFormat,
38
+ PublicFormat,
39
+ _KeySerializationEncryption,
40
+ )
41
+
42
+ try:
43
+ from bcrypt import kdf as _bcrypt_kdf
44
+
45
+ _bcrypt_supported = True
46
+ except ImportError:
47
+ _bcrypt_supported = False
48
+
49
+ def _bcrypt_kdf(
50
+ password: bytes,
51
+ salt: bytes,
52
+ desired_key_bytes: int,
53
+ rounds: int,
54
+ ignore_few_rounds: bool = False,
55
+ ) -> bytes:
56
+ raise UnsupportedAlgorithm("Need bcrypt module")
57
+
58
+
59
+ _SSH_ED25519 = b"ssh-ed25519"
60
+ _SSH_RSA = b"ssh-rsa"
61
+ _SSH_DSA = b"ssh-dss"
62
+ _ECDSA_NISTP256 = b"ecdsa-sha2-nistp256"
63
+ _ECDSA_NISTP384 = b"ecdsa-sha2-nistp384"
64
+ _ECDSA_NISTP521 = b"ecdsa-sha2-nistp521"
65
+ _CERT_SUFFIX = b"-cert-v01@openssh.com"
66
+
67
+ # U2F application string suffixed pubkey
68
+ _SK_SSH_ED25519 = b"sk-ssh-ed25519@openssh.com"
69
+ _SK_SSH_ECDSA_NISTP256 = b"sk-ecdsa-sha2-nistp256@openssh.com"
70
+
71
+ # These are not key types, only algorithms, so they cannot appear
72
+ # as a public key type
73
+ _SSH_RSA_SHA256 = b"rsa-sha2-256"
74
+ _SSH_RSA_SHA512 = b"rsa-sha2-512"
75
+
76
+ _SSH_PUBKEY_RC = re.compile(rb"\A(\S+)[ \t]+(\S+)")
77
+ _SK_MAGIC = b"openssh-key-v1\0"
78
+ _SK_START = b"-----BEGIN OPENSSH PRIVATE KEY-----"
79
+ _SK_END = b"-----END OPENSSH PRIVATE KEY-----"
80
+ _BCRYPT = b"bcrypt"
81
+ _NONE = b"none"
82
+ _DEFAULT_CIPHER = b"aes256-ctr"
83
+ _DEFAULT_ROUNDS = 16
84
+
85
+ # re is only way to work on bytes-like data
86
+ _PEM_RC = re.compile(_SK_START + b"(.*?)" + _SK_END, re.DOTALL)
87
+
88
+ # padding for max blocksize
89
+ _PADDING = memoryview(bytearray(range(1, 1 + 16)))
90
+
91
+
92
+ @dataclass
93
+ class _SSHCipher:
94
+ alg: type[algorithms.AES]
95
+ key_len: int
96
+ mode: type[modes.CTR] | type[modes.CBC] | type[modes.GCM]
97
+ block_len: int
98
+ iv_len: int
99
+ tag_len: int | None
100
+ is_aead: bool
101
+
102
+
103
+ # ciphers that are actually used in key wrapping
104
+ _SSH_CIPHERS: dict[bytes, _SSHCipher] = {
105
+ b"aes256-ctr": _SSHCipher(
106
+ alg=algorithms.AES,
107
+ key_len=32,
108
+ mode=modes.CTR,
109
+ block_len=16,
110
+ iv_len=16,
111
+ tag_len=None,
112
+ is_aead=False,
113
+ ),
114
+ b"aes256-cbc": _SSHCipher(
115
+ alg=algorithms.AES,
116
+ key_len=32,
117
+ mode=modes.CBC,
118
+ block_len=16,
119
+ iv_len=16,
120
+ tag_len=None,
121
+ is_aead=False,
122
+ ),
123
+ b"aes256-gcm@openssh.com": _SSHCipher(
124
+ alg=algorithms.AES,
125
+ key_len=32,
126
+ mode=modes.GCM,
127
+ block_len=16,
128
+ iv_len=12,
129
+ tag_len=16,
130
+ is_aead=True,
131
+ ),
132
+ }
133
+
134
+ # map local curve name to key type
135
+ _ECDSA_KEY_TYPE = {
136
+ "secp256r1": _ECDSA_NISTP256,
137
+ "secp384r1": _ECDSA_NISTP384,
138
+ "secp521r1": _ECDSA_NISTP521,
139
+ }
140
+
141
+
142
+ def _get_ssh_key_type(key: SSHPrivateKeyTypes | SSHPublicKeyTypes) -> bytes:
143
+ if isinstance(key, ec.EllipticCurvePrivateKey):
144
+ key_type = _ecdsa_key_type(key.public_key())
145
+ elif isinstance(key, ec.EllipticCurvePublicKey):
146
+ key_type = _ecdsa_key_type(key)
147
+ elif isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)):
148
+ key_type = _SSH_RSA
149
+ elif isinstance(key, (dsa.DSAPrivateKey, dsa.DSAPublicKey)):
150
+ key_type = _SSH_DSA
151
+ elif isinstance(
152
+ key, (ed25519.Ed25519PrivateKey, ed25519.Ed25519PublicKey)
153
+ ):
154
+ key_type = _SSH_ED25519
155
+ else:
156
+ raise ValueError("Unsupported key type")
157
+
158
+ return key_type
159
+
160
+
161
+ def _ecdsa_key_type(public_key: ec.EllipticCurvePublicKey) -> bytes:
162
+ """Return SSH key_type and curve_name for private key."""
163
+ curve = public_key.curve
164
+ if curve.name not in _ECDSA_KEY_TYPE:
165
+ raise ValueError(
166
+ f"Unsupported curve for ssh private key: {curve.name!r}"
167
+ )
168
+ return _ECDSA_KEY_TYPE[curve.name]
169
+
170
+
171
+ def _ssh_pem_encode(
172
+ data: bytes,
173
+ prefix: bytes = _SK_START + b"\n",
174
+ suffix: bytes = _SK_END + b"\n",
175
+ ) -> bytes:
176
+ return b"".join([prefix, _base64_encode(data), suffix])
177
+
178
+
179
+ def _check_block_size(data: bytes, block_len: int) -> None:
180
+ """Require data to be full blocks"""
181
+ if not data or len(data) % block_len != 0:
182
+ raise ValueError("Corrupt data: missing padding")
183
+
184
+
185
+ def _check_empty(data: bytes) -> None:
186
+ """All data should have been parsed."""
187
+ if data:
188
+ raise ValueError("Corrupt data: unparsed data")
189
+
190
+
191
+ def _init_cipher(
192
+ ciphername: bytes,
193
+ password: bytes | None,
194
+ salt: bytes,
195
+ rounds: int,
196
+ ) -> Cipher[modes.CBC | modes.CTR | modes.GCM]:
197
+ """Generate key + iv and return cipher."""
198
+ if not password:
199
+ raise ValueError("Key is password-protected.")
200
+
201
+ ciph = _SSH_CIPHERS[ciphername]
202
+ seed = _bcrypt_kdf(
203
+ password, salt, ciph.key_len + ciph.iv_len, rounds, True
204
+ )
205
+ return Cipher(
206
+ ciph.alg(seed[: ciph.key_len]),
207
+ ciph.mode(seed[ciph.key_len :]),
208
+ )
209
+
210
+
211
+ def _get_u32(data: memoryview) -> tuple[int, memoryview]:
212
+ """Uint32"""
213
+ if len(data) < 4:
214
+ raise ValueError("Invalid data")
215
+ return int.from_bytes(data[:4], byteorder="big"), data[4:]
216
+
217
+
218
+ def _get_u64(data: memoryview) -> tuple[int, memoryview]:
219
+ """Uint64"""
220
+ if len(data) < 8:
221
+ raise ValueError("Invalid data")
222
+ return int.from_bytes(data[:8], byteorder="big"), data[8:]
223
+
224
+
225
+ def _get_sshstr(data: memoryview) -> tuple[memoryview, memoryview]:
226
+ """Bytes with u32 length prefix"""
227
+ n, data = _get_u32(data)
228
+ if n > len(data):
229
+ raise ValueError("Invalid data")
230
+ return data[:n], data[n:]
231
+
232
+
233
+ def _get_mpint(data: memoryview) -> tuple[int, memoryview]:
234
+ """Big integer."""
235
+ val, data = _get_sshstr(data)
236
+ if val and val[0] > 0x7F:
237
+ raise ValueError("Invalid data")
238
+ return int.from_bytes(val, "big"), data
239
+
240
+
241
+ def _to_mpint(val: int) -> bytes:
242
+ """Storage format for signed bigint."""
243
+ if val < 0:
244
+ raise ValueError("negative mpint not allowed")
245
+ if not val:
246
+ return b""
247
+ nbytes = (val.bit_length() + 8) // 8
248
+ return utils.int_to_bytes(val, nbytes)
249
+
250
+
251
+ class _FragList:
252
+ """Build recursive structure without data copy."""
253
+
254
+ flist: list[bytes]
255
+
256
+ def __init__(self, init: list[bytes] | None = None) -> None:
257
+ self.flist = []
258
+ if init:
259
+ self.flist.extend(init)
260
+
261
+ def put_raw(self, val: bytes) -> None:
262
+ """Add plain bytes"""
263
+ self.flist.append(val)
264
+
265
+ def put_u32(self, val: int) -> None:
266
+ """Big-endian uint32"""
267
+ self.flist.append(val.to_bytes(length=4, byteorder="big"))
268
+
269
+ def put_u64(self, val: int) -> None:
270
+ """Big-endian uint64"""
271
+ self.flist.append(val.to_bytes(length=8, byteorder="big"))
272
+
273
+ def put_sshstr(self, val: bytes | _FragList) -> None:
274
+ """Bytes prefixed with u32 length"""
275
+ if isinstance(val, (bytes, memoryview, bytearray)):
276
+ self.put_u32(len(val))
277
+ self.flist.append(val)
278
+ else:
279
+ self.put_u32(val.size())
280
+ self.flist.extend(val.flist)
281
+
282
+ def put_mpint(self, val: int) -> None:
283
+ """Big-endian bigint prefixed with u32 length"""
284
+ self.put_sshstr(_to_mpint(val))
285
+
286
+ def size(self) -> int:
287
+ """Current number of bytes"""
288
+ return sum(map(len, self.flist))
289
+
290
+ def render(self, dstbuf: memoryview, pos: int = 0) -> int:
291
+ """Write into bytearray"""
292
+ for frag in self.flist:
293
+ flen = len(frag)
294
+ start, pos = pos, pos + flen
295
+ dstbuf[start:pos] = frag
296
+ return pos
297
+
298
+ def tobytes(self) -> bytes:
299
+ """Return as bytes"""
300
+ buf = memoryview(bytearray(self.size()))
301
+ self.render(buf)
302
+ return buf.tobytes()
303
+
304
+
305
+ class _SSHFormatRSA:
306
+ """Format for RSA keys.
307
+
308
+ Public:
309
+ mpint e, n
310
+ Private:
311
+ mpint n, e, d, iqmp, p, q
312
+ """
313
+
314
+ def get_public(
315
+ self, data: memoryview
316
+ ) -> tuple[tuple[int, int], memoryview]:
317
+ """RSA public fields"""
318
+ e, data = _get_mpint(data)
319
+ n, data = _get_mpint(data)
320
+ return (e, n), data
321
+
322
+ def load_public(
323
+ self, data: memoryview
324
+ ) -> tuple[rsa.RSAPublicKey, memoryview]:
325
+ """Make RSA public key from data."""
326
+ (e, n), data = self.get_public(data)
327
+ public_numbers = rsa.RSAPublicNumbers(e, n)
328
+ public_key = public_numbers.public_key()
329
+ return public_key, data
330
+
331
+ def load_private(
332
+ self, data: memoryview, pubfields
333
+ ) -> tuple[rsa.RSAPrivateKey, memoryview]:
334
+ """Make RSA private key from data."""
335
+ n, data = _get_mpint(data)
336
+ e, data = _get_mpint(data)
337
+ d, data = _get_mpint(data)
338
+ iqmp, data = _get_mpint(data)
339
+ p, data = _get_mpint(data)
340
+ q, data = _get_mpint(data)
341
+
342
+ if (e, n) != pubfields:
343
+ raise ValueError("Corrupt data: rsa field mismatch")
344
+ dmp1 = rsa.rsa_crt_dmp1(d, p)
345
+ dmq1 = rsa.rsa_crt_dmq1(d, q)
346
+ public_numbers = rsa.RSAPublicNumbers(e, n)
347
+ private_numbers = rsa.RSAPrivateNumbers(
348
+ p, q, d, dmp1, dmq1, iqmp, public_numbers
349
+ )
350
+ private_key = private_numbers.private_key()
351
+ return private_key, data
352
+
353
+ def encode_public(
354
+ self, public_key: rsa.RSAPublicKey, f_pub: _FragList
355
+ ) -> None:
356
+ """Write RSA public key"""
357
+ pubn = public_key.public_numbers()
358
+ f_pub.put_mpint(pubn.e)
359
+ f_pub.put_mpint(pubn.n)
360
+
361
+ def encode_private(
362
+ self, private_key: rsa.RSAPrivateKey, f_priv: _FragList
363
+ ) -> None:
364
+ """Write RSA private key"""
365
+ private_numbers = private_key.private_numbers()
366
+ public_numbers = private_numbers.public_numbers
367
+
368
+ f_priv.put_mpint(public_numbers.n)
369
+ f_priv.put_mpint(public_numbers.e)
370
+
371
+ f_priv.put_mpint(private_numbers.d)
372
+ f_priv.put_mpint(private_numbers.iqmp)
373
+ f_priv.put_mpint(private_numbers.p)
374
+ f_priv.put_mpint(private_numbers.q)
375
+
376
+
377
+ class _SSHFormatDSA:
378
+ """Format for DSA keys.
379
+
380
+ Public:
381
+ mpint p, q, g, y
382
+ Private:
383
+ mpint p, q, g, y, x
384
+ """
385
+
386
+ def get_public(self, data: memoryview) -> tuple[tuple, memoryview]:
387
+ """DSA public fields"""
388
+ p, data = _get_mpint(data)
389
+ q, data = _get_mpint(data)
390
+ g, data = _get_mpint(data)
391
+ y, data = _get_mpint(data)
392
+ return (p, q, g, y), data
393
+
394
+ def load_public(
395
+ self, data: memoryview
396
+ ) -> tuple[dsa.DSAPublicKey, memoryview]:
397
+ """Make DSA public key from data."""
398
+ (p, q, g, y), data = self.get_public(data)
399
+ parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
400
+ public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)
401
+ self._validate(public_numbers)
402
+ public_key = public_numbers.public_key()
403
+ return public_key, data
404
+
405
+ def load_private(
406
+ self, data: memoryview, pubfields
407
+ ) -> tuple[dsa.DSAPrivateKey, memoryview]:
408
+ """Make DSA private key from data."""
409
+ (p, q, g, y), data = self.get_public(data)
410
+ x, data = _get_mpint(data)
411
+
412
+ if (p, q, g, y) != pubfields:
413
+ raise ValueError("Corrupt data: dsa field mismatch")
414
+ parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
415
+ public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)
416
+ self._validate(public_numbers)
417
+ private_numbers = dsa.DSAPrivateNumbers(x, public_numbers)
418
+ private_key = private_numbers.private_key()
419
+ return private_key, data
420
+
421
+ def encode_public(
422
+ self, public_key: dsa.DSAPublicKey, f_pub: _FragList
423
+ ) -> None:
424
+ """Write DSA public key"""
425
+ public_numbers = public_key.public_numbers()
426
+ parameter_numbers = public_numbers.parameter_numbers
427
+ self._validate(public_numbers)
428
+
429
+ f_pub.put_mpint(parameter_numbers.p)
430
+ f_pub.put_mpint(parameter_numbers.q)
431
+ f_pub.put_mpint(parameter_numbers.g)
432
+ f_pub.put_mpint(public_numbers.y)
433
+
434
+ def encode_private(
435
+ self, private_key: dsa.DSAPrivateKey, f_priv: _FragList
436
+ ) -> None:
437
+ """Write DSA private key"""
438
+ self.encode_public(private_key.public_key(), f_priv)
439
+ f_priv.put_mpint(private_key.private_numbers().x)
440
+
441
+ def _validate(self, public_numbers: dsa.DSAPublicNumbers) -> None:
442
+ parameter_numbers = public_numbers.parameter_numbers
443
+ if parameter_numbers.p.bit_length() != 1024:
444
+ raise ValueError("SSH supports only 1024 bit DSA keys")
445
+
446
+
447
+ class _SSHFormatECDSA:
448
+ """Format for ECDSA keys.
449
+
450
+ Public:
451
+ str curve
452
+ bytes point
453
+ Private:
454
+ str curve
455
+ bytes point
456
+ mpint secret
457
+ """
458
+
459
+ def __init__(self, ssh_curve_name: bytes, curve: ec.EllipticCurve):
460
+ self.ssh_curve_name = ssh_curve_name
461
+ self.curve = curve
462
+
463
+ def get_public(
464
+ self, data: memoryview
465
+ ) -> tuple[tuple[memoryview, memoryview], memoryview]:
466
+ """ECDSA public fields"""
467
+ curve, data = _get_sshstr(data)
468
+ point, data = _get_sshstr(data)
469
+ if curve != self.ssh_curve_name:
470
+ raise ValueError("Curve name mismatch")
471
+ if point[0] != 4:
472
+ raise NotImplementedError("Need uncompressed point")
473
+ return (curve, point), data
474
+
475
+ def load_public(
476
+ self, data: memoryview
477
+ ) -> tuple[ec.EllipticCurvePublicKey, memoryview]:
478
+ """Make ECDSA public key from data."""
479
+ (_, point), data = self.get_public(data)
480
+ public_key = ec.EllipticCurvePublicKey.from_encoded_point(
481
+ self.curve, point.tobytes()
482
+ )
483
+ return public_key, data
484
+
485
+ def load_private(
486
+ self, data: memoryview, pubfields
487
+ ) -> tuple[ec.EllipticCurvePrivateKey, memoryview]:
488
+ """Make ECDSA private key from data."""
489
+ (curve_name, point), data = self.get_public(data)
490
+ secret, data = _get_mpint(data)
491
+
492
+ if (curve_name, point) != pubfields:
493
+ raise ValueError("Corrupt data: ecdsa field mismatch")
494
+ private_key = ec.derive_private_key(secret, self.curve)
495
+ return private_key, data
496
+
497
+ def encode_public(
498
+ self, public_key: ec.EllipticCurvePublicKey, f_pub: _FragList
499
+ ) -> None:
500
+ """Write ECDSA public key"""
501
+ point = public_key.public_bytes(
502
+ Encoding.X962, PublicFormat.UncompressedPoint
503
+ )
504
+ f_pub.put_sshstr(self.ssh_curve_name)
505
+ f_pub.put_sshstr(point)
506
+
507
+ def encode_private(
508
+ self, private_key: ec.EllipticCurvePrivateKey, f_priv: _FragList
509
+ ) -> None:
510
+ """Write ECDSA private key"""
511
+ public_key = private_key.public_key()
512
+ private_numbers = private_key.private_numbers()
513
+
514
+ self.encode_public(public_key, f_priv)
515
+ f_priv.put_mpint(private_numbers.private_value)
516
+
517
+
518
+ class _SSHFormatEd25519:
519
+ """Format for Ed25519 keys.
520
+
521
+ Public:
522
+ bytes point
523
+ Private:
524
+ bytes point
525
+ bytes secret_and_point
526
+ """
527
+
528
+ def get_public(
529
+ self, data: memoryview
530
+ ) -> tuple[tuple[memoryview], memoryview]:
531
+ """Ed25519 public fields"""
532
+ point, data = _get_sshstr(data)
533
+ return (point,), data
534
+
535
+ def load_public(
536
+ self, data: memoryview
537
+ ) -> tuple[ed25519.Ed25519PublicKey, memoryview]:
538
+ """Make Ed25519 public key from data."""
539
+ (point,), data = self.get_public(data)
540
+ public_key = ed25519.Ed25519PublicKey.from_public_bytes(
541
+ point.tobytes()
542
+ )
543
+ return public_key, data
544
+
545
+ def load_private(
546
+ self, data: memoryview, pubfields
547
+ ) -> tuple[ed25519.Ed25519PrivateKey, memoryview]:
548
+ """Make Ed25519 private key from data."""
549
+ (point,), data = self.get_public(data)
550
+ keypair, data = _get_sshstr(data)
551
+
552
+ secret = keypair[:32]
553
+ point2 = keypair[32:]
554
+ if point != point2 or (point,) != pubfields:
555
+ raise ValueError("Corrupt data: ed25519 field mismatch")
556
+ private_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret)
557
+ return private_key, data
558
+
559
+ def encode_public(
560
+ self, public_key: ed25519.Ed25519PublicKey, f_pub: _FragList
561
+ ) -> None:
562
+ """Write Ed25519 public key"""
563
+ raw_public_key = public_key.public_bytes(
564
+ Encoding.Raw, PublicFormat.Raw
565
+ )
566
+ f_pub.put_sshstr(raw_public_key)
567
+
568
+ def encode_private(
569
+ self, private_key: ed25519.Ed25519PrivateKey, f_priv: _FragList
570
+ ) -> None:
571
+ """Write Ed25519 private key"""
572
+ public_key = private_key.public_key()
573
+ raw_private_key = private_key.private_bytes(
574
+ Encoding.Raw, PrivateFormat.Raw, NoEncryption()
575
+ )
576
+ raw_public_key = public_key.public_bytes(
577
+ Encoding.Raw, PublicFormat.Raw
578
+ )
579
+ f_keypair = _FragList([raw_private_key, raw_public_key])
580
+
581
+ self.encode_public(public_key, f_priv)
582
+ f_priv.put_sshstr(f_keypair)
583
+
584
+
585
+ def load_application(data) -> tuple[memoryview, memoryview]:
586
+ """
587
+ U2F application strings
588
+ """
589
+ application, data = _get_sshstr(data)
590
+ if not application.tobytes().startswith(b"ssh:"):
591
+ raise ValueError(
592
+ "U2F application string does not start with b'ssh:' "
593
+ f"({application})"
594
+ )
595
+ return application, data
596
+
597
+
598
+ class _SSHFormatSKEd25519:
599
+ """
600
+ The format of a sk-ssh-ed25519@openssh.com public key is:
601
+
602
+ string "sk-ssh-ed25519@openssh.com"
603
+ string public key
604
+ string application (user-specified, but typically "ssh:")
605
+ """
606
+
607
+ def load_public(
608
+ self, data: memoryview
609
+ ) -> tuple[ed25519.Ed25519PublicKey, memoryview]:
610
+ """Make Ed25519 public key from data."""
611
+ public_key, data = _lookup_kformat(_SSH_ED25519).load_public(data)
612
+ _, data = load_application(data)
613
+ return public_key, data
614
+
615
+
616
+ class _SSHFormatSKECDSA:
617
+ """
618
+ The format of a sk-ecdsa-sha2-nistp256@openssh.com public key is:
619
+
620
+ string "sk-ecdsa-sha2-nistp256@openssh.com"
621
+ string curve name
622
+ ec_point Q
623
+ string application (user-specified, but typically "ssh:")
624
+ """
625
+
626
+ def load_public(
627
+ self, data: memoryview
628
+ ) -> tuple[ec.EllipticCurvePublicKey, memoryview]:
629
+ """Make ECDSA public key from data."""
630
+ public_key, data = _lookup_kformat(_ECDSA_NISTP256).load_public(data)
631
+ _, data = load_application(data)
632
+ return public_key, data
633
+
634
+
635
+ _KEY_FORMATS = {
636
+ _SSH_RSA: _SSHFormatRSA(),
637
+ _SSH_DSA: _SSHFormatDSA(),
638
+ _SSH_ED25519: _SSHFormatEd25519(),
639
+ _ECDSA_NISTP256: _SSHFormatECDSA(b"nistp256", ec.SECP256R1()),
640
+ _ECDSA_NISTP384: _SSHFormatECDSA(b"nistp384", ec.SECP384R1()),
641
+ _ECDSA_NISTP521: _SSHFormatECDSA(b"nistp521", ec.SECP521R1()),
642
+ _SK_SSH_ED25519: _SSHFormatSKEd25519(),
643
+ _SK_SSH_ECDSA_NISTP256: _SSHFormatSKECDSA(),
644
+ }
645
+
646
+
647
+ def _lookup_kformat(key_type: bytes):
648
+ """Return valid format or throw error"""
649
+ if not isinstance(key_type, bytes):
650
+ key_type = memoryview(key_type).tobytes()
651
+ if key_type in _KEY_FORMATS:
652
+ return _KEY_FORMATS[key_type]
653
+ raise UnsupportedAlgorithm(f"Unsupported key type: {key_type!r}")
654
+
655
+
656
+ SSHPrivateKeyTypes = typing.Union[
657
+ ec.EllipticCurvePrivateKey,
658
+ rsa.RSAPrivateKey,
659
+ dsa.DSAPrivateKey,
660
+ ed25519.Ed25519PrivateKey,
661
+ ]
662
+
663
+
664
+ def load_ssh_private_key(
665
+ data: bytes,
666
+ password: bytes | None,
667
+ backend: typing.Any = None,
668
+ ) -> SSHPrivateKeyTypes:
669
+ """Load private key from OpenSSH custom encoding."""
670
+ utils._check_byteslike("data", data)
671
+ if password is not None:
672
+ utils._check_bytes("password", password)
673
+
674
+ m = _PEM_RC.search(data)
675
+ if not m:
676
+ raise ValueError("Not OpenSSH private key format")
677
+ p1 = m.start(1)
678
+ p2 = m.end(1)
679
+ data = binascii.a2b_base64(memoryview(data)[p1:p2])
680
+ if not data.startswith(_SK_MAGIC):
681
+ raise ValueError("Not OpenSSH private key format")
682
+ data = memoryview(data)[len(_SK_MAGIC) :]
683
+
684
+ # parse header
685
+ ciphername, data = _get_sshstr(data)
686
+ kdfname, data = _get_sshstr(data)
687
+ kdfoptions, data = _get_sshstr(data)
688
+ nkeys, data = _get_u32(data)
689
+ if nkeys != 1:
690
+ raise ValueError("Only one key supported")
691
+
692
+ # load public key data
693
+ pubdata, data = _get_sshstr(data)
694
+ pub_key_type, pubdata = _get_sshstr(pubdata)
695
+ kformat = _lookup_kformat(pub_key_type)
696
+ pubfields, pubdata = kformat.get_public(pubdata)
697
+ _check_empty(pubdata)
698
+
699
+ if (ciphername, kdfname) != (_NONE, _NONE):
700
+ ciphername_bytes = ciphername.tobytes()
701
+ if ciphername_bytes not in _SSH_CIPHERS:
702
+ raise UnsupportedAlgorithm(
703
+ f"Unsupported cipher: {ciphername_bytes!r}"
704
+ )
705
+ if kdfname != _BCRYPT:
706
+ raise UnsupportedAlgorithm(f"Unsupported KDF: {kdfname!r}")
707
+ blklen = _SSH_CIPHERS[ciphername_bytes].block_len
708
+ tag_len = _SSH_CIPHERS[ciphername_bytes].tag_len
709
+ # load secret data
710
+ edata, data = _get_sshstr(data)
711
+ # see https://bugzilla.mindrot.org/show_bug.cgi?id=3553 for
712
+ # information about how OpenSSH handles AEAD tags
713
+ if _SSH_CIPHERS[ciphername_bytes].is_aead:
714
+ tag = bytes(data)
715
+ if len(tag) != tag_len:
716
+ raise ValueError("Corrupt data: invalid tag length for cipher")
717
+ else:
718
+ _check_empty(data)
719
+ _check_block_size(edata, blklen)
720
+ salt, kbuf = _get_sshstr(kdfoptions)
721
+ rounds, kbuf = _get_u32(kbuf)
722
+ _check_empty(kbuf)
723
+ ciph = _init_cipher(ciphername_bytes, password, salt.tobytes(), rounds)
724
+ dec = ciph.decryptor()
725
+ edata = memoryview(dec.update(edata))
726
+ if _SSH_CIPHERS[ciphername_bytes].is_aead:
727
+ assert isinstance(dec, AEADDecryptionContext)
728
+ _check_empty(dec.finalize_with_tag(tag))
729
+ else:
730
+ # _check_block_size requires data to be a full block so there
731
+ # should be no output from finalize
732
+ _check_empty(dec.finalize())
733
+ else:
734
+ # load secret data
735
+ edata, data = _get_sshstr(data)
736
+ _check_empty(data)
737
+ blklen = 8
738
+ _check_block_size(edata, blklen)
739
+ ck1, edata = _get_u32(edata)
740
+ ck2, edata = _get_u32(edata)
741
+ if ck1 != ck2:
742
+ raise ValueError("Corrupt data: broken checksum")
743
+
744
+ # load per-key struct
745
+ key_type, edata = _get_sshstr(edata)
746
+ if key_type != pub_key_type:
747
+ raise ValueError("Corrupt data: key type mismatch")
748
+ private_key, edata = kformat.load_private(edata, pubfields)
749
+ # We don't use the comment
750
+ _, edata = _get_sshstr(edata)
751
+
752
+ # yes, SSH does padding check *after* all other parsing is done.
753
+ # need to follow as it writes zero-byte padding too.
754
+ if edata != _PADDING[: len(edata)]:
755
+ raise ValueError("Corrupt data: invalid padding")
756
+
757
+ if isinstance(private_key, dsa.DSAPrivateKey):
758
+ warnings.warn(
759
+ "SSH DSA keys are deprecated and will be removed in a future "
760
+ "release.",
761
+ utils.DeprecatedIn40,
762
+ stacklevel=2,
763
+ )
764
+
765
+ return private_key
766
+
767
+
768
+ def _serialize_ssh_private_key(
769
+ private_key: SSHPrivateKeyTypes,
770
+ password: bytes,
771
+ encryption_algorithm: KeySerializationEncryption,
772
+ ) -> bytes:
773
+ """Serialize private key with OpenSSH custom encoding."""
774
+ utils._check_bytes("password", password)
775
+ if isinstance(private_key, dsa.DSAPrivateKey):
776
+ warnings.warn(
777
+ "SSH DSA key support is deprecated and will be "
778
+ "removed in a future release",
779
+ utils.DeprecatedIn40,
780
+ stacklevel=4,
781
+ )
782
+
783
+ key_type = _get_ssh_key_type(private_key)
784
+ kformat = _lookup_kformat(key_type)
785
+
786
+ # setup parameters
787
+ f_kdfoptions = _FragList()
788
+ if password:
789
+ ciphername = _DEFAULT_CIPHER
790
+ blklen = _SSH_CIPHERS[ciphername].block_len
791
+ kdfname = _BCRYPT
792
+ rounds = _DEFAULT_ROUNDS
793
+ if (
794
+ isinstance(encryption_algorithm, _KeySerializationEncryption)
795
+ and encryption_algorithm._kdf_rounds is not None
796
+ ):
797
+ rounds = encryption_algorithm._kdf_rounds
798
+ salt = os.urandom(16)
799
+ f_kdfoptions.put_sshstr(salt)
800
+ f_kdfoptions.put_u32(rounds)
801
+ ciph = _init_cipher(ciphername, password, salt, rounds)
802
+ else:
803
+ ciphername = kdfname = _NONE
804
+ blklen = 8
805
+ ciph = None
806
+ nkeys = 1
807
+ checkval = os.urandom(4)
808
+ comment = b""
809
+
810
+ # encode public and private parts together
811
+ f_public_key = _FragList()
812
+ f_public_key.put_sshstr(key_type)
813
+ kformat.encode_public(private_key.public_key(), f_public_key)
814
+
815
+ f_secrets = _FragList([checkval, checkval])
816
+ f_secrets.put_sshstr(key_type)
817
+ kformat.encode_private(private_key, f_secrets)
818
+ f_secrets.put_sshstr(comment)
819
+ f_secrets.put_raw(_PADDING[: blklen - (f_secrets.size() % blklen)])
820
+
821
+ # top-level structure
822
+ f_main = _FragList()
823
+ f_main.put_raw(_SK_MAGIC)
824
+ f_main.put_sshstr(ciphername)
825
+ f_main.put_sshstr(kdfname)
826
+ f_main.put_sshstr(f_kdfoptions)
827
+ f_main.put_u32(nkeys)
828
+ f_main.put_sshstr(f_public_key)
829
+ f_main.put_sshstr(f_secrets)
830
+
831
+ # copy result info bytearray
832
+ slen = f_secrets.size()
833
+ mlen = f_main.size()
834
+ buf = memoryview(bytearray(mlen + blklen))
835
+ f_main.render(buf)
836
+ ofs = mlen - slen
837
+
838
+ # encrypt in-place
839
+ if ciph is not None:
840
+ ciph.encryptor().update_into(buf[ofs:mlen], buf[ofs:])
841
+
842
+ return _ssh_pem_encode(buf[:mlen])
843
+
844
+
845
+ SSHPublicKeyTypes = typing.Union[
846
+ ec.EllipticCurvePublicKey,
847
+ rsa.RSAPublicKey,
848
+ dsa.DSAPublicKey,
849
+ ed25519.Ed25519PublicKey,
850
+ ]
851
+
852
+ SSHCertPublicKeyTypes = typing.Union[
853
+ ec.EllipticCurvePublicKey,
854
+ rsa.RSAPublicKey,
855
+ ed25519.Ed25519PublicKey,
856
+ ]
857
+
858
+
859
+ class SSHCertificateType(enum.Enum):
860
+ USER = 1
861
+ HOST = 2
862
+
863
+
864
+ class SSHCertificate:
865
+ def __init__(
866
+ self,
867
+ _nonce: memoryview,
868
+ _public_key: SSHPublicKeyTypes,
869
+ _serial: int,
870
+ _cctype: int,
871
+ _key_id: memoryview,
872
+ _valid_principals: list[bytes],
873
+ _valid_after: int,
874
+ _valid_before: int,
875
+ _critical_options: dict[bytes, bytes],
876
+ _extensions: dict[bytes, bytes],
877
+ _sig_type: memoryview,
878
+ _sig_key: memoryview,
879
+ _inner_sig_type: memoryview,
880
+ _signature: memoryview,
881
+ _tbs_cert_body: memoryview,
882
+ _cert_key_type: bytes,
883
+ _cert_body: memoryview,
884
+ ):
885
+ self._nonce = _nonce
886
+ self._public_key = _public_key
887
+ self._serial = _serial
888
+ try:
889
+ self._type = SSHCertificateType(_cctype)
890
+ except ValueError:
891
+ raise ValueError("Invalid certificate type")
892
+ self._key_id = _key_id
893
+ self._valid_principals = _valid_principals
894
+ self._valid_after = _valid_after
895
+ self._valid_before = _valid_before
896
+ self._critical_options = _critical_options
897
+ self._extensions = _extensions
898
+ self._sig_type = _sig_type
899
+ self._sig_key = _sig_key
900
+ self._inner_sig_type = _inner_sig_type
901
+ self._signature = _signature
902
+ self._cert_key_type = _cert_key_type
903
+ self._cert_body = _cert_body
904
+ self._tbs_cert_body = _tbs_cert_body
905
+
906
+ @property
907
+ def nonce(self) -> bytes:
908
+ return bytes(self._nonce)
909
+
910
+ def public_key(self) -> SSHCertPublicKeyTypes:
911
+ # make mypy happy until we remove DSA support entirely and
912
+ # the underlying union won't have a disallowed type
913
+ return typing.cast(SSHCertPublicKeyTypes, self._public_key)
914
+
915
+ @property
916
+ def serial(self) -> int:
917
+ return self._serial
918
+
919
+ @property
920
+ def type(self) -> SSHCertificateType:
921
+ return self._type
922
+
923
+ @property
924
+ def key_id(self) -> bytes:
925
+ return bytes(self._key_id)
926
+
927
+ @property
928
+ def valid_principals(self) -> list[bytes]:
929
+ return self._valid_principals
930
+
931
+ @property
932
+ def valid_before(self) -> int:
933
+ return self._valid_before
934
+
935
+ @property
936
+ def valid_after(self) -> int:
937
+ return self._valid_after
938
+
939
+ @property
940
+ def critical_options(self) -> dict[bytes, bytes]:
941
+ return self._critical_options
942
+
943
+ @property
944
+ def extensions(self) -> dict[bytes, bytes]:
945
+ return self._extensions
946
+
947
+ def signature_key(self) -> SSHCertPublicKeyTypes:
948
+ sigformat = _lookup_kformat(self._sig_type)
949
+ signature_key, sigkey_rest = sigformat.load_public(self._sig_key)
950
+ _check_empty(sigkey_rest)
951
+ return signature_key
952
+
953
+ def public_bytes(self) -> bytes:
954
+ return (
955
+ bytes(self._cert_key_type)
956
+ + b" "
957
+ + binascii.b2a_base64(bytes(self._cert_body), newline=False)
958
+ )
959
+
960
+ def verify_cert_signature(self) -> None:
961
+ signature_key = self.signature_key()
962
+ if isinstance(signature_key, ed25519.Ed25519PublicKey):
963
+ signature_key.verify(
964
+ bytes(self._signature), bytes(self._tbs_cert_body)
965
+ )
966
+ elif isinstance(signature_key, ec.EllipticCurvePublicKey):
967
+ # The signature is encoded as a pair of big-endian integers
968
+ r, data = _get_mpint(self._signature)
969
+ s, data = _get_mpint(data)
970
+ _check_empty(data)
971
+ computed_sig = asym_utils.encode_dss_signature(r, s)
972
+ hash_alg = _get_ec_hash_alg(signature_key.curve)
973
+ signature_key.verify(
974
+ computed_sig, bytes(self._tbs_cert_body), ec.ECDSA(hash_alg)
975
+ )
976
+ else:
977
+ assert isinstance(signature_key, rsa.RSAPublicKey)
978
+ if self._inner_sig_type == _SSH_RSA:
979
+ hash_alg = hashes.SHA1()
980
+ elif self._inner_sig_type == _SSH_RSA_SHA256:
981
+ hash_alg = hashes.SHA256()
982
+ else:
983
+ assert self._inner_sig_type == _SSH_RSA_SHA512
984
+ hash_alg = hashes.SHA512()
985
+ signature_key.verify(
986
+ bytes(self._signature),
987
+ bytes(self._tbs_cert_body),
988
+ padding.PKCS1v15(),
989
+ hash_alg,
990
+ )
991
+
992
+
993
+ def _get_ec_hash_alg(curve: ec.EllipticCurve) -> hashes.HashAlgorithm:
994
+ if isinstance(curve, ec.SECP256R1):
995
+ return hashes.SHA256()
996
+ elif isinstance(curve, ec.SECP384R1):
997
+ return hashes.SHA384()
998
+ else:
999
+ assert isinstance(curve, ec.SECP521R1)
1000
+ return hashes.SHA512()
1001
+
1002
+
1003
+ def _load_ssh_public_identity(
1004
+ data: bytes,
1005
+ _legacy_dsa_allowed=False,
1006
+ ) -> SSHCertificate | SSHPublicKeyTypes:
1007
+ utils._check_byteslike("data", data)
1008
+
1009
+ m = _SSH_PUBKEY_RC.match(data)
1010
+ if not m:
1011
+ raise ValueError("Invalid line format")
1012
+ key_type = orig_key_type = m.group(1)
1013
+ key_body = m.group(2)
1014
+ with_cert = False
1015
+ if key_type.endswith(_CERT_SUFFIX):
1016
+ with_cert = True
1017
+ key_type = key_type[: -len(_CERT_SUFFIX)]
1018
+ if key_type == _SSH_DSA and not _legacy_dsa_allowed:
1019
+ raise UnsupportedAlgorithm(
1020
+ "DSA keys aren't supported in SSH certificates"
1021
+ )
1022
+ kformat = _lookup_kformat(key_type)
1023
+
1024
+ try:
1025
+ rest = memoryview(binascii.a2b_base64(key_body))
1026
+ except (TypeError, binascii.Error):
1027
+ raise ValueError("Invalid format")
1028
+
1029
+ if with_cert:
1030
+ cert_body = rest
1031
+ inner_key_type, rest = _get_sshstr(rest)
1032
+ if inner_key_type != orig_key_type:
1033
+ raise ValueError("Invalid key format")
1034
+ if with_cert:
1035
+ nonce, rest = _get_sshstr(rest)
1036
+ public_key, rest = kformat.load_public(rest)
1037
+ if with_cert:
1038
+ serial, rest = _get_u64(rest)
1039
+ cctype, rest = _get_u32(rest)
1040
+ key_id, rest = _get_sshstr(rest)
1041
+ principals, rest = _get_sshstr(rest)
1042
+ valid_principals = []
1043
+ while principals:
1044
+ principal, principals = _get_sshstr(principals)
1045
+ valid_principals.append(bytes(principal))
1046
+ valid_after, rest = _get_u64(rest)
1047
+ valid_before, rest = _get_u64(rest)
1048
+ crit_options, rest = _get_sshstr(rest)
1049
+ critical_options = _parse_exts_opts(crit_options)
1050
+ exts, rest = _get_sshstr(rest)
1051
+ extensions = _parse_exts_opts(exts)
1052
+ # Get the reserved field, which is unused.
1053
+ _, rest = _get_sshstr(rest)
1054
+ sig_key_raw, rest = _get_sshstr(rest)
1055
+ sig_type, sig_key = _get_sshstr(sig_key_raw)
1056
+ if sig_type == _SSH_DSA and not _legacy_dsa_allowed:
1057
+ raise UnsupportedAlgorithm(
1058
+ "DSA signatures aren't supported in SSH certificates"
1059
+ )
1060
+ # Get the entire cert body and subtract the signature
1061
+ tbs_cert_body = cert_body[: -len(rest)]
1062
+ signature_raw, rest = _get_sshstr(rest)
1063
+ _check_empty(rest)
1064
+ inner_sig_type, sig_rest = _get_sshstr(signature_raw)
1065
+ # RSA certs can have multiple algorithm types
1066
+ if (
1067
+ sig_type == _SSH_RSA
1068
+ and inner_sig_type
1069
+ not in [_SSH_RSA_SHA256, _SSH_RSA_SHA512, _SSH_RSA]
1070
+ ) or (sig_type != _SSH_RSA and inner_sig_type != sig_type):
1071
+ raise ValueError("Signature key type does not match")
1072
+ signature, sig_rest = _get_sshstr(sig_rest)
1073
+ _check_empty(sig_rest)
1074
+ return SSHCertificate(
1075
+ nonce,
1076
+ public_key,
1077
+ serial,
1078
+ cctype,
1079
+ key_id,
1080
+ valid_principals,
1081
+ valid_after,
1082
+ valid_before,
1083
+ critical_options,
1084
+ extensions,
1085
+ sig_type,
1086
+ sig_key,
1087
+ inner_sig_type,
1088
+ signature,
1089
+ tbs_cert_body,
1090
+ orig_key_type,
1091
+ cert_body,
1092
+ )
1093
+ else:
1094
+ _check_empty(rest)
1095
+ return public_key
1096
+
1097
+
1098
+ def load_ssh_public_identity(
1099
+ data: bytes,
1100
+ ) -> SSHCertificate | SSHPublicKeyTypes:
1101
+ return _load_ssh_public_identity(data)
1102
+
1103
+
1104
+ def _parse_exts_opts(exts_opts: memoryview) -> dict[bytes, bytes]:
1105
+ result: dict[bytes, bytes] = {}
1106
+ last_name = None
1107
+ while exts_opts:
1108
+ name, exts_opts = _get_sshstr(exts_opts)
1109
+ bname: bytes = bytes(name)
1110
+ if bname in result:
1111
+ raise ValueError("Duplicate name")
1112
+ if last_name is not None and bname < last_name:
1113
+ raise ValueError("Fields not lexically sorted")
1114
+ value, exts_opts = _get_sshstr(exts_opts)
1115
+ if len(value) > 0:
1116
+ value, extra = _get_sshstr(value)
1117
+ if len(extra) > 0:
1118
+ raise ValueError("Unexpected extra data after value")
1119
+ result[bname] = bytes(value)
1120
+ last_name = bname
1121
+ return result
1122
+
1123
+
1124
+ def load_ssh_public_key(
1125
+ data: bytes, backend: typing.Any = None
1126
+ ) -> SSHPublicKeyTypes:
1127
+ cert_or_key = _load_ssh_public_identity(data, _legacy_dsa_allowed=True)
1128
+ public_key: SSHPublicKeyTypes
1129
+ if isinstance(cert_or_key, SSHCertificate):
1130
+ public_key = cert_or_key.public_key()
1131
+ else:
1132
+ public_key = cert_or_key
1133
+
1134
+ if isinstance(public_key, dsa.DSAPublicKey):
1135
+ warnings.warn(
1136
+ "SSH DSA keys are deprecated and will be removed in a future "
1137
+ "release.",
1138
+ utils.DeprecatedIn40,
1139
+ stacklevel=2,
1140
+ )
1141
+ return public_key
1142
+
1143
+
1144
+ def serialize_ssh_public_key(public_key: SSHPublicKeyTypes) -> bytes:
1145
+ """One-line public key format for OpenSSH"""
1146
+ if isinstance(public_key, dsa.DSAPublicKey):
1147
+ warnings.warn(
1148
+ "SSH DSA key support is deprecated and will be "
1149
+ "removed in a future release",
1150
+ utils.DeprecatedIn40,
1151
+ stacklevel=4,
1152
+ )
1153
+ key_type = _get_ssh_key_type(public_key)
1154
+ kformat = _lookup_kformat(key_type)
1155
+
1156
+ f_pub = _FragList()
1157
+ f_pub.put_sshstr(key_type)
1158
+ kformat.encode_public(public_key, f_pub)
1159
+
1160
+ pub = binascii.b2a_base64(f_pub.tobytes()).strip()
1161
+ return b"".join([key_type, b" ", pub])
1162
+
1163
+
1164
+ SSHCertPrivateKeyTypes = typing.Union[
1165
+ ec.EllipticCurvePrivateKey,
1166
+ rsa.RSAPrivateKey,
1167
+ ed25519.Ed25519PrivateKey,
1168
+ ]
1169
+
1170
+
1171
+ # This is an undocumented limit enforced in the openssh codebase for sshd and
1172
+ # ssh-keygen, but it is undefined in the ssh certificates spec.
1173
+ _SSHKEY_CERT_MAX_PRINCIPALS = 256
1174
+
1175
+
1176
+ class SSHCertificateBuilder:
1177
+ def __init__(
1178
+ self,
1179
+ _public_key: SSHCertPublicKeyTypes | None = None,
1180
+ _serial: int | None = None,
1181
+ _type: SSHCertificateType | None = None,
1182
+ _key_id: bytes | None = None,
1183
+ _valid_principals: list[bytes] = [],
1184
+ _valid_for_all_principals: bool = False,
1185
+ _valid_before: int | None = None,
1186
+ _valid_after: int | None = None,
1187
+ _critical_options: list[tuple[bytes, bytes]] = [],
1188
+ _extensions: list[tuple[bytes, bytes]] = [],
1189
+ ):
1190
+ self._public_key = _public_key
1191
+ self._serial = _serial
1192
+ self._type = _type
1193
+ self._key_id = _key_id
1194
+ self._valid_principals = _valid_principals
1195
+ self._valid_for_all_principals = _valid_for_all_principals
1196
+ self._valid_before = _valid_before
1197
+ self._valid_after = _valid_after
1198
+ self._critical_options = _critical_options
1199
+ self._extensions = _extensions
1200
+
1201
+ def public_key(
1202
+ self, public_key: SSHCertPublicKeyTypes
1203
+ ) -> SSHCertificateBuilder:
1204
+ if not isinstance(
1205
+ public_key,
1206
+ (
1207
+ ec.EllipticCurvePublicKey,
1208
+ rsa.RSAPublicKey,
1209
+ ed25519.Ed25519PublicKey,
1210
+ ),
1211
+ ):
1212
+ raise TypeError("Unsupported key type")
1213
+ if self._public_key is not None:
1214
+ raise ValueError("public_key already set")
1215
+
1216
+ return SSHCertificateBuilder(
1217
+ _public_key=public_key,
1218
+ _serial=self._serial,
1219
+ _type=self._type,
1220
+ _key_id=self._key_id,
1221
+ _valid_principals=self._valid_principals,
1222
+ _valid_for_all_principals=self._valid_for_all_principals,
1223
+ _valid_before=self._valid_before,
1224
+ _valid_after=self._valid_after,
1225
+ _critical_options=self._critical_options,
1226
+ _extensions=self._extensions,
1227
+ )
1228
+
1229
+ def serial(self, serial: int) -> SSHCertificateBuilder:
1230
+ if not isinstance(serial, int):
1231
+ raise TypeError("serial must be an integer")
1232
+ if not 0 <= serial < 2**64:
1233
+ raise ValueError("serial must be between 0 and 2**64")
1234
+ if self._serial is not None:
1235
+ raise ValueError("serial already set")
1236
+
1237
+ return SSHCertificateBuilder(
1238
+ _public_key=self._public_key,
1239
+ _serial=serial,
1240
+ _type=self._type,
1241
+ _key_id=self._key_id,
1242
+ _valid_principals=self._valid_principals,
1243
+ _valid_for_all_principals=self._valid_for_all_principals,
1244
+ _valid_before=self._valid_before,
1245
+ _valid_after=self._valid_after,
1246
+ _critical_options=self._critical_options,
1247
+ _extensions=self._extensions,
1248
+ )
1249
+
1250
+ def type(self, type: SSHCertificateType) -> SSHCertificateBuilder:
1251
+ if not isinstance(type, SSHCertificateType):
1252
+ raise TypeError("type must be an SSHCertificateType")
1253
+ if self._type is not None:
1254
+ raise ValueError("type already set")
1255
+
1256
+ return SSHCertificateBuilder(
1257
+ _public_key=self._public_key,
1258
+ _serial=self._serial,
1259
+ _type=type,
1260
+ _key_id=self._key_id,
1261
+ _valid_principals=self._valid_principals,
1262
+ _valid_for_all_principals=self._valid_for_all_principals,
1263
+ _valid_before=self._valid_before,
1264
+ _valid_after=self._valid_after,
1265
+ _critical_options=self._critical_options,
1266
+ _extensions=self._extensions,
1267
+ )
1268
+
1269
+ def key_id(self, key_id: bytes) -> SSHCertificateBuilder:
1270
+ if not isinstance(key_id, bytes):
1271
+ raise TypeError("key_id must be bytes")
1272
+ if self._key_id is not None:
1273
+ raise ValueError("key_id already set")
1274
+
1275
+ return SSHCertificateBuilder(
1276
+ _public_key=self._public_key,
1277
+ _serial=self._serial,
1278
+ _type=self._type,
1279
+ _key_id=key_id,
1280
+ _valid_principals=self._valid_principals,
1281
+ _valid_for_all_principals=self._valid_for_all_principals,
1282
+ _valid_before=self._valid_before,
1283
+ _valid_after=self._valid_after,
1284
+ _critical_options=self._critical_options,
1285
+ _extensions=self._extensions,
1286
+ )
1287
+
1288
+ def valid_principals(
1289
+ self, valid_principals: list[bytes]
1290
+ ) -> SSHCertificateBuilder:
1291
+ if self._valid_for_all_principals:
1292
+ raise ValueError(
1293
+ "Principals can't be set because the cert is valid "
1294
+ "for all principals"
1295
+ )
1296
+ if (
1297
+ not all(isinstance(x, bytes) for x in valid_principals)
1298
+ or not valid_principals
1299
+ ):
1300
+ raise TypeError(
1301
+ "principals must be a list of bytes and can't be empty"
1302
+ )
1303
+ if self._valid_principals:
1304
+ raise ValueError("valid_principals already set")
1305
+
1306
+ if len(valid_principals) > _SSHKEY_CERT_MAX_PRINCIPALS:
1307
+ raise ValueError(
1308
+ "Reached or exceeded the maximum number of valid_principals"
1309
+ )
1310
+
1311
+ return SSHCertificateBuilder(
1312
+ _public_key=self._public_key,
1313
+ _serial=self._serial,
1314
+ _type=self._type,
1315
+ _key_id=self._key_id,
1316
+ _valid_principals=valid_principals,
1317
+ _valid_for_all_principals=self._valid_for_all_principals,
1318
+ _valid_before=self._valid_before,
1319
+ _valid_after=self._valid_after,
1320
+ _critical_options=self._critical_options,
1321
+ _extensions=self._extensions,
1322
+ )
1323
+
1324
+ def valid_for_all_principals(self):
1325
+ if self._valid_principals:
1326
+ raise ValueError(
1327
+ "valid_principals already set, can't set "
1328
+ "valid_for_all_principals"
1329
+ )
1330
+ if self._valid_for_all_principals:
1331
+ raise ValueError("valid_for_all_principals already set")
1332
+
1333
+ return SSHCertificateBuilder(
1334
+ _public_key=self._public_key,
1335
+ _serial=self._serial,
1336
+ _type=self._type,
1337
+ _key_id=self._key_id,
1338
+ _valid_principals=self._valid_principals,
1339
+ _valid_for_all_principals=True,
1340
+ _valid_before=self._valid_before,
1341
+ _valid_after=self._valid_after,
1342
+ _critical_options=self._critical_options,
1343
+ _extensions=self._extensions,
1344
+ )
1345
+
1346
+ def valid_before(self, valid_before: int | float) -> SSHCertificateBuilder:
1347
+ if not isinstance(valid_before, (int, float)):
1348
+ raise TypeError("valid_before must be an int or float")
1349
+ valid_before = int(valid_before)
1350
+ if valid_before < 0 or valid_before >= 2**64:
1351
+ raise ValueError("valid_before must [0, 2**64)")
1352
+ if self._valid_before is not None:
1353
+ raise ValueError("valid_before already set")
1354
+
1355
+ return SSHCertificateBuilder(
1356
+ _public_key=self._public_key,
1357
+ _serial=self._serial,
1358
+ _type=self._type,
1359
+ _key_id=self._key_id,
1360
+ _valid_principals=self._valid_principals,
1361
+ _valid_for_all_principals=self._valid_for_all_principals,
1362
+ _valid_before=valid_before,
1363
+ _valid_after=self._valid_after,
1364
+ _critical_options=self._critical_options,
1365
+ _extensions=self._extensions,
1366
+ )
1367
+
1368
+ def valid_after(self, valid_after: int | float) -> SSHCertificateBuilder:
1369
+ if not isinstance(valid_after, (int, float)):
1370
+ raise TypeError("valid_after must be an int or float")
1371
+ valid_after = int(valid_after)
1372
+ if valid_after < 0 or valid_after >= 2**64:
1373
+ raise ValueError("valid_after must [0, 2**64)")
1374
+ if self._valid_after is not None:
1375
+ raise ValueError("valid_after already set")
1376
+
1377
+ return SSHCertificateBuilder(
1378
+ _public_key=self._public_key,
1379
+ _serial=self._serial,
1380
+ _type=self._type,
1381
+ _key_id=self._key_id,
1382
+ _valid_principals=self._valid_principals,
1383
+ _valid_for_all_principals=self._valid_for_all_principals,
1384
+ _valid_before=self._valid_before,
1385
+ _valid_after=valid_after,
1386
+ _critical_options=self._critical_options,
1387
+ _extensions=self._extensions,
1388
+ )
1389
+
1390
+ def add_critical_option(
1391
+ self, name: bytes, value: bytes
1392
+ ) -> SSHCertificateBuilder:
1393
+ if not isinstance(name, bytes) or not isinstance(value, bytes):
1394
+ raise TypeError("name and value must be bytes")
1395
+ # This is O(n**2)
1396
+ if name in [name for name, _ in self._critical_options]:
1397
+ raise ValueError("Duplicate critical option name")
1398
+
1399
+ return SSHCertificateBuilder(
1400
+ _public_key=self._public_key,
1401
+ _serial=self._serial,
1402
+ _type=self._type,
1403
+ _key_id=self._key_id,
1404
+ _valid_principals=self._valid_principals,
1405
+ _valid_for_all_principals=self._valid_for_all_principals,
1406
+ _valid_before=self._valid_before,
1407
+ _valid_after=self._valid_after,
1408
+ _critical_options=[*self._critical_options, (name, value)],
1409
+ _extensions=self._extensions,
1410
+ )
1411
+
1412
+ def add_extension(
1413
+ self, name: bytes, value: bytes
1414
+ ) -> SSHCertificateBuilder:
1415
+ if not isinstance(name, bytes) or not isinstance(value, bytes):
1416
+ raise TypeError("name and value must be bytes")
1417
+ # This is O(n**2)
1418
+ if name in [name for name, _ in self._extensions]:
1419
+ raise ValueError("Duplicate extension name")
1420
+
1421
+ return SSHCertificateBuilder(
1422
+ _public_key=self._public_key,
1423
+ _serial=self._serial,
1424
+ _type=self._type,
1425
+ _key_id=self._key_id,
1426
+ _valid_principals=self._valid_principals,
1427
+ _valid_for_all_principals=self._valid_for_all_principals,
1428
+ _valid_before=self._valid_before,
1429
+ _valid_after=self._valid_after,
1430
+ _critical_options=self._critical_options,
1431
+ _extensions=[*self._extensions, (name, value)],
1432
+ )
1433
+
1434
+ def sign(self, private_key: SSHCertPrivateKeyTypes) -> SSHCertificate:
1435
+ if not isinstance(
1436
+ private_key,
1437
+ (
1438
+ ec.EllipticCurvePrivateKey,
1439
+ rsa.RSAPrivateKey,
1440
+ ed25519.Ed25519PrivateKey,
1441
+ ),
1442
+ ):
1443
+ raise TypeError("Unsupported private key type")
1444
+
1445
+ if self._public_key is None:
1446
+ raise ValueError("public_key must be set")
1447
+
1448
+ # Not required
1449
+ serial = 0 if self._serial is None else self._serial
1450
+
1451
+ if self._type is None:
1452
+ raise ValueError("type must be set")
1453
+
1454
+ # Not required
1455
+ key_id = b"" if self._key_id is None else self._key_id
1456
+
1457
+ # A zero length list is valid, but means the certificate
1458
+ # is valid for any principal of the specified type. We require
1459
+ # the user to explicitly set valid_for_all_principals to get
1460
+ # that behavior.
1461
+ if not self._valid_principals and not self._valid_for_all_principals:
1462
+ raise ValueError(
1463
+ "valid_principals must be set if valid_for_all_principals "
1464
+ "is False"
1465
+ )
1466
+
1467
+ if self._valid_before is None:
1468
+ raise ValueError("valid_before must be set")
1469
+
1470
+ if self._valid_after is None:
1471
+ raise ValueError("valid_after must be set")
1472
+
1473
+ if self._valid_after > self._valid_before:
1474
+ raise ValueError("valid_after must be earlier than valid_before")
1475
+
1476
+ # lexically sort our byte strings
1477
+ self._critical_options.sort(key=lambda x: x[0])
1478
+ self._extensions.sort(key=lambda x: x[0])
1479
+
1480
+ key_type = _get_ssh_key_type(self._public_key)
1481
+ cert_prefix = key_type + _CERT_SUFFIX
1482
+
1483
+ # Marshal the bytes to be signed
1484
+ nonce = os.urandom(32)
1485
+ kformat = _lookup_kformat(key_type)
1486
+ f = _FragList()
1487
+ f.put_sshstr(cert_prefix)
1488
+ f.put_sshstr(nonce)
1489
+ kformat.encode_public(self._public_key, f)
1490
+ f.put_u64(serial)
1491
+ f.put_u32(self._type.value)
1492
+ f.put_sshstr(key_id)
1493
+ fprincipals = _FragList()
1494
+ for p in self._valid_principals:
1495
+ fprincipals.put_sshstr(p)
1496
+ f.put_sshstr(fprincipals.tobytes())
1497
+ f.put_u64(self._valid_after)
1498
+ f.put_u64(self._valid_before)
1499
+ fcrit = _FragList()
1500
+ for name, value in self._critical_options:
1501
+ fcrit.put_sshstr(name)
1502
+ if len(value) > 0:
1503
+ foptval = _FragList()
1504
+ foptval.put_sshstr(value)
1505
+ fcrit.put_sshstr(foptval.tobytes())
1506
+ else:
1507
+ fcrit.put_sshstr(value)
1508
+ f.put_sshstr(fcrit.tobytes())
1509
+ fext = _FragList()
1510
+ for name, value in self._extensions:
1511
+ fext.put_sshstr(name)
1512
+ if len(value) > 0:
1513
+ fextval = _FragList()
1514
+ fextval.put_sshstr(value)
1515
+ fext.put_sshstr(fextval.tobytes())
1516
+ else:
1517
+ fext.put_sshstr(value)
1518
+ f.put_sshstr(fext.tobytes())
1519
+ f.put_sshstr(b"") # RESERVED FIELD
1520
+ # encode CA public key
1521
+ ca_type = _get_ssh_key_type(private_key)
1522
+ caformat = _lookup_kformat(ca_type)
1523
+ caf = _FragList()
1524
+ caf.put_sshstr(ca_type)
1525
+ caformat.encode_public(private_key.public_key(), caf)
1526
+ f.put_sshstr(caf.tobytes())
1527
+ # Sigs according to the rules defined for the CA's public key
1528
+ # (RFC4253 section 6.6 for ssh-rsa, RFC5656 for ECDSA,
1529
+ # and RFC8032 for Ed25519).
1530
+ if isinstance(private_key, ed25519.Ed25519PrivateKey):
1531
+ signature = private_key.sign(f.tobytes())
1532
+ fsig = _FragList()
1533
+ fsig.put_sshstr(ca_type)
1534
+ fsig.put_sshstr(signature)
1535
+ f.put_sshstr(fsig.tobytes())
1536
+ elif isinstance(private_key, ec.EllipticCurvePrivateKey):
1537
+ hash_alg = _get_ec_hash_alg(private_key.curve)
1538
+ signature = private_key.sign(f.tobytes(), ec.ECDSA(hash_alg))
1539
+ r, s = asym_utils.decode_dss_signature(signature)
1540
+ fsig = _FragList()
1541
+ fsig.put_sshstr(ca_type)
1542
+ fsigblob = _FragList()
1543
+ fsigblob.put_mpint(r)
1544
+ fsigblob.put_mpint(s)
1545
+ fsig.put_sshstr(fsigblob.tobytes())
1546
+ f.put_sshstr(fsig.tobytes())
1547
+
1548
+ else:
1549
+ assert isinstance(private_key, rsa.RSAPrivateKey)
1550
+ # Just like Golang, we're going to use SHA512 for RSA
1551
+ # https://cs.opensource.google/go/x/crypto/+/refs/tags/
1552
+ # v0.4.0:ssh/certs.go;l=445
1553
+ # RFC 8332 defines SHA256 and 512 as options
1554
+ fsig = _FragList()
1555
+ fsig.put_sshstr(_SSH_RSA_SHA512)
1556
+ signature = private_key.sign(
1557
+ f.tobytes(), padding.PKCS1v15(), hashes.SHA512()
1558
+ )
1559
+ fsig.put_sshstr(signature)
1560
+ f.put_sshstr(fsig.tobytes())
1561
+
1562
+ cert_data = binascii.b2a_base64(f.tobytes()).strip()
1563
+ # load_ssh_public_identity returns a union, but this is
1564
+ # guaranteed to be an SSHCertificate, so we cast to make
1565
+ # mypy happy.
1566
+ return typing.cast(
1567
+ SSHCertificate,
1568
+ load_ssh_public_identity(b"".join([cert_prefix, b" ", cert_data])),
1569
+ )
lib/python3.10/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+
8
+ class InvalidToken(Exception):
9
+ pass
lib/python3.10/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+ import typing
9
+ from urllib.parse import quote, urlencode
10
+
11
+ from cryptography.hazmat.primitives import constant_time, hmac
12
+ from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512
13
+ from cryptography.hazmat.primitives.twofactor import InvalidToken
14
+
15
+ HOTPHashTypes = typing.Union[SHA1, SHA256, SHA512]
16
+
17
+
18
+ def _generate_uri(
19
+ hotp: HOTP,
20
+ type_name: str,
21
+ account_name: str,
22
+ issuer: str | None,
23
+ extra_parameters: list[tuple[str, int]],
24
+ ) -> str:
25
+ parameters = [
26
+ ("digits", hotp._length),
27
+ ("secret", base64.b32encode(hotp._key)),
28
+ ("algorithm", hotp._algorithm.name.upper()),
29
+ ]
30
+
31
+ if issuer is not None:
32
+ parameters.append(("issuer", issuer))
33
+
34
+ parameters.extend(extra_parameters)
35
+
36
+ label = (
37
+ f"{quote(issuer)}:{quote(account_name)}"
38
+ if issuer
39
+ else quote(account_name)
40
+ )
41
+ return f"otpauth://{type_name}/{label}?{urlencode(parameters)}"
42
+
43
+
44
+ class HOTP:
45
+ def __init__(
46
+ self,
47
+ key: bytes,
48
+ length: int,
49
+ algorithm: HOTPHashTypes,
50
+ backend: typing.Any = None,
51
+ enforce_key_length: bool = True,
52
+ ) -> None:
53
+ if len(key) < 16 and enforce_key_length is True:
54
+ raise ValueError("Key length has to be at least 128 bits.")
55
+
56
+ if not isinstance(length, int):
57
+ raise TypeError("Length parameter must be an integer type.")
58
+
59
+ if length < 6 or length > 8:
60
+ raise ValueError("Length of HOTP has to be between 6 and 8.")
61
+
62
+ if not isinstance(algorithm, (SHA1, SHA256, SHA512)):
63
+ raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.")
64
+
65
+ self._key = key
66
+ self._length = length
67
+ self._algorithm = algorithm
68
+
69
+ def generate(self, counter: int) -> bytes:
70
+ if not isinstance(counter, int):
71
+ raise TypeError("Counter parameter must be an integer type.")
72
+
73
+ truncated_value = self._dynamic_truncate(counter)
74
+ hotp = truncated_value % (10**self._length)
75
+ return "{0:0{1}}".format(hotp, self._length).encode()
76
+
77
+ def verify(self, hotp: bytes, counter: int) -> None:
78
+ if not constant_time.bytes_eq(self.generate(counter), hotp):
79
+ raise InvalidToken("Supplied HOTP value does not match.")
80
+
81
+ def _dynamic_truncate(self, counter: int) -> int:
82
+ ctx = hmac.HMAC(self._key, self._algorithm)
83
+
84
+ try:
85
+ ctx.update(counter.to_bytes(length=8, byteorder="big"))
86
+ except OverflowError:
87
+ raise ValueError(f"Counter must be between 0 and {2 ** 64 - 1}.")
88
+
89
+ hmac_value = ctx.finalize()
90
+
91
+ offset = hmac_value[len(hmac_value) - 1] & 0b1111
92
+ p = hmac_value[offset : offset + 4]
93
+ return int.from_bytes(p, byteorder="big") & 0x7FFFFFFF
94
+
95
+ def get_provisioning_uri(
96
+ self, account_name: str, counter: int, issuer: str | None
97
+ ) -> str:
98
+ return _generate_uri(
99
+ self, "hotp", account_name, issuer, [("counter", int(counter))]
100
+ )
lib/python3.10/site-packages/cryptography/hazmat/primitives/twofactor/totp.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from cryptography.hazmat.primitives import constant_time
10
+ from cryptography.hazmat.primitives.twofactor import InvalidToken
11
+ from cryptography.hazmat.primitives.twofactor.hotp import (
12
+ HOTP,
13
+ HOTPHashTypes,
14
+ _generate_uri,
15
+ )
16
+
17
+
18
+ class TOTP:
19
+ def __init__(
20
+ self,
21
+ key: bytes,
22
+ length: int,
23
+ algorithm: HOTPHashTypes,
24
+ time_step: int,
25
+ backend: typing.Any = None,
26
+ enforce_key_length: bool = True,
27
+ ):
28
+ self._time_step = time_step
29
+ self._hotp = HOTP(
30
+ key, length, algorithm, enforce_key_length=enforce_key_length
31
+ )
32
+
33
+ def generate(self, time: int | float) -> bytes:
34
+ if not isinstance(time, (int, float)):
35
+ raise TypeError(
36
+ "Time parameter must be an integer type or float type."
37
+ )
38
+
39
+ counter = int(time / self._time_step)
40
+ return self._hotp.generate(counter)
41
+
42
+ def verify(self, totp: bytes, time: int) -> None:
43
+ if not constant_time.bytes_eq(self.generate(time), totp):
44
+ raise InvalidToken("Supplied TOTP value does not match.")
45
+
46
+ def get_provisioning_uri(
47
+ self, account_name: str, issuer: str | None
48
+ ) -> str:
49
+ return _generate_uri(
50
+ self._hotp,
51
+ "totp",
52
+ account_name,
53
+ issuer,
54
+ [("period", int(self._time_step))],
55
+ )
lib/python3.10/site-packages/cryptography/py.typed ADDED
File without changes
lib/python3.10/site-packages/cryptography/utils.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ from __future__ import annotations
6
+
7
+ import enum
8
+ import sys
9
+ import types
10
+ import typing
11
+ import warnings
12
+
13
+
14
+ # We use a UserWarning subclass, instead of DeprecationWarning, because CPython
15
+ # decided deprecation warnings should be invisible by default.
16
+ class CryptographyDeprecationWarning(UserWarning):
17
+ pass
18
+
19
+
20
+ # Several APIs were deprecated with no specific end-of-life date because of the
21
+ # ubiquity of their use. They should not be removed until we agree on when that
22
+ # cycle ends.
23
+ DeprecatedIn36 = CryptographyDeprecationWarning
24
+ DeprecatedIn37 = CryptographyDeprecationWarning
25
+ DeprecatedIn40 = CryptographyDeprecationWarning
26
+ DeprecatedIn41 = CryptographyDeprecationWarning
27
+ DeprecatedIn42 = CryptographyDeprecationWarning
28
+ DeprecatedIn43 = CryptographyDeprecationWarning
29
+
30
+
31
+ def _check_bytes(name: str, value: bytes) -> None:
32
+ if not isinstance(value, bytes):
33
+ raise TypeError(f"{name} must be bytes")
34
+
35
+
36
+ def _check_byteslike(name: str, value: bytes) -> None:
37
+ try:
38
+ memoryview(value)
39
+ except TypeError:
40
+ raise TypeError(f"{name} must be bytes-like")
41
+
42
+
43
+ def int_to_bytes(integer: int, length: int | None = None) -> bytes:
44
+ if length == 0:
45
+ raise ValueError("length argument can't be 0")
46
+ return integer.to_bytes(
47
+ length or (integer.bit_length() + 7) // 8 or 1, "big"
48
+ )
49
+
50
+
51
+ class InterfaceNotImplemented(Exception):
52
+ pass
53
+
54
+
55
+ class _DeprecatedValue:
56
+ def __init__(self, value: object, message: str, warning_class):
57
+ self.value = value
58
+ self.message = message
59
+ self.warning_class = warning_class
60
+
61
+
62
+ class _ModuleWithDeprecations(types.ModuleType):
63
+ def __init__(self, module: types.ModuleType):
64
+ super().__init__(module.__name__)
65
+ self.__dict__["_module"] = module
66
+
67
+ def __getattr__(self, attr: str) -> object:
68
+ obj = getattr(self._module, attr)
69
+ if isinstance(obj, _DeprecatedValue):
70
+ warnings.warn(obj.message, obj.warning_class, stacklevel=2)
71
+ obj = obj.value
72
+ return obj
73
+
74
+ def __setattr__(self, attr: str, value: object) -> None:
75
+ setattr(self._module, attr, value)
76
+
77
+ def __delattr__(self, attr: str) -> None:
78
+ obj = getattr(self._module, attr)
79
+ if isinstance(obj, _DeprecatedValue):
80
+ warnings.warn(obj.message, obj.warning_class, stacklevel=2)
81
+
82
+ delattr(self._module, attr)
83
+
84
+ def __dir__(self) -> typing.Sequence[str]:
85
+ return ["_module", *dir(self._module)]
86
+
87
+
88
+ def deprecated(
89
+ value: object,
90
+ module_name: str,
91
+ message: str,
92
+ warning_class: type[Warning],
93
+ name: str | None = None,
94
+ ) -> _DeprecatedValue:
95
+ module = sys.modules[module_name]
96
+ if not isinstance(module, _ModuleWithDeprecations):
97
+ sys.modules[module_name] = module = _ModuleWithDeprecations(module)
98
+ dv = _DeprecatedValue(value, message, warning_class)
99
+ # Maintain backwards compatibility with `name is None` for pyOpenSSL.
100
+ if name is not None:
101
+ setattr(module, name, dv)
102
+ return dv
103
+
104
+
105
+ def cached_property(func: typing.Callable) -> property:
106
+ cached_name = f"_cached_{func}"
107
+ sentinel = object()
108
+
109
+ def inner(instance: object):
110
+ cache = getattr(instance, cached_name, sentinel)
111
+ if cache is not sentinel:
112
+ return cache
113
+ result = func(instance)
114
+ setattr(instance, cached_name, result)
115
+ return result
116
+
117
+ return property(inner)
118
+
119
+
120
+ # Python 3.10 changed representation of enums. We use well-defined object
121
+ # representation and string representation from Python 3.9.
122
+ class Enum(enum.Enum):
123
+ def __repr__(self) -> str:
124
+ return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>"
125
+
126
+ def __str__(self) -> str:
127
+ return f"{self.__class__.__name__}.{self._name_}"