Debian Codegraph @

lib/Crypto/Cipher/Salsa20.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Cipher/Salsa20.py : Salsa20 stream cipher (http://cr.yp.to/snuffle.html)
4 #
5 # Contributed by Fabrizio Tarizzo <[email protected]>.
6 #
7 # ===================================================================
8 # The contents of this file are dedicated to the public domain. To
9 # the extent that dedication to the public domain is not available,
10 # everyone is granted a worldwide, perpetual, royalty-free,
11 # non-exclusive license to exercise all rights associated with the
12 # contents of this file for any purpose whatsoever.
13 # No rights are reserved.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 # SOFTWARE.
23 # ===================================================================
24
25 from Crypto.Util.py3compat import _copy_bytes
26 from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
27 create_string_buffer,
28 get_raw_buffer, VoidPointer,
29 SmartPointer, c_size_t,
30 c_uint8_ptr, is_writeable_buffer)
31
32 from Crypto.Random import get_random_bytes
33
34 _raw_salsa20_lib = load_pycryptodome_raw_lib("Crypto.Cipher._Salsa20",
35 """
36 int Salsa20_stream_init(uint8_t *key, size_t keylen,
37 uint8_t *nonce, size_t nonce_len,
38 void **pSalsaState);
39 int Salsa20_stream_destroy(void *salsaState);
40 int Salsa20_stream_encrypt(void *salsaState,
41 const uint8_t in[],
42 uint8_t out[], size_t len);
43 """)
44
45
46 class Salsa20Cipher:
47 """Salsa20 cipher object. Do not create it directly. Use :py:func:`new`
48 instead.
49
50 :var nonce: The nonce with length 8
51 :vartype nonce: byte string
52 """
53
54 def __init__(self, key, nonce):
55 """Initialize a Salsa20 cipher object
56
57 See also `new()` at the module level."""
58
59 if len(key) not in key_size:
60 raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key))
61
62 if len(nonce) != 8:
63 raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" %
64 len(nonce))
65
66 self.nonce = _copy_bytes(None, None, nonce)
67
68 self._state = VoidPointer()
69 result = _raw_salsa20_lib.Salsa20_stream_init(
70 c_uint8_ptr(key),
71 c_size_t(len(key)),
72 c_uint8_ptr(nonce),
73 c_size_t(len(nonce)),
74 self._state.address_of())
75 if result:
76 raise ValueError("Error %d instantiating a Salsa20 cipher")
77 self._state = SmartPointer(self._state.get(),
78 _raw_salsa20_lib.Salsa20_stream_destroy)
79
80 self.block_size = 1
81 self.key_size = len(key)
82
83 def encrypt(self, plaintext, output=None):
84 """Encrypt a piece of data.
85
86 Args:
87 plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size.
88 Keyword Args:
89 output(bytes/bytearray/memoryview): The location where the ciphertext
90 is written to. If ``None``, the ciphertext is returned.
91 Returns:
92 If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
93 Otherwise, ``None``.
94 """
95
96 if output is None:
97 ciphertext = create_string_buffer(len(plaintext))
98 else:
99 ciphertext = output
100
101 if not is_writeable_buffer(output):
102 raise TypeError("output must be a bytearray or a writeable memoryview")
103
104 if len(plaintext) != len(output):
105 raise ValueError("output must have the same length as the input"
106 " (%d bytes)" % len(plaintext))
107
108 result = _raw_salsa20_lib.Salsa20_stream_encrypt(
109 self._state.get(),
110 c_uint8_ptr(plaintext),
111 c_uint8_ptr(ciphertext),
112 c_size_t(len(plaintext)))
113 if result:
114 raise ValueError("Error %d while encrypting with Salsa20" % result)
115
116 if output is None:
117 return get_raw_buffer(ciphertext)
118 else:
119 return None
120
121 def decrypt(self, ciphertext, output=None):
122 """Decrypt a piece of data.
123
124 Args:
125 ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size.
126 Keyword Args:
127 output(bytes/bytearray/memoryview): The location where the plaintext
128 is written to. If ``None``, the plaintext is returned.
129 Returns:
130 If ``output`` is ``None``, the plaintext is returned as ``bytes``.
131 Otherwise, ``None``.
132 """
133
134 try:
135 return self.encrypt(ciphertext, output=output)
136 except ValueError as e:
137 raise ValueError(str(e).replace("enc", "dec"))
138
139
140 def new(key, nonce=None):
141 """Create a new Salsa20 cipher
142
143 :keyword key: The secret key to use. It must be 16 or 32 bytes long.
144 :type key: bytes/bytearray/memoryview
145
146 :keyword nonce:
147 A value that must never be reused for any other encryption
148 done with this key. It must be 8 bytes long.
149
150 If not provided, a random byte string will be generated (you can read
151 it back via the ``nonce`` attribute of the returned object).
152 :type nonce: bytes/bytearray/memoryview
153
154 :Return: a :class:`Crypto.Cipher.Salsa20.Salsa20Cipher` object
155 """
156
157 if nonce is None:
158 nonce = get_random_bytes(8)
159
160 return Salsa20Cipher(key, nonce)
161
162 # Size of a data block (in bytes)
163 block_size = 1
164
165 # Size of a key (in bytes)
166 key_size = (16, 32)
167