Debian Codegraph @

src/nacl/utils.py

raw
1 # Copyright 2013 Donald Stufft and individual contributors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 import os
17 from typing import SupportsBytes, Type, TypeVar
18
19 import nacl.bindings
20 from nacl import encoding
21
22 _EncryptedMessage = TypeVar("_EncryptedMessage", bound="EncryptedMessage")
23
24
25 class EncryptedMessage(bytes):
26 """
27 A bytes subclass that holds a messaged that has been encrypted by a
28 :class:`SecretBox`.
29 """
30
31 _nonce: bytes
32 _ciphertext: bytes
33
34 @classmethod
35 def _from_parts(
36 cls: Type[_EncryptedMessage],
37 nonce: bytes,
38 ciphertext: bytes,
39 combined: bytes,
40 ) -> _EncryptedMessage:
41 obj = cls(combined)
42 obj._nonce = nonce
43 obj._ciphertext = ciphertext
44 return obj
45
46 @property
47 def nonce(self) -> bytes:
48 """
49 The nonce used during the encryption of the :class:`EncryptedMessage`.
50 """
51 return self._nonce
52
53 @property
54 def ciphertext(self) -> bytes:
55 """
56 The ciphertext contained within the :class:`EncryptedMessage`.
57 """
58 return self._ciphertext
59
60
61 class StringFixer:
62 def __str__(self: SupportsBytes) -> str:
63 return str(self.__bytes__())
64
65
66 def bytes_as_string(bytes_in: bytes) -> str:
67 return bytes_in.decode("ascii")
68
69
70 def random(size: int = 32) -> bytes:
71 return os.urandom(size)
72
73
74 def randombytes_deterministic(
75 size: int, seed: bytes, encoder: encoding.Encoder = encoding.RawEncoder
76 ) -> bytes:
77 """
78 Returns ``size`` number of deterministically generated pseudorandom bytes
79 from a seed
80
81 :param size: int
82 :param seed: bytes
83 :param encoder: The encoder class used to encode the produced bytes
84 :rtype: bytes
85 """
86 raw_data = nacl.bindings.randombytes_buf_deterministic(size, seed)
87
88 return encoder.encode(raw_data)