Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/PyNaCl-1.6.0.dev1-py3.8-linux-x86_64.egg/nacl/utils.py: 67%
30 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-06 06:06 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-06 06:06 +0000
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.
16import os
17from typing import SupportsBytes, Type, TypeVar
19import nacl.bindings
20from nacl import encoding
22_EncryptedMessage = TypeVar("_EncryptedMessage", bound="EncryptedMessage")
25class EncryptedMessage(bytes):
26 """
27 A bytes subclass that holds a messaged that has been encrypted by a
28 :class:`SecretBox`.
29 """
31 _nonce: bytes
32 _ciphertext: bytes
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
46 @property
47 def nonce(self) -> bytes:
48 """
49 The nonce used during the encryption of the :class:`EncryptedMessage`.
50 """
51 return self._nonce
53 @property
54 def ciphertext(self) -> bytes:
55 """
56 The ciphertext contained within the :class:`EncryptedMessage`.
57 """
58 return self._ciphertext
61class StringFixer:
62 def __str__(self: SupportsBytes) -> str:
63 return str(self.__bytes__())
66def bytes_as_string(bytes_in: bytes) -> str:
67 return bytes_in.decode("ascii")
70def random(size: int = 32) -> bytes:
71 return os.urandom(size)
74def 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
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)
88 return encoder.encode(raw_data)