Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/INSTALLER +1 -0
- env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/LICENSE.md +31 -0
- env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/METADATA +243 -0
- env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/RECORD +22 -0
- env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/WHEEL +4 -0
- env-llmeval/lib/python3.10/site-packages/sympy/crypto/__init__.py +35 -0
- env-llmeval/lib/python3.10/site-packages/sympy/crypto/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/crypto/__pycache__/crypto.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/crypto/crypto.py +3360 -0
- env-llmeval/lib/python3.10/site-packages/sympy/crypto/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/test_crypto.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py +562 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_gaussopt.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_medium.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_polarization.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_utils.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_waves.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_gaussopt.py +102 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_medium.py +48 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_polarization.py +57 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_utils.py +202 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_waves.py +82 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/quantities.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/cgs.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/length_weight_time.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/mks.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/mksa.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/natural.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/si.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/si.py +377 -0
- env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/INSTALLER +1 -0
- env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/LICENSE +21 -0
- env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/METADATA +162 -0
- env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/RECORD +17 -0
- env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/WHEEL +5 -0
- env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/top_level.txt +1 -0
- env-llmeval/lib/python3.10/site-packages/yaml/__init__.py +390 -0
- env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/composer.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/constructor.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/cyaml.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/dumper.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/emitter.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/error.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/events.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/LICENSE.md
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
BSD 3-Clause License
|
2 |
+
|
3 |
+
Copyright (c) 2013-2024, Kim Davies and contributors.
|
4 |
+
All rights reserved.
|
5 |
+
|
6 |
+
Redistribution and use in source and binary forms, with or without
|
7 |
+
modification, are permitted provided that the following conditions are
|
8 |
+
met:
|
9 |
+
|
10 |
+
1. Redistributions of source code must retain the above copyright
|
11 |
+
notice, this list of conditions and the following disclaimer.
|
12 |
+
|
13 |
+
2. Redistributions in binary form must reproduce the above copyright
|
14 |
+
notice, this list of conditions and the following disclaimer in the
|
15 |
+
documentation and/or other materials provided with the distribution.
|
16 |
+
|
17 |
+
3. Neither the name of the copyright holder nor the names of its
|
18 |
+
contributors may be used to endorse or promote products derived from
|
19 |
+
this software without specific prior written permission.
|
20 |
+
|
21 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
22 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
23 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
24 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
25 |
+
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
26 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
27 |
+
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
28 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
29 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
30 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
31 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/METADATA
ADDED
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: idna
|
3 |
+
Version: 3.7
|
4 |
+
Summary: Internationalized Domain Names in Applications (IDNA)
|
5 |
+
Author-email: Kim Davies <[email protected]>
|
6 |
+
Requires-Python: >=3.5
|
7 |
+
Description-Content-Type: text/x-rst
|
8 |
+
Classifier: Development Status :: 5 - Production/Stable
|
9 |
+
Classifier: Intended Audience :: Developers
|
10 |
+
Classifier: Intended Audience :: System Administrators
|
11 |
+
Classifier: License :: OSI Approved :: BSD License
|
12 |
+
Classifier: Operating System :: OS Independent
|
13 |
+
Classifier: Programming Language :: Python
|
14 |
+
Classifier: Programming Language :: Python :: 3
|
15 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
16 |
+
Classifier: Programming Language :: Python :: 3.5
|
17 |
+
Classifier: Programming Language :: Python :: 3.6
|
18 |
+
Classifier: Programming Language :: Python :: 3.7
|
19 |
+
Classifier: Programming Language :: Python :: 3.8
|
20 |
+
Classifier: Programming Language :: Python :: 3.9
|
21 |
+
Classifier: Programming Language :: Python :: 3.10
|
22 |
+
Classifier: Programming Language :: Python :: 3.11
|
23 |
+
Classifier: Programming Language :: Python :: 3.12
|
24 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
25 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
26 |
+
Classifier: Topic :: Internet :: Name Service (DNS)
|
27 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
28 |
+
Classifier: Topic :: Utilities
|
29 |
+
Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.rst
|
30 |
+
Project-URL: Issue tracker, https://github.com/kjd/idna/issues
|
31 |
+
Project-URL: Source, https://github.com/kjd/idna
|
32 |
+
|
33 |
+
Internationalized Domain Names in Applications (IDNA)
|
34 |
+
=====================================================
|
35 |
+
|
36 |
+
Support for the Internationalized Domain Names in
|
37 |
+
Applications (IDNA) protocol as specified in `RFC 5891
|
38 |
+
<https://tools.ietf.org/html/rfc5891>`_. This is the latest version of
|
39 |
+
the protocol and is sometimes referred to as “IDNA 2008”.
|
40 |
+
|
41 |
+
This library also provides support for Unicode Technical
|
42 |
+
Standard 46, `Unicode IDNA Compatibility Processing
|
43 |
+
<https://unicode.org/reports/tr46/>`_.
|
44 |
+
|
45 |
+
This acts as a suitable replacement for the “encodings.idna”
|
46 |
+
module that comes with the Python standard library, but which
|
47 |
+
only supports the older superseded IDNA specification (`RFC 3490
|
48 |
+
<https://tools.ietf.org/html/rfc3490>`_).
|
49 |
+
|
50 |
+
Basic functions are simply executed:
|
51 |
+
|
52 |
+
.. code-block:: pycon
|
53 |
+
|
54 |
+
>>> import idna
|
55 |
+
>>> idna.encode('ドメイン.テスト')
|
56 |
+
b'xn--eckwd4c7c.xn--zckzah'
|
57 |
+
>>> print(idna.decode('xn--eckwd4c7c.xn--zckzah'))
|
58 |
+
ドメイン.テスト
|
59 |
+
|
60 |
+
|
61 |
+
Installation
|
62 |
+
------------
|
63 |
+
|
64 |
+
This package is available for installation from PyPI:
|
65 |
+
|
66 |
+
.. code-block:: bash
|
67 |
+
|
68 |
+
$ python3 -m pip install idna
|
69 |
+
|
70 |
+
|
71 |
+
Usage
|
72 |
+
-----
|
73 |
+
|
74 |
+
For typical usage, the ``encode`` and ``decode`` functions will take a
|
75 |
+
domain name argument and perform a conversion to A-labels or U-labels
|
76 |
+
respectively.
|
77 |
+
|
78 |
+
.. code-block:: pycon
|
79 |
+
|
80 |
+
>>> import idna
|
81 |
+
>>> idna.encode('ドメイン.テスト')
|
82 |
+
b'xn--eckwd4c7c.xn--zckzah'
|
83 |
+
>>> print(idna.decode('xn--eckwd4c7c.xn--zckzah'))
|
84 |
+
ドメイン.テスト
|
85 |
+
|
86 |
+
You may use the codec encoding and decoding methods using the
|
87 |
+
``idna.codec`` module:
|
88 |
+
|
89 |
+
.. code-block:: pycon
|
90 |
+
|
91 |
+
>>> import idna.codec
|
92 |
+
>>> print('домен.испытание'.encode('idna2008'))
|
93 |
+
b'xn--d1acufc.xn--80akhbyknj4f'
|
94 |
+
>>> print(b'xn--d1acufc.xn--80akhbyknj4f'.decode('idna2008'))
|
95 |
+
домен.испытание
|
96 |
+
|
97 |
+
Conversions can be applied at a per-label basis using the ``ulabel`` or
|
98 |
+
``alabel`` functions if necessary:
|
99 |
+
|
100 |
+
.. code-block:: pycon
|
101 |
+
|
102 |
+
>>> idna.alabel('测试')
|
103 |
+
b'xn--0zwm56d'
|
104 |
+
|
105 |
+
Compatibility Mapping (UTS #46)
|
106 |
+
+++++++++++++++++++++++++++++++
|
107 |
+
|
108 |
+
As described in `RFC 5895 <https://tools.ietf.org/html/rfc5895>`_, the
|
109 |
+
IDNA specification does not normalize input from different potential
|
110 |
+
ways a user may input a domain name. This functionality, known as
|
111 |
+
a “mapping”, is considered by the specification to be a local
|
112 |
+
user-interface issue distinct from IDNA conversion functionality.
|
113 |
+
|
114 |
+
This library provides one such mapping that was developed by the
|
115 |
+
Unicode Consortium. Known as `Unicode IDNA Compatibility Processing
|
116 |
+
<https://unicode.org/reports/tr46/>`_, it provides for both a regular
|
117 |
+
mapping for typical applications, as well as a transitional mapping to
|
118 |
+
help migrate from older IDNA 2003 applications.
|
119 |
+
|
120 |
+
For example, “Königsgäßchen” is not a permissible label as *LATIN
|
121 |
+
CAPITAL LETTER K* is not allowed (nor are capital letters in general).
|
122 |
+
UTS 46 will convert this into lower case prior to applying the IDNA
|
123 |
+
conversion.
|
124 |
+
|
125 |
+
.. code-block:: pycon
|
126 |
+
|
127 |
+
>>> import idna
|
128 |
+
>>> idna.encode('Königsgäßchen')
|
129 |
+
...
|
130 |
+
idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed
|
131 |
+
>>> idna.encode('Königsgäßchen', uts46=True)
|
132 |
+
b'xn--knigsgchen-b4a3dun'
|
133 |
+
>>> print(idna.decode('xn--knigsgchen-b4a3dun'))
|
134 |
+
königsgäßchen
|
135 |
+
|
136 |
+
Transitional processing provides conversions to help transition from
|
137 |
+
the older 2003 standard to the current standard. For example, in the
|
138 |
+
original IDNA specification, the *LATIN SMALL LETTER SHARP S* (ß) was
|
139 |
+
converted into two *LATIN SMALL LETTER S* (ss), whereas in the current
|
140 |
+
IDNA specification this conversion is not performed.
|
141 |
+
|
142 |
+
.. code-block:: pycon
|
143 |
+
|
144 |
+
>>> idna.encode('Königsgäßchen', uts46=True, transitional=True)
|
145 |
+
'xn--knigsgsschen-lcb0w'
|
146 |
+
|
147 |
+
Implementers should use transitional processing with caution, only in
|
148 |
+
rare cases where conversion from legacy labels to current labels must be
|
149 |
+
performed (i.e. IDNA implementations that pre-date 2008). For typical
|
150 |
+
applications that just need to convert labels, transitional processing
|
151 |
+
is unlikely to be beneficial and could produce unexpected incompatible
|
152 |
+
results.
|
153 |
+
|
154 |
+
``encodings.idna`` Compatibility
|
155 |
+
++++++++++++++++++++++++++++++++
|
156 |
+
|
157 |
+
Function calls from the Python built-in ``encodings.idna`` module are
|
158 |
+
mapped to their IDNA 2008 equivalents using the ``idna.compat`` module.
|
159 |
+
Simply substitute the ``import`` clause in your code to refer to the new
|
160 |
+
module name.
|
161 |
+
|
162 |
+
Exceptions
|
163 |
+
----------
|
164 |
+
|
165 |
+
All errors raised during the conversion following the specification
|
166 |
+
should raise an exception derived from the ``idna.IDNAError`` base
|
167 |
+
class.
|
168 |
+
|
169 |
+
More specific exceptions that may be generated as ``idna.IDNABidiError``
|
170 |
+
when the error reflects an illegal combination of left-to-right and
|
171 |
+
right-to-left characters in a label; ``idna.InvalidCodepoint`` when
|
172 |
+
a specific codepoint is an illegal character in an IDN label (i.e.
|
173 |
+
INVALID); and ``idna.InvalidCodepointContext`` when the codepoint is
|
174 |
+
illegal based on its positional context (i.e. it is CONTEXTO or CONTEXTJ
|
175 |
+
but the contextual requirements are not satisfied.)
|
176 |
+
|
177 |
+
Building and Diagnostics
|
178 |
+
------------------------
|
179 |
+
|
180 |
+
The IDNA and UTS 46 functionality relies upon pre-calculated lookup
|
181 |
+
tables for performance. These tables are derived from computing against
|
182 |
+
eligibility criteria in the respective standards. These tables are
|
183 |
+
computed using the command-line script ``tools/idna-data``.
|
184 |
+
|
185 |
+
This tool will fetch relevant codepoint data from the Unicode repository
|
186 |
+
and perform the required calculations to identify eligibility. There are
|
187 |
+
three main modes:
|
188 |
+
|
189 |
+
* ``idna-data make-libdata``. Generates ``idnadata.py`` and
|
190 |
+
``uts46data.py``, the pre-calculated lookup tables used for IDNA and
|
191 |
+
UTS 46 conversions. Implementers who wish to track this library against
|
192 |
+
a different Unicode version may use this tool to manually generate a
|
193 |
+
different version of the ``idnadata.py`` and ``uts46data.py`` files.
|
194 |
+
|
195 |
+
* ``idna-data make-table``. Generate a table of the IDNA disposition
|
196 |
+
(e.g. PVALID, CONTEXTJ, CONTEXTO) in the format found in Appendix
|
197 |
+
B.1 of RFC 5892 and the pre-computed tables published by `IANA
|
198 |
+
<https://www.iana.org/>`_.
|
199 |
+
|
200 |
+
* ``idna-data U+0061``. Prints debugging output on the various
|
201 |
+
properties associated with an individual Unicode codepoint (in this
|
202 |
+
case, U+0061), that are used to assess the IDNA and UTS 46 status of a
|
203 |
+
codepoint. This is helpful in debugging or analysis.
|
204 |
+
|
205 |
+
The tool accepts a number of arguments, described using ``idna-data
|
206 |
+
-h``. Most notably, the ``--version`` argument allows the specification
|
207 |
+
of the version of Unicode to be used in computing the table data. For
|
208 |
+
example, ``idna-data --version 9.0.0 make-libdata`` will generate
|
209 |
+
library data against Unicode 9.0.0.
|
210 |
+
|
211 |
+
|
212 |
+
Additional Notes
|
213 |
+
----------------
|
214 |
+
|
215 |
+
* **Packages**. The latest tagged release version is published in the
|
216 |
+
`Python Package Index <https://pypi.org/project/idna/>`_.
|
217 |
+
|
218 |
+
* **Version support**. This library supports Python 3.5 and higher.
|
219 |
+
As this library serves as a low-level toolkit for a variety of
|
220 |
+
applications, many of which strive for broad compatibility with older
|
221 |
+
Python versions, there is no rush to remove older interpreter support.
|
222 |
+
Removing support for older versions should be well justified in that the
|
223 |
+
maintenance burden has become too high.
|
224 |
+
|
225 |
+
* **Python 2**. Python 2 is supported by version 2.x of this library.
|
226 |
+
While active development of the version 2.x series has ended, notable
|
227 |
+
issues being corrected may be backported to 2.x. Use "idna<3" in your
|
228 |
+
requirements file if you need this library for a Python 2 application.
|
229 |
+
|
230 |
+
* **Testing**. The library has a test suite based on each rule of the
|
231 |
+
IDNA specification, as well as tests that are provided as part of the
|
232 |
+
Unicode Technical Standard 46, `Unicode IDNA Compatibility Processing
|
233 |
+
<https://unicode.org/reports/tr46/>`_.
|
234 |
+
|
235 |
+
* **Emoji**. It is an occasional request to support emoji domains in
|
236 |
+
this library. Encoding of symbols like emoji is expressly prohibited by
|
237 |
+
the technical standard IDNA 2008 and emoji domains are broadly phased
|
238 |
+
out across the domain industry due to associated security risks. For
|
239 |
+
now, applications that need to support these non-compliant labels
|
240 |
+
may wish to consider trying the encode/decode operation in this library
|
241 |
+
first, and then falling back to using `encodings.idna`. See `the Github
|
242 |
+
project <https://github.com/kjd/idna/issues/18>`_ for more discussion.
|
243 |
+
|
env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/RECORD
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
idna-3.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
idna-3.7.dist-info/LICENSE.md,sha256=pZ8LDvNjWHQQmkRhykT_enDVBpboFHZ7-vch1Mmw2w8,1541
|
3 |
+
idna-3.7.dist-info/METADATA,sha256=OixCk-dKLZkPy-MfviOmiPvwJ1O2K_8rqCrFjC_uxy4,9888
|
4 |
+
idna-3.7.dist-info/RECORD,,
|
5 |
+
idna-3.7.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
|
6 |
+
idna/__init__.py,sha256=KJQN1eQBr8iIK5SKrJ47lXvxG0BJ7Lm38W4zT0v_8lk,849
|
7 |
+
idna/__pycache__/__init__.cpython-310.pyc,,
|
8 |
+
idna/__pycache__/codec.cpython-310.pyc,,
|
9 |
+
idna/__pycache__/compat.cpython-310.pyc,,
|
10 |
+
idna/__pycache__/core.cpython-310.pyc,,
|
11 |
+
idna/__pycache__/idnadata.cpython-310.pyc,,
|
12 |
+
idna/__pycache__/intranges.cpython-310.pyc,,
|
13 |
+
idna/__pycache__/package_data.cpython-310.pyc,,
|
14 |
+
idna/__pycache__/uts46data.cpython-310.pyc,,
|
15 |
+
idna/codec.py,sha256=PS6m-XmdST7Wj7J7ulRMakPDt5EBJyYrT3CPtjh-7t4,3426
|
16 |
+
idna/compat.py,sha256=0_sOEUMT4CVw9doD3vyRhX80X19PwqFoUBs7gWsFME4,321
|
17 |
+
idna/core.py,sha256=lyhpoe2vulEaB_65xhXmoKgO-xUqFDvcwxu5hpNNO4E,12663
|
18 |
+
idna/idnadata.py,sha256=dqRwytzkjIHMBa2R1lYvHDwACenZPt8eGVu1Y8UBE-E,78320
|
19 |
+
idna/intranges.py,sha256=YBr4fRYuWH7kTKS2tXlFjM24ZF1Pdvcir-aywniInqg,1881
|
20 |
+
idna/package_data.py,sha256=Tkt0KnIeyIlnHddOaz9WSkkislNgokJAuE-p5GorMqo,21
|
21 |
+
idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
22 |
+
idna/uts46data.py,sha256=1KuksWqLuccPXm2uyRVkhfiFLNIhM_H2m4azCcnOqEU,206503
|
env-llmeval/lib/python3.10/site-packages/idna-3.7.dist-info/WHEEL
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: flit 3.9.0
|
3 |
+
Root-Is-Purelib: true
|
4 |
+
Tag: py3-none-any
|
env-llmeval/lib/python3.10/site-packages/sympy/crypto/__init__.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.crypto.crypto import (cycle_list,
|
2 |
+
encipher_shift, encipher_affine, encipher_substitution,
|
3 |
+
check_and_join, encipher_vigenere, decipher_vigenere, bifid5_square,
|
4 |
+
bifid6_square, encipher_hill, decipher_hill,
|
5 |
+
encipher_bifid5, encipher_bifid6, decipher_bifid5,
|
6 |
+
decipher_bifid6, encipher_kid_rsa, decipher_kid_rsa,
|
7 |
+
kid_rsa_private_key, kid_rsa_public_key, decipher_rsa, rsa_private_key,
|
8 |
+
rsa_public_key, encipher_rsa, lfsr_connection_polynomial,
|
9 |
+
lfsr_autocorrelation, lfsr_sequence, encode_morse, decode_morse,
|
10 |
+
elgamal_private_key, elgamal_public_key, decipher_elgamal,
|
11 |
+
encipher_elgamal, dh_private_key, dh_public_key, dh_shared_key,
|
12 |
+
padded_key, encipher_bifid, decipher_bifid, bifid_square, bifid5,
|
13 |
+
bifid6, bifid10, decipher_gm, encipher_gm, gm_public_key,
|
14 |
+
gm_private_key, bg_private_key, bg_public_key, encipher_bg, decipher_bg,
|
15 |
+
encipher_rot13, decipher_rot13, encipher_atbash, decipher_atbash,
|
16 |
+
encipher_railfence, decipher_railfence)
|
17 |
+
|
18 |
+
__all__ = [
|
19 |
+
'cycle_list', 'encipher_shift', 'encipher_affine',
|
20 |
+
'encipher_substitution', 'check_and_join', 'encipher_vigenere',
|
21 |
+
'decipher_vigenere', 'bifid5_square', 'bifid6_square', 'encipher_hill',
|
22 |
+
'decipher_hill', 'encipher_bifid5', 'encipher_bifid6', 'decipher_bifid5',
|
23 |
+
'decipher_bifid6', 'encipher_kid_rsa', 'decipher_kid_rsa',
|
24 |
+
'kid_rsa_private_key', 'kid_rsa_public_key', 'decipher_rsa',
|
25 |
+
'rsa_private_key', 'rsa_public_key', 'encipher_rsa',
|
26 |
+
'lfsr_connection_polynomial', 'lfsr_autocorrelation', 'lfsr_sequence',
|
27 |
+
'encode_morse', 'decode_morse', 'elgamal_private_key',
|
28 |
+
'elgamal_public_key', 'decipher_elgamal', 'encipher_elgamal',
|
29 |
+
'dh_private_key', 'dh_public_key', 'dh_shared_key', 'padded_key',
|
30 |
+
'encipher_bifid', 'decipher_bifid', 'bifid_square', 'bifid5', 'bifid6',
|
31 |
+
'bifid10', 'decipher_gm', 'encipher_gm', 'gm_public_key',
|
32 |
+
'gm_private_key', 'bg_private_key', 'bg_public_key', 'encipher_bg',
|
33 |
+
'decipher_bg', 'encipher_rot13', 'decipher_rot13', 'encipher_atbash',
|
34 |
+
'decipher_atbash', 'encipher_railfence', 'decipher_railfence',
|
35 |
+
]
|
env-llmeval/lib/python3.10/site-packages/sympy/crypto/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.64 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/crypto/__pycache__/crypto.cpython-310.pyc
ADDED
Binary file (93.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/crypto/crypto.py
ADDED
@@ -0,0 +1,3360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This file contains some classical ciphers and routines
|
3 |
+
implementing a linear-feedback shift register (LFSR)
|
4 |
+
and the Diffie-Hellman key exchange.
|
5 |
+
|
6 |
+
.. warning::
|
7 |
+
|
8 |
+
This module is intended for educational purposes only. Do not use the
|
9 |
+
functions in this module for real cryptographic applications. If you wish
|
10 |
+
to encrypt real data, we recommend using something like the `cryptography
|
11 |
+
<https://cryptography.io/en/latest/>`_ module.
|
12 |
+
|
13 |
+
"""
|
14 |
+
|
15 |
+
from string import whitespace, ascii_uppercase as uppercase, printable
|
16 |
+
from functools import reduce
|
17 |
+
import warnings
|
18 |
+
|
19 |
+
from itertools import cycle
|
20 |
+
|
21 |
+
from sympy.core import Symbol
|
22 |
+
from sympy.core.numbers import igcdex, mod_inverse, igcd, Rational
|
23 |
+
from sympy.core.random import _randrange, _randint
|
24 |
+
from sympy.matrices import Matrix
|
25 |
+
from sympy.ntheory import isprime, primitive_root, factorint
|
26 |
+
from sympy.ntheory import totient as _euler
|
27 |
+
from sympy.ntheory import reduced_totient as _carmichael
|
28 |
+
from sympy.ntheory.generate import nextprime
|
29 |
+
from sympy.ntheory.modular import crt
|
30 |
+
from sympy.polys.domains import FF
|
31 |
+
from sympy.polys.polytools import gcd, Poly
|
32 |
+
from sympy.utilities.misc import as_int, filldedent, translate
|
33 |
+
from sympy.utilities.iterables import uniq, multiset
|
34 |
+
|
35 |
+
|
36 |
+
class NonInvertibleCipherWarning(RuntimeWarning):
|
37 |
+
"""A warning raised if the cipher is not invertible."""
|
38 |
+
def __init__(self, msg):
|
39 |
+
self.fullMessage = msg
|
40 |
+
|
41 |
+
def __str__(self):
|
42 |
+
return '\n\t' + self.fullMessage
|
43 |
+
|
44 |
+
def warn(self, stacklevel=3):
|
45 |
+
warnings.warn(self, stacklevel=stacklevel)
|
46 |
+
|
47 |
+
|
48 |
+
def AZ(s=None):
|
49 |
+
"""Return the letters of ``s`` in uppercase. In case more than
|
50 |
+
one string is passed, each of them will be processed and a list
|
51 |
+
of upper case strings will be returned.
|
52 |
+
|
53 |
+
Examples
|
54 |
+
========
|
55 |
+
|
56 |
+
>>> from sympy.crypto.crypto import AZ
|
57 |
+
>>> AZ('Hello, world!')
|
58 |
+
'HELLOWORLD'
|
59 |
+
>>> AZ('Hello, world!'.split())
|
60 |
+
['HELLO', 'WORLD']
|
61 |
+
|
62 |
+
See Also
|
63 |
+
========
|
64 |
+
|
65 |
+
check_and_join
|
66 |
+
|
67 |
+
"""
|
68 |
+
if not s:
|
69 |
+
return uppercase
|
70 |
+
t = isinstance(s, str)
|
71 |
+
if t:
|
72 |
+
s = [s]
|
73 |
+
rv = [check_and_join(i.upper().split(), uppercase, filter=True)
|
74 |
+
for i in s]
|
75 |
+
if t:
|
76 |
+
return rv[0]
|
77 |
+
return rv
|
78 |
+
|
79 |
+
bifid5 = AZ().replace('J', '')
|
80 |
+
bifid6 = AZ() + '0123456789'
|
81 |
+
bifid10 = printable
|
82 |
+
|
83 |
+
|
84 |
+
def padded_key(key, symbols):
|
85 |
+
"""Return a string of the distinct characters of ``symbols`` with
|
86 |
+
those of ``key`` appearing first. A ValueError is raised if
|
87 |
+
a) there are duplicate characters in ``symbols`` or
|
88 |
+
b) there are characters in ``key`` that are not in ``symbols``.
|
89 |
+
|
90 |
+
Examples
|
91 |
+
========
|
92 |
+
|
93 |
+
>>> from sympy.crypto.crypto import padded_key
|
94 |
+
>>> padded_key('PUPPY', 'OPQRSTUVWXY')
|
95 |
+
'PUYOQRSTVWX'
|
96 |
+
>>> padded_key('RSA', 'ARTIST')
|
97 |
+
Traceback (most recent call last):
|
98 |
+
...
|
99 |
+
ValueError: duplicate characters in symbols: T
|
100 |
+
|
101 |
+
"""
|
102 |
+
syms = list(uniq(symbols))
|
103 |
+
if len(syms) != len(symbols):
|
104 |
+
extra = ''.join(sorted({
|
105 |
+
i for i in symbols if symbols.count(i) > 1}))
|
106 |
+
raise ValueError('duplicate characters in symbols: %s' % extra)
|
107 |
+
extra = set(key) - set(syms)
|
108 |
+
if extra:
|
109 |
+
raise ValueError(
|
110 |
+
'characters in key but not symbols: %s' % ''.join(
|
111 |
+
sorted(extra)))
|
112 |
+
key0 = ''.join(list(uniq(key)))
|
113 |
+
# remove from syms characters in key0
|
114 |
+
return key0 + translate(''.join(syms), None, key0)
|
115 |
+
|
116 |
+
|
117 |
+
def check_and_join(phrase, symbols=None, filter=None):
|
118 |
+
"""
|
119 |
+
Joins characters of ``phrase`` and if ``symbols`` is given, raises
|
120 |
+
an error if any character in ``phrase`` is not in ``symbols``.
|
121 |
+
|
122 |
+
Parameters
|
123 |
+
==========
|
124 |
+
|
125 |
+
phrase
|
126 |
+
String or list of strings to be returned as a string.
|
127 |
+
|
128 |
+
symbols
|
129 |
+
Iterable of characters allowed in ``phrase``.
|
130 |
+
|
131 |
+
If ``symbols`` is ``None``, no checking is performed.
|
132 |
+
|
133 |
+
Examples
|
134 |
+
========
|
135 |
+
|
136 |
+
>>> from sympy.crypto.crypto import check_and_join
|
137 |
+
>>> check_and_join('a phrase')
|
138 |
+
'a phrase'
|
139 |
+
>>> check_and_join('a phrase'.upper().split())
|
140 |
+
'APHRASE'
|
141 |
+
>>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True)
|
142 |
+
'ARAE'
|
143 |
+
>>> check_and_join('a phrase!'.upper().split(), 'ARE')
|
144 |
+
Traceback (most recent call last):
|
145 |
+
...
|
146 |
+
ValueError: characters in phrase but not symbols: "!HPS"
|
147 |
+
|
148 |
+
"""
|
149 |
+
rv = ''.join(''.join(phrase))
|
150 |
+
if symbols is not None:
|
151 |
+
symbols = check_and_join(symbols)
|
152 |
+
missing = ''.join(sorted(set(rv) - set(symbols)))
|
153 |
+
if missing:
|
154 |
+
if not filter:
|
155 |
+
raise ValueError(
|
156 |
+
'characters in phrase but not symbols: "%s"' % missing)
|
157 |
+
rv = translate(rv, None, missing)
|
158 |
+
return rv
|
159 |
+
|
160 |
+
|
161 |
+
def _prep(msg, key, alp, default=None):
|
162 |
+
if not alp:
|
163 |
+
if not default:
|
164 |
+
alp = AZ()
|
165 |
+
msg = AZ(msg)
|
166 |
+
key = AZ(key)
|
167 |
+
else:
|
168 |
+
alp = default
|
169 |
+
else:
|
170 |
+
alp = ''.join(alp)
|
171 |
+
key = check_and_join(key, alp, filter=True)
|
172 |
+
msg = check_and_join(msg, alp, filter=True)
|
173 |
+
return msg, key, alp
|
174 |
+
|
175 |
+
|
176 |
+
def cycle_list(k, n):
|
177 |
+
"""
|
178 |
+
Returns the elements of the list ``range(n)`` shifted to the
|
179 |
+
left by ``k`` (so the list starts with ``k`` (mod ``n``)).
|
180 |
+
|
181 |
+
Examples
|
182 |
+
========
|
183 |
+
|
184 |
+
>>> from sympy.crypto.crypto import cycle_list
|
185 |
+
>>> cycle_list(3, 10)
|
186 |
+
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
|
187 |
+
|
188 |
+
"""
|
189 |
+
k = k % n
|
190 |
+
return list(range(k, n)) + list(range(k))
|
191 |
+
|
192 |
+
|
193 |
+
######## shift cipher examples ############
|
194 |
+
|
195 |
+
|
196 |
+
def encipher_shift(msg, key, symbols=None):
|
197 |
+
"""
|
198 |
+
Performs shift cipher encryption on plaintext msg, and returns the
|
199 |
+
ciphertext.
|
200 |
+
|
201 |
+
Parameters
|
202 |
+
==========
|
203 |
+
|
204 |
+
key : int
|
205 |
+
The secret key.
|
206 |
+
|
207 |
+
msg : str
|
208 |
+
Plaintext of upper-case letters.
|
209 |
+
|
210 |
+
Returns
|
211 |
+
=======
|
212 |
+
|
213 |
+
str
|
214 |
+
Ciphertext of upper-case letters.
|
215 |
+
|
216 |
+
Examples
|
217 |
+
========
|
218 |
+
|
219 |
+
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift
|
220 |
+
>>> msg = "GONAVYBEATARMY"
|
221 |
+
>>> ct = encipher_shift(msg, 1); ct
|
222 |
+
'HPOBWZCFBUBSNZ'
|
223 |
+
|
224 |
+
To decipher the shifted text, change the sign of the key:
|
225 |
+
|
226 |
+
>>> encipher_shift(ct, -1)
|
227 |
+
'GONAVYBEATARMY'
|
228 |
+
|
229 |
+
There is also a convenience function that does this with the
|
230 |
+
original key:
|
231 |
+
|
232 |
+
>>> decipher_shift(ct, 1)
|
233 |
+
'GONAVYBEATARMY'
|
234 |
+
|
235 |
+
Notes
|
236 |
+
=====
|
237 |
+
|
238 |
+
ALGORITHM:
|
239 |
+
|
240 |
+
STEPS:
|
241 |
+
0. Number the letters of the alphabet from 0, ..., N
|
242 |
+
1. Compute from the string ``msg`` a list ``L1`` of
|
243 |
+
corresponding integers.
|
244 |
+
2. Compute from the list ``L1`` a new list ``L2``, given by
|
245 |
+
adding ``(k mod 26)`` to each element in ``L1``.
|
246 |
+
3. Compute from the list ``L2`` a string ``ct`` of
|
247 |
+
corresponding letters.
|
248 |
+
|
249 |
+
The shift cipher is also called the Caesar cipher, after
|
250 |
+
Julius Caesar, who, according to Suetonius, used it with a
|
251 |
+
shift of three to protect messages of military significance.
|
252 |
+
Caesar's nephew Augustus reportedly used a similar cipher, but
|
253 |
+
with a right shift of 1.
|
254 |
+
|
255 |
+
References
|
256 |
+
==========
|
257 |
+
|
258 |
+
.. [1] https://en.wikipedia.org/wiki/Caesar_cipher
|
259 |
+
.. [2] https://mathworld.wolfram.com/CaesarsMethod.html
|
260 |
+
|
261 |
+
See Also
|
262 |
+
========
|
263 |
+
|
264 |
+
decipher_shift
|
265 |
+
|
266 |
+
"""
|
267 |
+
msg, _, A = _prep(msg, '', symbols)
|
268 |
+
shift = len(A) - key % len(A)
|
269 |
+
key = A[shift:] + A[:shift]
|
270 |
+
return translate(msg, key, A)
|
271 |
+
|
272 |
+
|
273 |
+
def decipher_shift(msg, key, symbols=None):
|
274 |
+
"""
|
275 |
+
Return the text by shifting the characters of ``msg`` to the
|
276 |
+
left by the amount given by ``key``.
|
277 |
+
|
278 |
+
Examples
|
279 |
+
========
|
280 |
+
|
281 |
+
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift
|
282 |
+
>>> msg = "GONAVYBEATARMY"
|
283 |
+
>>> ct = encipher_shift(msg, 1); ct
|
284 |
+
'HPOBWZCFBUBSNZ'
|
285 |
+
|
286 |
+
To decipher the shifted text, change the sign of the key:
|
287 |
+
|
288 |
+
>>> encipher_shift(ct, -1)
|
289 |
+
'GONAVYBEATARMY'
|
290 |
+
|
291 |
+
Or use this function with the original key:
|
292 |
+
|
293 |
+
>>> decipher_shift(ct, 1)
|
294 |
+
'GONAVYBEATARMY'
|
295 |
+
|
296 |
+
"""
|
297 |
+
return encipher_shift(msg, -key, symbols)
|
298 |
+
|
299 |
+
def encipher_rot13(msg, symbols=None):
|
300 |
+
"""
|
301 |
+
Performs the ROT13 encryption on a given plaintext ``msg``.
|
302 |
+
|
303 |
+
Explanation
|
304 |
+
===========
|
305 |
+
|
306 |
+
ROT13 is a substitution cipher which substitutes each letter
|
307 |
+
in the plaintext message for the letter furthest away from it
|
308 |
+
in the English alphabet.
|
309 |
+
|
310 |
+
Equivalently, it is just a Caeser (shift) cipher with a shift
|
311 |
+
key of 13 (midway point of the alphabet).
|
312 |
+
|
313 |
+
References
|
314 |
+
==========
|
315 |
+
|
316 |
+
.. [1] https://en.wikipedia.org/wiki/ROT13
|
317 |
+
|
318 |
+
See Also
|
319 |
+
========
|
320 |
+
|
321 |
+
decipher_rot13
|
322 |
+
encipher_shift
|
323 |
+
|
324 |
+
"""
|
325 |
+
return encipher_shift(msg, 13, symbols)
|
326 |
+
|
327 |
+
def decipher_rot13(msg, symbols=None):
|
328 |
+
"""
|
329 |
+
Performs the ROT13 decryption on a given plaintext ``msg``.
|
330 |
+
|
331 |
+
Explanation
|
332 |
+
============
|
333 |
+
|
334 |
+
``decipher_rot13`` is equivalent to ``encipher_rot13`` as both
|
335 |
+
``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a
|
336 |
+
key of 13 will return the same results. Nonetheless,
|
337 |
+
``decipher_rot13`` has nonetheless been explicitly defined here for
|
338 |
+
consistency.
|
339 |
+
|
340 |
+
Examples
|
341 |
+
========
|
342 |
+
|
343 |
+
>>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13
|
344 |
+
>>> msg = 'GONAVYBEATARMY'
|
345 |
+
>>> ciphertext = encipher_rot13(msg);ciphertext
|
346 |
+
'TBANILORNGNEZL'
|
347 |
+
>>> decipher_rot13(ciphertext)
|
348 |
+
'GONAVYBEATARMY'
|
349 |
+
>>> encipher_rot13(msg) == decipher_rot13(msg)
|
350 |
+
True
|
351 |
+
>>> msg == decipher_rot13(ciphertext)
|
352 |
+
True
|
353 |
+
|
354 |
+
"""
|
355 |
+
return decipher_shift(msg, 13, symbols)
|
356 |
+
|
357 |
+
######## affine cipher examples ############
|
358 |
+
|
359 |
+
|
360 |
+
def encipher_affine(msg, key, symbols=None, _inverse=False):
|
361 |
+
r"""
|
362 |
+
Performs the affine cipher encryption on plaintext ``msg``, and
|
363 |
+
returns the ciphertext.
|
364 |
+
|
365 |
+
Explanation
|
366 |
+
===========
|
367 |
+
|
368 |
+
Encryption is based on the map `x \rightarrow ax+b` (mod `N`)
|
369 |
+
where ``N`` is the number of characters in the alphabet.
|
370 |
+
Decryption is based on the map `x \rightarrow cx+d` (mod `N`),
|
371 |
+
where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
|
372 |
+
In particular, for the map to be invertible, we need
|
373 |
+
`\mathrm{gcd}(a, N) = 1` and an error will be raised if this is
|
374 |
+
not true.
|
375 |
+
|
376 |
+
Parameters
|
377 |
+
==========
|
378 |
+
|
379 |
+
msg : str
|
380 |
+
Characters that appear in ``symbols``.
|
381 |
+
|
382 |
+
a, b : int, int
|
383 |
+
A pair integers, with ``gcd(a, N) = 1`` (the secret key).
|
384 |
+
|
385 |
+
symbols
|
386 |
+
String of characters (default = uppercase letters).
|
387 |
+
|
388 |
+
When no symbols are given, ``msg`` is converted to upper case
|
389 |
+
letters and all other characters are ignored.
|
390 |
+
|
391 |
+
Returns
|
392 |
+
=======
|
393 |
+
|
394 |
+
ct
|
395 |
+
String of characters (the ciphertext message)
|
396 |
+
|
397 |
+
Notes
|
398 |
+
=====
|
399 |
+
|
400 |
+
ALGORITHM:
|
401 |
+
|
402 |
+
STEPS:
|
403 |
+
0. Number the letters of the alphabet from 0, ..., N
|
404 |
+
1. Compute from the string ``msg`` a list ``L1`` of
|
405 |
+
corresponding integers.
|
406 |
+
2. Compute from the list ``L1`` a new list ``L2``, given by
|
407 |
+
replacing ``x`` by ``a*x + b (mod N)``, for each element
|
408 |
+
``x`` in ``L1``.
|
409 |
+
3. Compute from the list ``L2`` a string ``ct`` of
|
410 |
+
corresponding letters.
|
411 |
+
|
412 |
+
This is a straightforward generalization of the shift cipher with
|
413 |
+
the added complexity of requiring 2 characters to be deciphered in
|
414 |
+
order to recover the key.
|
415 |
+
|
416 |
+
References
|
417 |
+
==========
|
418 |
+
|
419 |
+
.. [1] https://en.wikipedia.org/wiki/Affine_cipher
|
420 |
+
|
421 |
+
See Also
|
422 |
+
========
|
423 |
+
|
424 |
+
decipher_affine
|
425 |
+
|
426 |
+
"""
|
427 |
+
msg, _, A = _prep(msg, '', symbols)
|
428 |
+
N = len(A)
|
429 |
+
a, b = key
|
430 |
+
assert gcd(a, N) == 1
|
431 |
+
if _inverse:
|
432 |
+
c = mod_inverse(a, N)
|
433 |
+
d = -b*c
|
434 |
+
a, b = c, d
|
435 |
+
B = ''.join([A[(a*i + b) % N] for i in range(N)])
|
436 |
+
return translate(msg, A, B)
|
437 |
+
|
438 |
+
|
439 |
+
def decipher_affine(msg, key, symbols=None):
|
440 |
+
r"""
|
441 |
+
Return the deciphered text that was made from the mapping,
|
442 |
+
`x \rightarrow ax+b` (mod `N`), where ``N`` is the
|
443 |
+
number of characters in the alphabet. Deciphering is done by
|
444 |
+
reciphering with a new key: `x \rightarrow cx+d` (mod `N`),
|
445 |
+
where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
|
446 |
+
|
447 |
+
Examples
|
448 |
+
========
|
449 |
+
|
450 |
+
>>> from sympy.crypto.crypto import encipher_affine, decipher_affine
|
451 |
+
>>> msg = "GO NAVY BEAT ARMY"
|
452 |
+
>>> key = (3, 1)
|
453 |
+
>>> encipher_affine(msg, key)
|
454 |
+
'TROBMVENBGBALV'
|
455 |
+
>>> decipher_affine(_, key)
|
456 |
+
'GONAVYBEATARMY'
|
457 |
+
|
458 |
+
See Also
|
459 |
+
========
|
460 |
+
|
461 |
+
encipher_affine
|
462 |
+
|
463 |
+
"""
|
464 |
+
return encipher_affine(msg, key, symbols, _inverse=True)
|
465 |
+
|
466 |
+
|
467 |
+
def encipher_atbash(msg, symbols=None):
|
468 |
+
r"""
|
469 |
+
Enciphers a given ``msg`` into its Atbash ciphertext and returns it.
|
470 |
+
|
471 |
+
Explanation
|
472 |
+
===========
|
473 |
+
|
474 |
+
Atbash is a substitution cipher originally used to encrypt the Hebrew
|
475 |
+
alphabet. Atbash works on the principle of mapping each alphabet to its
|
476 |
+
reverse / counterpart (i.e. a would map to z, b to y etc.)
|
477 |
+
|
478 |
+
Atbash is functionally equivalent to the affine cipher with ``a = 25``
|
479 |
+
and ``b = 25``
|
480 |
+
|
481 |
+
See Also
|
482 |
+
========
|
483 |
+
|
484 |
+
decipher_atbash
|
485 |
+
|
486 |
+
"""
|
487 |
+
return encipher_affine(msg, (25, 25), symbols)
|
488 |
+
|
489 |
+
|
490 |
+
def decipher_atbash(msg, symbols=None):
|
491 |
+
r"""
|
492 |
+
Deciphers a given ``msg`` using Atbash cipher and returns it.
|
493 |
+
|
494 |
+
Explanation
|
495 |
+
===========
|
496 |
+
|
497 |
+
``decipher_atbash`` is functionally equivalent to ``encipher_atbash``.
|
498 |
+
However, it has still been added as a separate function to maintain
|
499 |
+
consistency.
|
500 |
+
|
501 |
+
Examples
|
502 |
+
========
|
503 |
+
|
504 |
+
>>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash
|
505 |
+
>>> msg = 'GONAVYBEATARMY'
|
506 |
+
>>> encipher_atbash(msg)
|
507 |
+
'TLMZEBYVZGZINB'
|
508 |
+
>>> decipher_atbash(msg)
|
509 |
+
'TLMZEBYVZGZINB'
|
510 |
+
>>> encipher_atbash(msg) == decipher_atbash(msg)
|
511 |
+
True
|
512 |
+
>>> msg == encipher_atbash(encipher_atbash(msg))
|
513 |
+
True
|
514 |
+
|
515 |
+
References
|
516 |
+
==========
|
517 |
+
|
518 |
+
.. [1] https://en.wikipedia.org/wiki/Atbash
|
519 |
+
|
520 |
+
See Also
|
521 |
+
========
|
522 |
+
|
523 |
+
encipher_atbash
|
524 |
+
|
525 |
+
"""
|
526 |
+
return decipher_affine(msg, (25, 25), symbols)
|
527 |
+
|
528 |
+
#################### substitution cipher ###########################
|
529 |
+
|
530 |
+
|
531 |
+
def encipher_substitution(msg, old, new=None):
|
532 |
+
r"""
|
533 |
+
Returns the ciphertext obtained by replacing each character that
|
534 |
+
appears in ``old`` with the corresponding character in ``new``.
|
535 |
+
If ``old`` is a mapping, then new is ignored and the replacements
|
536 |
+
defined by ``old`` are used.
|
537 |
+
|
538 |
+
Explanation
|
539 |
+
===========
|
540 |
+
|
541 |
+
This is a more general than the affine cipher in that the key can
|
542 |
+
only be recovered by determining the mapping for each symbol.
|
543 |
+
Though in practice, once a few symbols are recognized the mappings
|
544 |
+
for other characters can be quickly guessed.
|
545 |
+
|
546 |
+
Examples
|
547 |
+
========
|
548 |
+
|
549 |
+
>>> from sympy.crypto.crypto import encipher_substitution, AZ
|
550 |
+
>>> old = 'OEYAG'
|
551 |
+
>>> new = '034^6'
|
552 |
+
>>> msg = AZ("go navy! beat army!")
|
553 |
+
>>> ct = encipher_substitution(msg, old, new); ct
|
554 |
+
'60N^V4B3^T^RM4'
|
555 |
+
|
556 |
+
To decrypt a substitution, reverse the last two arguments:
|
557 |
+
|
558 |
+
>>> encipher_substitution(ct, new, old)
|
559 |
+
'GONAVYBEATARMY'
|
560 |
+
|
561 |
+
In the special case where ``old`` and ``new`` are a permutation of
|
562 |
+
order 2 (representing a transposition of characters) their order
|
563 |
+
is immaterial:
|
564 |
+
|
565 |
+
>>> old = 'NAVY'
|
566 |
+
>>> new = 'ANYV'
|
567 |
+
>>> encipher = lambda x: encipher_substitution(x, old, new)
|
568 |
+
>>> encipher('NAVY')
|
569 |
+
'ANYV'
|
570 |
+
>>> encipher(_)
|
571 |
+
'NAVY'
|
572 |
+
|
573 |
+
The substitution cipher, in general, is a method
|
574 |
+
whereby "units" (not necessarily single characters) of plaintext
|
575 |
+
are replaced with ciphertext according to a regular system.
|
576 |
+
|
577 |
+
>>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc']))
|
578 |
+
>>> print(encipher_substitution('abc', ords))
|
579 |
+
\97\98\99
|
580 |
+
|
581 |
+
References
|
582 |
+
==========
|
583 |
+
|
584 |
+
.. [1] https://en.wikipedia.org/wiki/Substitution_cipher
|
585 |
+
|
586 |
+
"""
|
587 |
+
return translate(msg, old, new)
|
588 |
+
|
589 |
+
|
590 |
+
######################################################################
|
591 |
+
#################### Vigenere cipher examples ########################
|
592 |
+
######################################################################
|
593 |
+
|
594 |
+
def encipher_vigenere(msg, key, symbols=None):
|
595 |
+
"""
|
596 |
+
Performs the Vigenere cipher encryption on plaintext ``msg``, and
|
597 |
+
returns the ciphertext.
|
598 |
+
|
599 |
+
Examples
|
600 |
+
========
|
601 |
+
|
602 |
+
>>> from sympy.crypto.crypto import encipher_vigenere, AZ
|
603 |
+
>>> key = "encrypt"
|
604 |
+
>>> msg = "meet me on monday"
|
605 |
+
>>> encipher_vigenere(msg, key)
|
606 |
+
'QRGKKTHRZQEBPR'
|
607 |
+
|
608 |
+
Section 1 of the Kryptos sculpture at the CIA headquarters
|
609 |
+
uses this cipher and also changes the order of the
|
610 |
+
alphabet [2]_. Here is the first line of that section of
|
611 |
+
the sculpture:
|
612 |
+
|
613 |
+
>>> from sympy.crypto.crypto import decipher_vigenere, padded_key
|
614 |
+
>>> alp = padded_key('KRYPTOS', AZ())
|
615 |
+
>>> key = 'PALIMPSEST'
|
616 |
+
>>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ'
|
617 |
+
>>> decipher_vigenere(msg, key, alp)
|
618 |
+
'BETWEENSUBTLESHADINGANDTHEABSENC'
|
619 |
+
|
620 |
+
Explanation
|
621 |
+
===========
|
622 |
+
|
623 |
+
The Vigenere cipher is named after Blaise de Vigenere, a sixteenth
|
624 |
+
century diplomat and cryptographer, by a historical accident.
|
625 |
+
Vigenere actually invented a different and more complicated cipher.
|
626 |
+
The so-called *Vigenere cipher* was actually invented
|
627 |
+
by Giovan Batista Belaso in 1553.
|
628 |
+
|
629 |
+
This cipher was used in the 1800's, for example, during the American
|
630 |
+
Civil War. The Confederacy used a brass cipher disk to implement the
|
631 |
+
Vigenere cipher (now on display in the NSA Museum in Fort
|
632 |
+
Meade) [1]_.
|
633 |
+
|
634 |
+
The Vigenere cipher is a generalization of the shift cipher.
|
635 |
+
Whereas the shift cipher shifts each letter by the same amount
|
636 |
+
(that amount being the key of the shift cipher) the Vigenere
|
637 |
+
cipher shifts a letter by an amount determined by the key (which is
|
638 |
+
a word or phrase known only to the sender and receiver).
|
639 |
+
|
640 |
+
For example, if the key was a single letter, such as "C", then the
|
641 |
+
so-called Vigenere cipher is actually a shift cipher with a
|
642 |
+
shift of `2` (since "C" is the 2nd letter of the alphabet, if
|
643 |
+
you start counting at `0`). If the key was a word with two
|
644 |
+
letters, such as "CA", then the so-called Vigenere cipher will
|
645 |
+
shift letters in even positions by `2` and letters in odd positions
|
646 |
+
are left alone (shifted by `0`, since "A" is the 0th letter, if
|
647 |
+
you start counting at `0`).
|
648 |
+
|
649 |
+
|
650 |
+
ALGORITHM:
|
651 |
+
|
652 |
+
INPUT:
|
653 |
+
|
654 |
+
``msg``: string of characters that appear in ``symbols``
|
655 |
+
(the plaintext)
|
656 |
+
|
657 |
+
``key``: a string of characters that appear in ``symbols``
|
658 |
+
(the secret key)
|
659 |
+
|
660 |
+
``symbols``: a string of letters defining the alphabet
|
661 |
+
|
662 |
+
|
663 |
+
OUTPUT:
|
664 |
+
|
665 |
+
``ct``: string of characters (the ciphertext message)
|
666 |
+
|
667 |
+
STEPS:
|
668 |
+
0. Number the letters of the alphabet from 0, ..., N
|
669 |
+
1. Compute from the string ``key`` a list ``L1`` of
|
670 |
+
corresponding integers. Let ``n1 = len(L1)``.
|
671 |
+
2. Compute from the string ``msg`` a list ``L2`` of
|
672 |
+
corresponding integers. Let ``n2 = len(L2)``.
|
673 |
+
3. Break ``L2`` up sequentially into sublists of size
|
674 |
+
``n1``; the last sublist may be smaller than ``n1``
|
675 |
+
4. For each of these sublists ``L`` of ``L2``, compute a
|
676 |
+
new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)``
|
677 |
+
to the ``i``-th element in the sublist, for each ``i``.
|
678 |
+
5. Assemble these lists ``C`` by concatenation into a new
|
679 |
+
list of length ``n2``.
|
680 |
+
6. Compute from the new list a string ``ct`` of
|
681 |
+
corresponding letters.
|
682 |
+
|
683 |
+
Once it is known that the key is, say, `n` characters long,
|
684 |
+
frequency analysis can be applied to every `n`-th letter of
|
685 |
+
the ciphertext to determine the plaintext. This method is
|
686 |
+
called *Kasiski examination* (although it was first discovered
|
687 |
+
by Babbage). If they key is as long as the message and is
|
688 |
+
comprised of randomly selected characters -- a one-time pad -- the
|
689 |
+
message is theoretically unbreakable.
|
690 |
+
|
691 |
+
The cipher Vigenere actually discovered is an "auto-key" cipher
|
692 |
+
described as follows.
|
693 |
+
|
694 |
+
ALGORITHM:
|
695 |
+
|
696 |
+
INPUT:
|
697 |
+
|
698 |
+
``key``: a string of letters (the secret key)
|
699 |
+
|
700 |
+
``msg``: string of letters (the plaintext message)
|
701 |
+
|
702 |
+
OUTPUT:
|
703 |
+
|
704 |
+
``ct``: string of upper-case letters (the ciphertext message)
|
705 |
+
|
706 |
+
STEPS:
|
707 |
+
0. Number the letters of the alphabet from 0, ..., N
|
708 |
+
1. Compute from the string ``msg`` a list ``L2`` of
|
709 |
+
corresponding integers. Let ``n2 = len(L2)``.
|
710 |
+
2. Let ``n1`` be the length of the key. Append to the
|
711 |
+
string ``key`` the first ``n2 - n1`` characters of
|
712 |
+
the plaintext message. Compute from this string (also of
|
713 |
+
length ``n2``) a list ``L1`` of integers corresponding
|
714 |
+
to the letter numbers in the first step.
|
715 |
+
3. Compute a new list ``C`` given by
|
716 |
+
``C[i] = L1[i] + L2[i] (mod N)``.
|
717 |
+
4. Compute from the new list a string ``ct`` of letters
|
718 |
+
corresponding to the new integers.
|
719 |
+
|
720 |
+
To decipher the auto-key ciphertext, the key is used to decipher
|
721 |
+
the first ``n1`` characters and then those characters become the
|
722 |
+
key to decipher the next ``n1`` characters, etc...:
|
723 |
+
|
724 |
+
>>> m = AZ('go navy, beat army! yes you can'); m
|
725 |
+
'GONAVYBEATARMYYESYOUCAN'
|
726 |
+
>>> key = AZ('gold bug'); n1 = len(key); n2 = len(m)
|
727 |
+
>>> auto_key = key + m[:n2 - n1]; auto_key
|
728 |
+
'GOLDBUGGONAVYBEATARMYYE'
|
729 |
+
>>> ct = encipher_vigenere(m, auto_key); ct
|
730 |
+
'MCYDWSHKOGAMKZCELYFGAYR'
|
731 |
+
>>> n1 = len(key)
|
732 |
+
>>> pt = []
|
733 |
+
>>> while ct:
|
734 |
+
... part, ct = ct[:n1], ct[n1:]
|
735 |
+
... pt.append(decipher_vigenere(part, key))
|
736 |
+
... key = pt[-1]
|
737 |
+
...
|
738 |
+
>>> ''.join(pt) == m
|
739 |
+
True
|
740 |
+
|
741 |
+
References
|
742 |
+
==========
|
743 |
+
|
744 |
+
.. [1] https://en.wikipedia.org/wiki/Vigenere_cipher
|
745 |
+
.. [2] https://web.archive.org/web/20071116100808/https://filebox.vt.edu/users/batman/kryptos.html
|
746 |
+
(short URL: https://goo.gl/ijr22d)
|
747 |
+
|
748 |
+
"""
|
749 |
+
msg, key, A = _prep(msg, key, symbols)
|
750 |
+
map = {c: i for i, c in enumerate(A)}
|
751 |
+
key = [map[c] for c in key]
|
752 |
+
N = len(map)
|
753 |
+
k = len(key)
|
754 |
+
rv = []
|
755 |
+
for i, m in enumerate(msg):
|
756 |
+
rv.append(A[(map[m] + key[i % k]) % N])
|
757 |
+
rv = ''.join(rv)
|
758 |
+
return rv
|
759 |
+
|
760 |
+
|
761 |
+
def decipher_vigenere(msg, key, symbols=None):
|
762 |
+
"""
|
763 |
+
Decode using the Vigenere cipher.
|
764 |
+
|
765 |
+
Examples
|
766 |
+
========
|
767 |
+
|
768 |
+
>>> from sympy.crypto.crypto import decipher_vigenere
|
769 |
+
>>> key = "encrypt"
|
770 |
+
>>> ct = "QRGK kt HRZQE BPR"
|
771 |
+
>>> decipher_vigenere(ct, key)
|
772 |
+
'MEETMEONMONDAY'
|
773 |
+
|
774 |
+
"""
|
775 |
+
msg, key, A = _prep(msg, key, symbols)
|
776 |
+
map = {c: i for i, c in enumerate(A)}
|
777 |
+
N = len(A) # normally, 26
|
778 |
+
K = [map[c] for c in key]
|
779 |
+
n = len(K)
|
780 |
+
C = [map[c] for c in msg]
|
781 |
+
rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)])
|
782 |
+
return rv
|
783 |
+
|
784 |
+
|
785 |
+
#################### Hill cipher ########################
|
786 |
+
|
787 |
+
|
788 |
+
def encipher_hill(msg, key, symbols=None, pad="Q"):
|
789 |
+
r"""
|
790 |
+
Return the Hill cipher encryption of ``msg``.
|
791 |
+
|
792 |
+
Explanation
|
793 |
+
===========
|
794 |
+
|
795 |
+
The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_,
|
796 |
+
was the first polygraphic cipher in which it was practical
|
797 |
+
(though barely) to operate on more than three symbols at once.
|
798 |
+
The following discussion assumes an elementary knowledge of
|
799 |
+
matrices.
|
800 |
+
|
801 |
+
First, each letter is first encoded as a number starting with 0.
|
802 |
+
Suppose your message `msg` consists of `n` capital letters, with no
|
803 |
+
spaces. This may be regarded an `n`-tuple M of elements of
|
804 |
+
`Z_{26}` (if the letters are those of the English alphabet). A key
|
805 |
+
in the Hill cipher is a `k x k` matrix `K`, all of whose entries
|
806 |
+
are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the
|
807 |
+
linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k`
|
808 |
+
is one-to-one).
|
809 |
+
|
810 |
+
|
811 |
+
Parameters
|
812 |
+
==========
|
813 |
+
|
814 |
+
msg
|
815 |
+
Plaintext message of `n` upper-case letters.
|
816 |
+
|
817 |
+
key
|
818 |
+
A `k \times k` invertible matrix `K`, all of whose entries are
|
819 |
+
in `Z_{26}` (or whatever number of symbols are being used).
|
820 |
+
|
821 |
+
pad
|
822 |
+
Character (default "Q") to use to make length of text be a
|
823 |
+
multiple of ``k``.
|
824 |
+
|
825 |
+
Returns
|
826 |
+
=======
|
827 |
+
|
828 |
+
ct
|
829 |
+
Ciphertext of upper-case letters.
|
830 |
+
|
831 |
+
Notes
|
832 |
+
=====
|
833 |
+
|
834 |
+
ALGORITHM:
|
835 |
+
|
836 |
+
STEPS:
|
837 |
+
0. Number the letters of the alphabet from 0, ..., N
|
838 |
+
1. Compute from the string ``msg`` a list ``L`` of
|
839 |
+
corresponding integers. Let ``n = len(L)``.
|
840 |
+
2. Break the list ``L`` up into ``t = ceiling(n/k)``
|
841 |
+
sublists ``L_1``, ..., ``L_t`` of size ``k`` (with
|
842 |
+
the last list "padded" to ensure its size is
|
843 |
+
``k``).
|
844 |
+
3. Compute new list ``C_1``, ..., ``C_t`` given by
|
845 |
+
``C[i] = K*L_i`` (arithmetic is done mod N), for each
|
846 |
+
``i``.
|
847 |
+
4. Concatenate these into a list ``C = C_1 + ... + C_t``.
|
848 |
+
5. Compute from ``C`` a string ``ct`` of corresponding
|
849 |
+
letters. This has length ``k*t``.
|
850 |
+
|
851 |
+
References
|
852 |
+
==========
|
853 |
+
|
854 |
+
.. [1] https://en.wikipedia.org/wiki/Hill_cipher
|
855 |
+
.. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet,
|
856 |
+
The American Mathematical Monthly Vol.36, June-July 1929,
|
857 |
+
pp.306-312.
|
858 |
+
|
859 |
+
See Also
|
860 |
+
========
|
861 |
+
|
862 |
+
decipher_hill
|
863 |
+
|
864 |
+
"""
|
865 |
+
assert key.is_square
|
866 |
+
assert len(pad) == 1
|
867 |
+
msg, pad, A = _prep(msg, pad, symbols)
|
868 |
+
map = {c: i for i, c in enumerate(A)}
|
869 |
+
P = [map[c] for c in msg]
|
870 |
+
N = len(A)
|
871 |
+
k = key.cols
|
872 |
+
n = len(P)
|
873 |
+
m, r = divmod(n, k)
|
874 |
+
if r:
|
875 |
+
P = P + [map[pad]]*(k - r)
|
876 |
+
m += 1
|
877 |
+
rv = ''.join([A[c % N] for j in range(m) for c in
|
878 |
+
list(key*Matrix(k, 1, [P[i]
|
879 |
+
for i in range(k*j, k*(j + 1))]))])
|
880 |
+
return rv
|
881 |
+
|
882 |
+
|
883 |
+
def decipher_hill(msg, key, symbols=None):
|
884 |
+
"""
|
885 |
+
Deciphering is the same as enciphering but using the inverse of the
|
886 |
+
key matrix.
|
887 |
+
|
888 |
+
Examples
|
889 |
+
========
|
890 |
+
|
891 |
+
>>> from sympy.crypto.crypto import encipher_hill, decipher_hill
|
892 |
+
>>> from sympy import Matrix
|
893 |
+
|
894 |
+
>>> key = Matrix([[1, 2], [3, 5]])
|
895 |
+
>>> encipher_hill("meet me on monday", key)
|
896 |
+
'UEQDUEODOCTCWQ'
|
897 |
+
>>> decipher_hill(_, key)
|
898 |
+
'MEETMEONMONDAY'
|
899 |
+
|
900 |
+
When the length of the plaintext (stripped of invalid characters)
|
901 |
+
is not a multiple of the key dimension, extra characters will
|
902 |
+
appear at the end of the enciphered and deciphered text. In order to
|
903 |
+
decipher the text, those characters must be included in the text to
|
904 |
+
be deciphered. In the following, the key has a dimension of 4 but
|
905 |
+
the text is 2 short of being a multiple of 4 so two characters will
|
906 |
+
be added.
|
907 |
+
|
908 |
+
>>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0],
|
909 |
+
... [2, 2, 3, 4], [1, 1, 0, 1]])
|
910 |
+
>>> msg = "ST"
|
911 |
+
>>> encipher_hill(msg, key)
|
912 |
+
'HJEB'
|
913 |
+
>>> decipher_hill(_, key)
|
914 |
+
'STQQ'
|
915 |
+
>>> encipher_hill(msg, key, pad="Z")
|
916 |
+
'ISPK'
|
917 |
+
>>> decipher_hill(_, key)
|
918 |
+
'STZZ'
|
919 |
+
|
920 |
+
If the last two characters of the ciphertext were ignored in
|
921 |
+
either case, the wrong plaintext would be recovered:
|
922 |
+
|
923 |
+
>>> decipher_hill("HD", key)
|
924 |
+
'ORMV'
|
925 |
+
>>> decipher_hill("IS", key)
|
926 |
+
'UIKY'
|
927 |
+
|
928 |
+
See Also
|
929 |
+
========
|
930 |
+
|
931 |
+
encipher_hill
|
932 |
+
|
933 |
+
"""
|
934 |
+
assert key.is_square
|
935 |
+
msg, _, A = _prep(msg, '', symbols)
|
936 |
+
map = {c: i for i, c in enumerate(A)}
|
937 |
+
C = [map[c] for c in msg]
|
938 |
+
N = len(A)
|
939 |
+
k = key.cols
|
940 |
+
n = len(C)
|
941 |
+
m, r = divmod(n, k)
|
942 |
+
if r:
|
943 |
+
C = C + [0]*(k - r)
|
944 |
+
m += 1
|
945 |
+
key_inv = key.inv_mod(N)
|
946 |
+
rv = ''.join([A[p % N] for j in range(m) for p in
|
947 |
+
list(key_inv*Matrix(
|
948 |
+
k, 1, [C[i] for i in range(k*j, k*(j + 1))]))])
|
949 |
+
return rv
|
950 |
+
|
951 |
+
|
952 |
+
#################### Bifid cipher ########################
|
953 |
+
|
954 |
+
|
955 |
+
def encipher_bifid(msg, key, symbols=None):
|
956 |
+
r"""
|
957 |
+
Performs the Bifid cipher encryption on plaintext ``msg``, and
|
958 |
+
returns the ciphertext.
|
959 |
+
|
960 |
+
This is the version of the Bifid cipher that uses an `n \times n`
|
961 |
+
Polybius square.
|
962 |
+
|
963 |
+
Parameters
|
964 |
+
==========
|
965 |
+
|
966 |
+
msg
|
967 |
+
Plaintext string.
|
968 |
+
|
969 |
+
key
|
970 |
+
Short string for key.
|
971 |
+
|
972 |
+
Duplicate characters are ignored and then it is padded with the
|
973 |
+
characters in ``symbols`` that were not in the short key.
|
974 |
+
|
975 |
+
symbols
|
976 |
+
`n \times n` characters defining the alphabet.
|
977 |
+
|
978 |
+
(default is string.printable)
|
979 |
+
|
980 |
+
Returns
|
981 |
+
=======
|
982 |
+
|
983 |
+
ciphertext
|
984 |
+
Ciphertext using Bifid5 cipher without spaces.
|
985 |
+
|
986 |
+
See Also
|
987 |
+
========
|
988 |
+
|
989 |
+
decipher_bifid, encipher_bifid5, encipher_bifid6
|
990 |
+
|
991 |
+
References
|
992 |
+
==========
|
993 |
+
|
994 |
+
.. [1] https://en.wikipedia.org/wiki/Bifid_cipher
|
995 |
+
|
996 |
+
"""
|
997 |
+
msg, key, A = _prep(msg, key, symbols, bifid10)
|
998 |
+
long_key = ''.join(uniq(key)) or A
|
999 |
+
|
1000 |
+
n = len(A)**.5
|
1001 |
+
if n != int(n):
|
1002 |
+
raise ValueError(
|
1003 |
+
'Length of alphabet (%s) is not a square number.' % len(A))
|
1004 |
+
N = int(n)
|
1005 |
+
if len(long_key) < N**2:
|
1006 |
+
long_key = list(long_key) + [x for x in A if x not in long_key]
|
1007 |
+
|
1008 |
+
# the fractionalization
|
1009 |
+
row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)}
|
1010 |
+
r, c = zip(*[row_col[x] for x in msg])
|
1011 |
+
rc = r + c
|
1012 |
+
ch = {i: ch for ch, i in row_col.items()}
|
1013 |
+
rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2]))
|
1014 |
+
return rv
|
1015 |
+
|
1016 |
+
|
1017 |
+
def decipher_bifid(msg, key, symbols=None):
|
1018 |
+
r"""
|
1019 |
+
Performs the Bifid cipher decryption on ciphertext ``msg``, and
|
1020 |
+
returns the plaintext.
|
1021 |
+
|
1022 |
+
This is the version of the Bifid cipher that uses the `n \times n`
|
1023 |
+
Polybius square.
|
1024 |
+
|
1025 |
+
Parameters
|
1026 |
+
==========
|
1027 |
+
|
1028 |
+
msg
|
1029 |
+
Ciphertext string.
|
1030 |
+
|
1031 |
+
key
|
1032 |
+
Short string for key.
|
1033 |
+
|
1034 |
+
Duplicate characters are ignored and then it is padded with the
|
1035 |
+
characters in symbols that were not in the short key.
|
1036 |
+
|
1037 |
+
symbols
|
1038 |
+
`n \times n` characters defining the alphabet.
|
1039 |
+
|
1040 |
+
(default=string.printable, a `10 \times 10` matrix)
|
1041 |
+
|
1042 |
+
Returns
|
1043 |
+
=======
|
1044 |
+
|
1045 |
+
deciphered
|
1046 |
+
Deciphered text.
|
1047 |
+
|
1048 |
+
Examples
|
1049 |
+
========
|
1050 |
+
|
1051 |
+
>>> from sympy.crypto.crypto import (
|
1052 |
+
... encipher_bifid, decipher_bifid, AZ)
|
1053 |
+
|
1054 |
+
Do an encryption using the bifid5 alphabet:
|
1055 |
+
|
1056 |
+
>>> alp = AZ().replace('J', '')
|
1057 |
+
>>> ct = AZ("meet me on monday!")
|
1058 |
+
>>> key = AZ("gold bug")
|
1059 |
+
>>> encipher_bifid(ct, key, alp)
|
1060 |
+
'IEILHHFSTSFQYE'
|
1061 |
+
|
1062 |
+
When entering the text or ciphertext, spaces are ignored so it
|
1063 |
+
can be formatted as desired. Re-entering the ciphertext from the
|
1064 |
+
preceding, putting 4 characters per line and padding with an extra
|
1065 |
+
J, does not cause problems for the deciphering:
|
1066 |
+
|
1067 |
+
>>> decipher_bifid('''
|
1068 |
+
... IEILH
|
1069 |
+
... HFSTS
|
1070 |
+
... FQYEJ''', key, alp)
|
1071 |
+
'MEETMEONMONDAY'
|
1072 |
+
|
1073 |
+
When no alphabet is given, all 100 printable characters will be
|
1074 |
+
used:
|
1075 |
+
|
1076 |
+
>>> key = ''
|
1077 |
+
>>> encipher_bifid('hello world!', key)
|
1078 |
+
'bmtwmg-bIo*w'
|
1079 |
+
>>> decipher_bifid(_, key)
|
1080 |
+
'hello world!'
|
1081 |
+
|
1082 |
+
If the key is changed, a different encryption is obtained:
|
1083 |
+
|
1084 |
+
>>> key = 'gold bug'
|
1085 |
+
>>> encipher_bifid('hello world!', 'gold_bug')
|
1086 |
+
'hg2sfuei7t}w'
|
1087 |
+
|
1088 |
+
And if the key used to decrypt the message is not exact, the
|
1089 |
+
original text will not be perfectly obtained:
|
1090 |
+
|
1091 |
+
>>> decipher_bifid(_, 'gold pug')
|
1092 |
+
'heldo~wor6d!'
|
1093 |
+
|
1094 |
+
"""
|
1095 |
+
msg, _, A = _prep(msg, '', symbols, bifid10)
|
1096 |
+
long_key = ''.join(uniq(key)) or A
|
1097 |
+
|
1098 |
+
n = len(A)**.5
|
1099 |
+
if n != int(n):
|
1100 |
+
raise ValueError(
|
1101 |
+
'Length of alphabet (%s) is not a square number.' % len(A))
|
1102 |
+
N = int(n)
|
1103 |
+
if len(long_key) < N**2:
|
1104 |
+
long_key = list(long_key) + [x for x in A if x not in long_key]
|
1105 |
+
|
1106 |
+
# the reverse fractionalization
|
1107 |
+
row_col = {
|
1108 |
+
ch: divmod(i, N) for i, ch in enumerate(long_key)}
|
1109 |
+
rc = [i for c in msg for i in row_col[c]]
|
1110 |
+
n = len(msg)
|
1111 |
+
rc = zip(*(rc[:n], rc[n:]))
|
1112 |
+
ch = {i: ch for ch, i in row_col.items()}
|
1113 |
+
rv = ''.join(ch[i] for i in rc)
|
1114 |
+
return rv
|
1115 |
+
|
1116 |
+
|
1117 |
+
def bifid_square(key):
|
1118 |
+
"""Return characters of ``key`` arranged in a square.
|
1119 |
+
|
1120 |
+
Examples
|
1121 |
+
========
|
1122 |
+
|
1123 |
+
>>> from sympy.crypto.crypto import (
|
1124 |
+
... bifid_square, AZ, padded_key, bifid5)
|
1125 |
+
>>> bifid_square(AZ().replace('J', ''))
|
1126 |
+
Matrix([
|
1127 |
+
[A, B, C, D, E],
|
1128 |
+
[F, G, H, I, K],
|
1129 |
+
[L, M, N, O, P],
|
1130 |
+
[Q, R, S, T, U],
|
1131 |
+
[V, W, X, Y, Z]])
|
1132 |
+
|
1133 |
+
>>> bifid_square(padded_key(AZ('gold bug!'), bifid5))
|
1134 |
+
Matrix([
|
1135 |
+
[G, O, L, D, B],
|
1136 |
+
[U, A, C, E, F],
|
1137 |
+
[H, I, K, M, N],
|
1138 |
+
[P, Q, R, S, T],
|
1139 |
+
[V, W, X, Y, Z]])
|
1140 |
+
|
1141 |
+
See Also
|
1142 |
+
========
|
1143 |
+
|
1144 |
+
padded_key
|
1145 |
+
|
1146 |
+
"""
|
1147 |
+
A = ''.join(uniq(''.join(key)))
|
1148 |
+
n = len(A)**.5
|
1149 |
+
if n != int(n):
|
1150 |
+
raise ValueError(
|
1151 |
+
'Length of alphabet (%s) is not a square number.' % len(A))
|
1152 |
+
n = int(n)
|
1153 |
+
f = lambda i, j: Symbol(A[n*i + j])
|
1154 |
+
rv = Matrix(n, n, f)
|
1155 |
+
return rv
|
1156 |
+
|
1157 |
+
|
1158 |
+
def encipher_bifid5(msg, key):
|
1159 |
+
r"""
|
1160 |
+
Performs the Bifid cipher encryption on plaintext ``msg``, and
|
1161 |
+
returns the ciphertext.
|
1162 |
+
|
1163 |
+
Explanation
|
1164 |
+
===========
|
1165 |
+
|
1166 |
+
This is the version of the Bifid cipher that uses the `5 \times 5`
|
1167 |
+
Polybius square. The letter "J" is ignored so it must be replaced
|
1168 |
+
with something else (traditionally an "I") before encryption.
|
1169 |
+
|
1170 |
+
ALGORITHM: (5x5 case)
|
1171 |
+
|
1172 |
+
STEPS:
|
1173 |
+
0. Create the `5 \times 5` Polybius square ``S`` associated
|
1174 |
+
to ``key`` as follows:
|
1175 |
+
|
1176 |
+
a) moving from left-to-right, top-to-bottom,
|
1177 |
+
place the letters of the key into a `5 \times 5`
|
1178 |
+
matrix,
|
1179 |
+
b) if the key has less than 25 letters, add the
|
1180 |
+
letters of the alphabet not in the key until the
|
1181 |
+
`5 \times 5` square is filled.
|
1182 |
+
|
1183 |
+
1. Create a list ``P`` of pairs of numbers which are the
|
1184 |
+
coordinates in the Polybius square of the letters in
|
1185 |
+
``msg``.
|
1186 |
+
2. Let ``L1`` be the list of all first coordinates of ``P``
|
1187 |
+
(length of ``L1 = n``), let ``L2`` be the list of all
|
1188 |
+
second coordinates of ``P`` (so the length of ``L2``
|
1189 |
+
is also ``n``).
|
1190 |
+
3. Let ``L`` be the concatenation of ``L1`` and ``L2``
|
1191 |
+
(length ``L = 2*n``), except that consecutive numbers
|
1192 |
+
are paired ``(L[2*i], L[2*i + 1])``. You can regard
|
1193 |
+
``L`` as a list of pairs of length ``n``.
|
1194 |
+
4. Let ``C`` be the list of all letters which are of the
|
1195 |
+
form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a
|
1196 |
+
string, this is the ciphertext of ``msg``.
|
1197 |
+
|
1198 |
+
Parameters
|
1199 |
+
==========
|
1200 |
+
|
1201 |
+
msg : str
|
1202 |
+
Plaintext string.
|
1203 |
+
|
1204 |
+
Converted to upper case and filtered of anything but all letters
|
1205 |
+
except J.
|
1206 |
+
|
1207 |
+
key
|
1208 |
+
Short string for key; non-alphabetic letters, J and duplicated
|
1209 |
+
characters are ignored and then, if the length is less than 25
|
1210 |
+
characters, it is padded with other letters of the alphabet
|
1211 |
+
(in alphabetical order).
|
1212 |
+
|
1213 |
+
Returns
|
1214 |
+
=======
|
1215 |
+
|
1216 |
+
ct
|
1217 |
+
Ciphertext (all caps, no spaces).
|
1218 |
+
|
1219 |
+
Examples
|
1220 |
+
========
|
1221 |
+
|
1222 |
+
>>> from sympy.crypto.crypto import (
|
1223 |
+
... encipher_bifid5, decipher_bifid5)
|
1224 |
+
|
1225 |
+
"J" will be omitted unless it is replaced with something else:
|
1226 |
+
|
1227 |
+
>>> round_trip = lambda m, k: \
|
1228 |
+
... decipher_bifid5(encipher_bifid5(m, k), k)
|
1229 |
+
>>> key = 'a'
|
1230 |
+
>>> msg = "JOSIE"
|
1231 |
+
>>> round_trip(msg, key)
|
1232 |
+
'OSIE'
|
1233 |
+
>>> round_trip(msg.replace("J", "I"), key)
|
1234 |
+
'IOSIE'
|
1235 |
+
>>> j = "QIQ"
|
1236 |
+
>>> round_trip(msg.replace("J", j), key).replace(j, "J")
|
1237 |
+
'JOSIE'
|
1238 |
+
|
1239 |
+
|
1240 |
+
Notes
|
1241 |
+
=====
|
1242 |
+
|
1243 |
+
The Bifid cipher was invented around 1901 by Felix Delastelle.
|
1244 |
+
It is a *fractional substitution* cipher, where letters are
|
1245 |
+
replaced by pairs of symbols from a smaller alphabet. The
|
1246 |
+
cipher uses a `5 \times 5` square filled with some ordering of the
|
1247 |
+
alphabet, except that "J" is replaced with "I" (this is a so-called
|
1248 |
+
Polybius square; there is a `6 \times 6` analog if you add back in
|
1249 |
+
"J" and also append onto the usual 26 letter alphabet, the digits
|
1250 |
+
0, 1, ..., 9).
|
1251 |
+
According to Helen Gaines' book *Cryptanalysis*, this type of cipher
|
1252 |
+
was used in the field by the German Army during World War I.
|
1253 |
+
|
1254 |
+
See Also
|
1255 |
+
========
|
1256 |
+
|
1257 |
+
decipher_bifid5, encipher_bifid
|
1258 |
+
|
1259 |
+
"""
|
1260 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
|
1261 |
+
key = padded_key(key, bifid5)
|
1262 |
+
return encipher_bifid(msg, '', key)
|
1263 |
+
|
1264 |
+
|
1265 |
+
def decipher_bifid5(msg, key):
|
1266 |
+
r"""
|
1267 |
+
Return the Bifid cipher decryption of ``msg``.
|
1268 |
+
|
1269 |
+
Explanation
|
1270 |
+
===========
|
1271 |
+
|
1272 |
+
This is the version of the Bifid cipher that uses the `5 \times 5`
|
1273 |
+
Polybius square; the letter "J" is ignored unless a ``key`` of
|
1274 |
+
length 25 is used.
|
1275 |
+
|
1276 |
+
Parameters
|
1277 |
+
==========
|
1278 |
+
|
1279 |
+
msg
|
1280 |
+
Ciphertext string.
|
1281 |
+
|
1282 |
+
key
|
1283 |
+
Short string for key; duplicated characters are ignored and if
|
1284 |
+
the length is less then 25 characters, it will be padded with
|
1285 |
+
other letters from the alphabet omitting "J".
|
1286 |
+
Non-alphabetic characters are ignored.
|
1287 |
+
|
1288 |
+
Returns
|
1289 |
+
=======
|
1290 |
+
|
1291 |
+
plaintext
|
1292 |
+
Plaintext from Bifid5 cipher (all caps, no spaces).
|
1293 |
+
|
1294 |
+
Examples
|
1295 |
+
========
|
1296 |
+
|
1297 |
+
>>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5
|
1298 |
+
>>> key = "gold bug"
|
1299 |
+
>>> encipher_bifid5('meet me on friday', key)
|
1300 |
+
'IEILEHFSTSFXEE'
|
1301 |
+
>>> encipher_bifid5('meet me on monday', key)
|
1302 |
+
'IEILHHFSTSFQYE'
|
1303 |
+
>>> decipher_bifid5(_, key)
|
1304 |
+
'MEETMEONMONDAY'
|
1305 |
+
|
1306 |
+
"""
|
1307 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
|
1308 |
+
key = padded_key(key, bifid5)
|
1309 |
+
return decipher_bifid(msg, '', key)
|
1310 |
+
|
1311 |
+
|
1312 |
+
def bifid5_square(key=None):
|
1313 |
+
r"""
|
1314 |
+
5x5 Polybius square.
|
1315 |
+
|
1316 |
+
Produce the Polybius square for the `5 \times 5` Bifid cipher.
|
1317 |
+
|
1318 |
+
Examples
|
1319 |
+
========
|
1320 |
+
|
1321 |
+
>>> from sympy.crypto.crypto import bifid5_square
|
1322 |
+
>>> bifid5_square("gold bug")
|
1323 |
+
Matrix([
|
1324 |
+
[G, O, L, D, B],
|
1325 |
+
[U, A, C, E, F],
|
1326 |
+
[H, I, K, M, N],
|
1327 |
+
[P, Q, R, S, T],
|
1328 |
+
[V, W, X, Y, Z]])
|
1329 |
+
|
1330 |
+
"""
|
1331 |
+
if not key:
|
1332 |
+
key = bifid5
|
1333 |
+
else:
|
1334 |
+
_, key, _ = _prep('', key.upper(), None, bifid5)
|
1335 |
+
key = padded_key(key, bifid5)
|
1336 |
+
return bifid_square(key)
|
1337 |
+
|
1338 |
+
|
1339 |
+
def encipher_bifid6(msg, key):
|
1340 |
+
r"""
|
1341 |
+
Performs the Bifid cipher encryption on plaintext ``msg``, and
|
1342 |
+
returns the ciphertext.
|
1343 |
+
|
1344 |
+
This is the version of the Bifid cipher that uses the `6 \times 6`
|
1345 |
+
Polybius square.
|
1346 |
+
|
1347 |
+
Parameters
|
1348 |
+
==========
|
1349 |
+
|
1350 |
+
msg
|
1351 |
+
Plaintext string (digits okay).
|
1352 |
+
|
1353 |
+
key
|
1354 |
+
Short string for key (digits okay).
|
1355 |
+
|
1356 |
+
If ``key`` is less than 36 characters long, the square will be
|
1357 |
+
filled with letters A through Z and digits 0 through 9.
|
1358 |
+
|
1359 |
+
Returns
|
1360 |
+
=======
|
1361 |
+
|
1362 |
+
ciphertext
|
1363 |
+
Ciphertext from Bifid cipher (all caps, no spaces).
|
1364 |
+
|
1365 |
+
See Also
|
1366 |
+
========
|
1367 |
+
|
1368 |
+
decipher_bifid6, encipher_bifid
|
1369 |
+
|
1370 |
+
"""
|
1371 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
|
1372 |
+
key = padded_key(key, bifid6)
|
1373 |
+
return encipher_bifid(msg, '', key)
|
1374 |
+
|
1375 |
+
|
1376 |
+
def decipher_bifid6(msg, key):
|
1377 |
+
r"""
|
1378 |
+
Performs the Bifid cipher decryption on ciphertext ``msg``, and
|
1379 |
+
returns the plaintext.
|
1380 |
+
|
1381 |
+
This is the version of the Bifid cipher that uses the `6 \times 6`
|
1382 |
+
Polybius square.
|
1383 |
+
|
1384 |
+
Parameters
|
1385 |
+
==========
|
1386 |
+
|
1387 |
+
msg
|
1388 |
+
Ciphertext string (digits okay); converted to upper case
|
1389 |
+
|
1390 |
+
key
|
1391 |
+
Short string for key (digits okay).
|
1392 |
+
|
1393 |
+
If ``key`` is less than 36 characters long, the square will be
|
1394 |
+
filled with letters A through Z and digits 0 through 9.
|
1395 |
+
All letters are converted to uppercase.
|
1396 |
+
|
1397 |
+
Returns
|
1398 |
+
=======
|
1399 |
+
|
1400 |
+
plaintext
|
1401 |
+
Plaintext from Bifid cipher (all caps, no spaces).
|
1402 |
+
|
1403 |
+
Examples
|
1404 |
+
========
|
1405 |
+
|
1406 |
+
>>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
|
1407 |
+
>>> key = "gold bug"
|
1408 |
+
>>> encipher_bifid6('meet me on monday at 8am', key)
|
1409 |
+
'KFKLJJHF5MMMKTFRGPL'
|
1410 |
+
>>> decipher_bifid6(_, key)
|
1411 |
+
'MEETMEONMONDAYAT8AM'
|
1412 |
+
|
1413 |
+
"""
|
1414 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
|
1415 |
+
key = padded_key(key, bifid6)
|
1416 |
+
return decipher_bifid(msg, '', key)
|
1417 |
+
|
1418 |
+
|
1419 |
+
def bifid6_square(key=None):
|
1420 |
+
r"""
|
1421 |
+
6x6 Polybius square.
|
1422 |
+
|
1423 |
+
Produces the Polybius square for the `6 \times 6` Bifid cipher.
|
1424 |
+
Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9".
|
1425 |
+
|
1426 |
+
Examples
|
1427 |
+
========
|
1428 |
+
|
1429 |
+
>>> from sympy.crypto.crypto import bifid6_square
|
1430 |
+
>>> key = "gold bug"
|
1431 |
+
>>> bifid6_square(key)
|
1432 |
+
Matrix([
|
1433 |
+
[G, O, L, D, B, U],
|
1434 |
+
[A, C, E, F, H, I],
|
1435 |
+
[J, K, M, N, P, Q],
|
1436 |
+
[R, S, T, V, W, X],
|
1437 |
+
[Y, Z, 0, 1, 2, 3],
|
1438 |
+
[4, 5, 6, 7, 8, 9]])
|
1439 |
+
|
1440 |
+
"""
|
1441 |
+
if not key:
|
1442 |
+
key = bifid6
|
1443 |
+
else:
|
1444 |
+
_, key, _ = _prep('', key.upper(), None, bifid6)
|
1445 |
+
key = padded_key(key, bifid6)
|
1446 |
+
return bifid_square(key)
|
1447 |
+
|
1448 |
+
|
1449 |
+
#################### RSA #############################
|
1450 |
+
|
1451 |
+
def _decipher_rsa_crt(i, d, factors):
|
1452 |
+
"""Decipher RSA using chinese remainder theorem from the information
|
1453 |
+
of the relatively-prime factors of the modulus.
|
1454 |
+
|
1455 |
+
Parameters
|
1456 |
+
==========
|
1457 |
+
|
1458 |
+
i : integer
|
1459 |
+
Ciphertext
|
1460 |
+
|
1461 |
+
d : integer
|
1462 |
+
The exponent component.
|
1463 |
+
|
1464 |
+
factors : list of relatively-prime integers
|
1465 |
+
The integers given must be coprime and the product must equal
|
1466 |
+
the modulus component of the original RSA key.
|
1467 |
+
|
1468 |
+
Examples
|
1469 |
+
========
|
1470 |
+
|
1471 |
+
How to decrypt RSA with CRT:
|
1472 |
+
|
1473 |
+
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
|
1474 |
+
>>> primes = [61, 53]
|
1475 |
+
>>> e = 17
|
1476 |
+
>>> args = primes + [e]
|
1477 |
+
>>> puk = rsa_public_key(*args)
|
1478 |
+
>>> prk = rsa_private_key(*args)
|
1479 |
+
|
1480 |
+
>>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt
|
1481 |
+
>>> msg = 65
|
1482 |
+
>>> crt_primes = primes
|
1483 |
+
>>> encrypted = encipher_rsa(msg, puk)
|
1484 |
+
>>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes)
|
1485 |
+
>>> decrypted
|
1486 |
+
65
|
1487 |
+
"""
|
1488 |
+
moduluses = [pow(i, d, p) for p in factors]
|
1489 |
+
|
1490 |
+
result = crt(factors, moduluses)
|
1491 |
+
if not result:
|
1492 |
+
raise ValueError("CRT failed")
|
1493 |
+
return result[0]
|
1494 |
+
|
1495 |
+
|
1496 |
+
def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None):
|
1497 |
+
r"""A private subroutine to generate RSA key
|
1498 |
+
|
1499 |
+
Parameters
|
1500 |
+
==========
|
1501 |
+
|
1502 |
+
public, private : bool, optional
|
1503 |
+
Flag to generate either a public key, a private key.
|
1504 |
+
|
1505 |
+
totient : 'Euler' or 'Carmichael'
|
1506 |
+
Different notation used for totient.
|
1507 |
+
|
1508 |
+
multipower : bool, optional
|
1509 |
+
Flag to bypass warning for multipower RSA.
|
1510 |
+
"""
|
1511 |
+
|
1512 |
+
if len(args) < 2:
|
1513 |
+
return False
|
1514 |
+
|
1515 |
+
if totient not in ('Euler', 'Carmichael'):
|
1516 |
+
raise ValueError(
|
1517 |
+
"The argument totient={} should either be " \
|
1518 |
+
"'Euler', 'Carmichalel'." \
|
1519 |
+
.format(totient))
|
1520 |
+
|
1521 |
+
if totient == 'Euler':
|
1522 |
+
_totient = _euler
|
1523 |
+
else:
|
1524 |
+
_totient = _carmichael
|
1525 |
+
|
1526 |
+
if index is not None:
|
1527 |
+
index = as_int(index)
|
1528 |
+
if totient != 'Carmichael':
|
1529 |
+
raise ValueError(
|
1530 |
+
"Setting the 'index' keyword argument requires totient"
|
1531 |
+
"notation to be specified as 'Carmichael'.")
|
1532 |
+
|
1533 |
+
primes, e = args[:-1], args[-1]
|
1534 |
+
|
1535 |
+
if not all(isprime(p) for p in primes):
|
1536 |
+
new_primes = []
|
1537 |
+
for i in primes:
|
1538 |
+
new_primes.extend(factorint(i, multiple=True))
|
1539 |
+
primes = new_primes
|
1540 |
+
|
1541 |
+
n = reduce(lambda i, j: i*j, primes)
|
1542 |
+
|
1543 |
+
tally = multiset(primes)
|
1544 |
+
if all(v == 1 for v in tally.values()):
|
1545 |
+
multiple = list(tally.keys())
|
1546 |
+
phi = _totient._from_distinct_primes(*multiple)
|
1547 |
+
|
1548 |
+
else:
|
1549 |
+
if not multipower:
|
1550 |
+
NonInvertibleCipherWarning(
|
1551 |
+
'Non-distinctive primes found in the factors {}. '
|
1552 |
+
'The cipher may not be decryptable for some numbers '
|
1553 |
+
'in the complete residue system Z[{}], but the cipher '
|
1554 |
+
'can still be valid if you restrict the domain to be '
|
1555 |
+
'the reduced residue system Z*[{}]. You can pass '
|
1556 |
+
'the flag multipower=True if you want to suppress this '
|
1557 |
+
'warning.'
|
1558 |
+
.format(primes, n, n)
|
1559 |
+
# stacklevel=4 because most users will call a function that
|
1560 |
+
# calls this function
|
1561 |
+
).warn(stacklevel=4)
|
1562 |
+
phi = _totient._from_factors(tally)
|
1563 |
+
|
1564 |
+
if igcd(e, phi) == 1:
|
1565 |
+
if public and not private:
|
1566 |
+
if isinstance(index, int):
|
1567 |
+
e = e % phi
|
1568 |
+
e += index * phi
|
1569 |
+
return n, e
|
1570 |
+
|
1571 |
+
if private and not public:
|
1572 |
+
d = mod_inverse(e, phi)
|
1573 |
+
if isinstance(index, int):
|
1574 |
+
d += index * phi
|
1575 |
+
return n, d
|
1576 |
+
|
1577 |
+
return False
|
1578 |
+
|
1579 |
+
|
1580 |
+
def rsa_public_key(*args, **kwargs):
|
1581 |
+
r"""Return the RSA *public key* pair, `(n, e)`
|
1582 |
+
|
1583 |
+
Parameters
|
1584 |
+
==========
|
1585 |
+
|
1586 |
+
args : naturals
|
1587 |
+
If specified as `p, q, e` where `p` and `q` are distinct primes
|
1588 |
+
and `e` is a desired public exponent of the RSA, `n = p q` and
|
1589 |
+
`e` will be verified against the totient
|
1590 |
+
`\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient)
|
1591 |
+
to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`.
|
1592 |
+
|
1593 |
+
If specified as `p_1, p_2, \dots, p_n, e` where
|
1594 |
+
`p_1, p_2, \dots, p_n` are specified as primes,
|
1595 |
+
and `e` is specified as a desired public exponent of the RSA,
|
1596 |
+
it will be able to form a multi-prime RSA, which is a more
|
1597 |
+
generalized form of the popular 2-prime RSA.
|
1598 |
+
|
1599 |
+
It can also be possible to form a single-prime RSA by specifying
|
1600 |
+
the argument as `p, e`, which can be considered a trivial case
|
1601 |
+
of a multiprime RSA.
|
1602 |
+
|
1603 |
+
Furthermore, it can be possible to form a multi-power RSA by
|
1604 |
+
specifying two or more pairs of the primes to be same.
|
1605 |
+
However, unlike the two-distinct prime RSA or multi-prime
|
1606 |
+
RSA, not every numbers in the complete residue system
|
1607 |
+
(`\mathbb{Z}_n`) will be decryptable since the mapping
|
1608 |
+
`\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}`
|
1609 |
+
will not be bijective.
|
1610 |
+
(Only except for the trivial case when
|
1611 |
+
`e = 1`
|
1612 |
+
or more generally,
|
1613 |
+
|
1614 |
+
.. math::
|
1615 |
+
e \in \left \{ 1 + k \lambda(n)
|
1616 |
+
\mid k \in \mathbb{Z} \land k \geq 0 \right \}
|
1617 |
+
|
1618 |
+
when RSA reduces to the identity.)
|
1619 |
+
However, the RSA can still be decryptable for the numbers in the
|
1620 |
+
reduced residue system (`\mathbb{Z}_n^{\times}`), since the
|
1621 |
+
mapping
|
1622 |
+
`\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}`
|
1623 |
+
can still be bijective.
|
1624 |
+
|
1625 |
+
If you pass a non-prime integer to the arguments
|
1626 |
+
`p_1, p_2, \dots, p_n`, the particular number will be
|
1627 |
+
prime-factored and it will become either a multi-prime RSA or a
|
1628 |
+
multi-power RSA in its canonical form, depending on whether the
|
1629 |
+
product equals its radical or not.
|
1630 |
+
`p_1 p_2 \dots p_n = \text{rad}(p_1 p_2 \dots p_n)`
|
1631 |
+
|
1632 |
+
totient : bool, optional
|
1633 |
+
If ``'Euler'``, it uses Euler's totient `\phi(n)` which is
|
1634 |
+
:meth:`sympy.ntheory.factor_.totient` in SymPy.
|
1635 |
+
|
1636 |
+
If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)`
|
1637 |
+
which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
|
1638 |
+
|
1639 |
+
Unlike private key generation, this is a trivial keyword for
|
1640 |
+
public key generation because
|
1641 |
+
`\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`.
|
1642 |
+
|
1643 |
+
index : nonnegative integer, optional
|
1644 |
+
Returns an arbitrary solution of a RSA public key at the index
|
1645 |
+
specified at `0, 1, 2, \dots`. This parameter needs to be
|
1646 |
+
specified along with ``totient='Carmichael'``.
|
1647 |
+
|
1648 |
+
Similarly to the non-uniquenss of a RSA private key as described
|
1649 |
+
in the ``index`` parameter documentation in
|
1650 |
+
:meth:`rsa_private_key`, RSA public key is also not unique and
|
1651 |
+
there is an infinite number of RSA public exponents which
|
1652 |
+
can behave in the same manner.
|
1653 |
+
|
1654 |
+
From any given RSA public exponent `e`, there are can be an
|
1655 |
+
another RSA public exponent `e + k \lambda(n)` where `k` is an
|
1656 |
+
integer, `\lambda` is a Carmichael's totient function.
|
1657 |
+
|
1658 |
+
However, considering only the positive cases, there can be
|
1659 |
+
a principal solution of a RSA public exponent `e_0` in
|
1660 |
+
`0 < e_0 < \lambda(n)`, and all the other solutions
|
1661 |
+
can be canonicalzed in a form of `e_0 + k \lambda(n)`.
|
1662 |
+
|
1663 |
+
``index`` specifies the `k` notation to yield any possible value
|
1664 |
+
an RSA public key can have.
|
1665 |
+
|
1666 |
+
An example of computing any arbitrary RSA public key:
|
1667 |
+
|
1668 |
+
>>> from sympy.crypto.crypto import rsa_public_key
|
1669 |
+
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0)
|
1670 |
+
(3233, 17)
|
1671 |
+
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1)
|
1672 |
+
(3233, 797)
|
1673 |
+
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2)
|
1674 |
+
(3233, 1577)
|
1675 |
+
|
1676 |
+
multipower : bool, optional
|
1677 |
+
Any pair of non-distinct primes found in the RSA specification
|
1678 |
+
will restrict the domain of the cryptosystem, as noted in the
|
1679 |
+
explanation of the parameter ``args``.
|
1680 |
+
|
1681 |
+
SymPy RSA key generator may give a warning before dispatching it
|
1682 |
+
as a multi-power RSA, however, you can disable the warning if
|
1683 |
+
you pass ``True`` to this keyword.
|
1684 |
+
|
1685 |
+
Returns
|
1686 |
+
=======
|
1687 |
+
|
1688 |
+
(n, e) : int, int
|
1689 |
+
`n` is a product of any arbitrary number of primes given as
|
1690 |
+
the argument.
|
1691 |
+
|
1692 |
+
`e` is relatively prime (coprime) to the Euler totient
|
1693 |
+
`\phi(n)`.
|
1694 |
+
|
1695 |
+
False
|
1696 |
+
Returned if less than two arguments are given, or `e` is
|
1697 |
+
not relatively prime to the modulus.
|
1698 |
+
|
1699 |
+
Examples
|
1700 |
+
========
|
1701 |
+
|
1702 |
+
>>> from sympy.crypto.crypto import rsa_public_key
|
1703 |
+
|
1704 |
+
A public key of a two-prime RSA:
|
1705 |
+
|
1706 |
+
>>> p, q, e = 3, 5, 7
|
1707 |
+
>>> rsa_public_key(p, q, e)
|
1708 |
+
(15, 7)
|
1709 |
+
>>> rsa_public_key(p, q, 30)
|
1710 |
+
False
|
1711 |
+
|
1712 |
+
A public key of a multiprime RSA:
|
1713 |
+
|
1714 |
+
>>> primes = [2, 3, 5, 7, 11, 13]
|
1715 |
+
>>> e = 7
|
1716 |
+
>>> args = primes + [e]
|
1717 |
+
>>> rsa_public_key(*args)
|
1718 |
+
(30030, 7)
|
1719 |
+
|
1720 |
+
Notes
|
1721 |
+
=====
|
1722 |
+
|
1723 |
+
Although the RSA can be generalized over any modulus `n`, using
|
1724 |
+
two large primes had became the most popular specification because a
|
1725 |
+
product of two large primes is usually the hardest to factor
|
1726 |
+
relatively to the digits of `n` can have.
|
1727 |
+
|
1728 |
+
However, it may need further understanding of the time complexities
|
1729 |
+
of each prime-factoring algorithms to verify the claim.
|
1730 |
+
|
1731 |
+
See Also
|
1732 |
+
========
|
1733 |
+
|
1734 |
+
rsa_private_key
|
1735 |
+
encipher_rsa
|
1736 |
+
decipher_rsa
|
1737 |
+
|
1738 |
+
References
|
1739 |
+
==========
|
1740 |
+
|
1741 |
+
.. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
|
1742 |
+
|
1743 |
+
.. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
|
1744 |
+
|
1745 |
+
.. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
|
1746 |
+
|
1747 |
+
.. [4] https://www.itiis.org/digital-library/manuscript/1381
|
1748 |
+
"""
|
1749 |
+
return _rsa_key(*args, public=True, private=False, **kwargs)
|
1750 |
+
|
1751 |
+
|
1752 |
+
def rsa_private_key(*args, **kwargs):
|
1753 |
+
r"""Return the RSA *private key* pair, `(n, d)`
|
1754 |
+
|
1755 |
+
Parameters
|
1756 |
+
==========
|
1757 |
+
|
1758 |
+
args : naturals
|
1759 |
+
The keyword is identical to the ``args`` in
|
1760 |
+
:meth:`rsa_public_key`.
|
1761 |
+
|
1762 |
+
totient : bool, optional
|
1763 |
+
If ``'Euler'``, it uses Euler's totient convention `\phi(n)`
|
1764 |
+
which is :meth:`sympy.ntheory.factor_.totient` in SymPy.
|
1765 |
+
|
1766 |
+
If ``'Carmichael'``, it uses Carmichael's totient convention
|
1767 |
+
`\lambda(n)` which is
|
1768 |
+
:meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
|
1769 |
+
|
1770 |
+
There can be some output differences for private key generation
|
1771 |
+
as examples below.
|
1772 |
+
|
1773 |
+
Example using Euler's totient:
|
1774 |
+
|
1775 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
1776 |
+
>>> rsa_private_key(61, 53, 17, totient='Euler')
|
1777 |
+
(3233, 2753)
|
1778 |
+
|
1779 |
+
Example using Carmichael's totient:
|
1780 |
+
|
1781 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
1782 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael')
|
1783 |
+
(3233, 413)
|
1784 |
+
|
1785 |
+
index : nonnegative integer, optional
|
1786 |
+
Returns an arbitrary solution of a RSA private key at the index
|
1787 |
+
specified at `0, 1, 2, \dots`. This parameter needs to be
|
1788 |
+
specified along with ``totient='Carmichael'``.
|
1789 |
+
|
1790 |
+
RSA private exponent is a non-unique solution of
|
1791 |
+
`e d \mod \lambda(n) = 1` and it is possible in any form of
|
1792 |
+
`d + k \lambda(n)`, where `d` is an another
|
1793 |
+
already-computed private exponent, and `\lambda` is a
|
1794 |
+
Carmichael's totient function, and `k` is any integer.
|
1795 |
+
|
1796 |
+
However, considering only the positive cases, there can be
|
1797 |
+
a principal solution of a RSA private exponent `d_0` in
|
1798 |
+
`0 < d_0 < \lambda(n)`, and all the other solutions
|
1799 |
+
can be canonicalzed in a form of `d_0 + k \lambda(n)`.
|
1800 |
+
|
1801 |
+
``index`` specifies the `k` notation to yield any possible value
|
1802 |
+
an RSA private key can have.
|
1803 |
+
|
1804 |
+
An example of computing any arbitrary RSA private key:
|
1805 |
+
|
1806 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
1807 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0)
|
1808 |
+
(3233, 413)
|
1809 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1)
|
1810 |
+
(3233, 1193)
|
1811 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2)
|
1812 |
+
(3233, 1973)
|
1813 |
+
|
1814 |
+
multipower : bool, optional
|
1815 |
+
The keyword is identical to the ``multipower`` in
|
1816 |
+
:meth:`rsa_public_key`.
|
1817 |
+
|
1818 |
+
Returns
|
1819 |
+
=======
|
1820 |
+
|
1821 |
+
(n, d) : int, int
|
1822 |
+
`n` is a product of any arbitrary number of primes given as
|
1823 |
+
the argument.
|
1824 |
+
|
1825 |
+
`d` is the inverse of `e` (mod `\phi(n)`) where `e` is the
|
1826 |
+
exponent given, and `\phi` is a Euler totient.
|
1827 |
+
|
1828 |
+
False
|
1829 |
+
Returned if less than two arguments are given, or `e` is
|
1830 |
+
not relatively prime to the totient of the modulus.
|
1831 |
+
|
1832 |
+
Examples
|
1833 |
+
========
|
1834 |
+
|
1835 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
1836 |
+
|
1837 |
+
A private key of a two-prime RSA:
|
1838 |
+
|
1839 |
+
>>> p, q, e = 3, 5, 7
|
1840 |
+
>>> rsa_private_key(p, q, e)
|
1841 |
+
(15, 7)
|
1842 |
+
>>> rsa_private_key(p, q, 30)
|
1843 |
+
False
|
1844 |
+
|
1845 |
+
A private key of a multiprime RSA:
|
1846 |
+
|
1847 |
+
>>> primes = [2, 3, 5, 7, 11, 13]
|
1848 |
+
>>> e = 7
|
1849 |
+
>>> args = primes + [e]
|
1850 |
+
>>> rsa_private_key(*args)
|
1851 |
+
(30030, 823)
|
1852 |
+
|
1853 |
+
See Also
|
1854 |
+
========
|
1855 |
+
|
1856 |
+
rsa_public_key
|
1857 |
+
encipher_rsa
|
1858 |
+
decipher_rsa
|
1859 |
+
|
1860 |
+
References
|
1861 |
+
==========
|
1862 |
+
|
1863 |
+
.. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
|
1864 |
+
|
1865 |
+
.. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
|
1866 |
+
|
1867 |
+
.. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
|
1868 |
+
|
1869 |
+
.. [4] https://www.itiis.org/digital-library/manuscript/1381
|
1870 |
+
"""
|
1871 |
+
return _rsa_key(*args, public=False, private=True, **kwargs)
|
1872 |
+
|
1873 |
+
|
1874 |
+
def _encipher_decipher_rsa(i, key, factors=None):
|
1875 |
+
n, d = key
|
1876 |
+
if not factors:
|
1877 |
+
return pow(i, d, n)
|
1878 |
+
|
1879 |
+
def _is_coprime_set(l):
|
1880 |
+
is_coprime_set = True
|
1881 |
+
for i in range(len(l)):
|
1882 |
+
for j in range(i+1, len(l)):
|
1883 |
+
if igcd(l[i], l[j]) != 1:
|
1884 |
+
is_coprime_set = False
|
1885 |
+
break
|
1886 |
+
return is_coprime_set
|
1887 |
+
|
1888 |
+
prod = reduce(lambda i, j: i*j, factors)
|
1889 |
+
if prod == n and _is_coprime_set(factors):
|
1890 |
+
return _decipher_rsa_crt(i, d, factors)
|
1891 |
+
return _encipher_decipher_rsa(i, key, factors=None)
|
1892 |
+
|
1893 |
+
|
1894 |
+
def encipher_rsa(i, key, factors=None):
|
1895 |
+
r"""Encrypt the plaintext with RSA.
|
1896 |
+
|
1897 |
+
Parameters
|
1898 |
+
==========
|
1899 |
+
|
1900 |
+
i : integer
|
1901 |
+
The plaintext to be encrypted for.
|
1902 |
+
|
1903 |
+
key : (n, e) where n, e are integers
|
1904 |
+
`n` is the modulus of the key and `e` is the exponent of the
|
1905 |
+
key. The encryption is computed by `i^e \bmod n`.
|
1906 |
+
|
1907 |
+
The key can either be a public key or a private key, however,
|
1908 |
+
the message encrypted by a public key can only be decrypted by
|
1909 |
+
a private key, and vice versa, as RSA is an asymmetric
|
1910 |
+
cryptography system.
|
1911 |
+
|
1912 |
+
factors : list of coprime integers
|
1913 |
+
This is identical to the keyword ``factors`` in
|
1914 |
+
:meth:`decipher_rsa`.
|
1915 |
+
|
1916 |
+
Notes
|
1917 |
+
=====
|
1918 |
+
|
1919 |
+
Some specifications may make the RSA not cryptographically
|
1920 |
+
meaningful.
|
1921 |
+
|
1922 |
+
For example, `0`, `1` will remain always same after taking any
|
1923 |
+
number of exponentiation, thus, should be avoided.
|
1924 |
+
|
1925 |
+
Furthermore, if `i^e < n`, `i` may easily be figured out by taking
|
1926 |
+
`e` th root.
|
1927 |
+
|
1928 |
+
And also, specifying the exponent as `1` or in more generalized form
|
1929 |
+
as `1 + k \lambda(n)` where `k` is an nonnegative integer,
|
1930 |
+
`\lambda` is a carmichael totient, the RSA becomes an identity
|
1931 |
+
mapping.
|
1932 |
+
|
1933 |
+
Examples
|
1934 |
+
========
|
1935 |
+
|
1936 |
+
>>> from sympy.crypto.crypto import encipher_rsa
|
1937 |
+
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
|
1938 |
+
|
1939 |
+
Public Key Encryption:
|
1940 |
+
|
1941 |
+
>>> p, q, e = 3, 5, 7
|
1942 |
+
>>> puk = rsa_public_key(p, q, e)
|
1943 |
+
>>> msg = 12
|
1944 |
+
>>> encipher_rsa(msg, puk)
|
1945 |
+
3
|
1946 |
+
|
1947 |
+
Private Key Encryption:
|
1948 |
+
|
1949 |
+
>>> p, q, e = 3, 5, 7
|
1950 |
+
>>> prk = rsa_private_key(p, q, e)
|
1951 |
+
>>> msg = 12
|
1952 |
+
>>> encipher_rsa(msg, prk)
|
1953 |
+
3
|
1954 |
+
|
1955 |
+
Encryption using chinese remainder theorem:
|
1956 |
+
|
1957 |
+
>>> encipher_rsa(msg, prk, factors=[p, q])
|
1958 |
+
3
|
1959 |
+
"""
|
1960 |
+
return _encipher_decipher_rsa(i, key, factors=factors)
|
1961 |
+
|
1962 |
+
|
1963 |
+
def decipher_rsa(i, key, factors=None):
|
1964 |
+
r"""Decrypt the ciphertext with RSA.
|
1965 |
+
|
1966 |
+
Parameters
|
1967 |
+
==========
|
1968 |
+
|
1969 |
+
i : integer
|
1970 |
+
The ciphertext to be decrypted for.
|
1971 |
+
|
1972 |
+
key : (n, d) where n, d are integers
|
1973 |
+
`n` is the modulus of the key and `d` is the exponent of the
|
1974 |
+
key. The decryption is computed by `i^d \bmod n`.
|
1975 |
+
|
1976 |
+
The key can either be a public key or a private key, however,
|
1977 |
+
the message encrypted by a public key can only be decrypted by
|
1978 |
+
a private key, and vice versa, as RSA is an asymmetric
|
1979 |
+
cryptography system.
|
1980 |
+
|
1981 |
+
factors : list of coprime integers
|
1982 |
+
As the modulus `n` created from RSA key generation is composed
|
1983 |
+
of arbitrary prime factors
|
1984 |
+
`n = {p_1}^{k_1}{p_2}^{k_2}\dots{p_n}^{k_n}` where
|
1985 |
+
`p_1, p_2, \dots, p_n` are distinct primes and
|
1986 |
+
`k_1, k_2, \dots, k_n` are positive integers, chinese remainder
|
1987 |
+
theorem can be used to compute `i^d \bmod n` from the
|
1988 |
+
fragmented modulo operations like
|
1989 |
+
|
1990 |
+
.. math::
|
1991 |
+
i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, \dots,
|
1992 |
+
i^d \bmod {p_n}^{k_n}
|
1993 |
+
|
1994 |
+
or like
|
1995 |
+
|
1996 |
+
.. math::
|
1997 |
+
i^d \bmod {p_1}^{k_1}{p_2}^{k_2},
|
1998 |
+
i^d \bmod {p_3}^{k_3}, \dots ,
|
1999 |
+
i^d \bmod {p_n}^{k_n}
|
2000 |
+
|
2001 |
+
as long as every moduli does not share any common divisor each
|
2002 |
+
other.
|
2003 |
+
|
2004 |
+
The raw primes used in generating the RSA key pair can be a good
|
2005 |
+
option.
|
2006 |
+
|
2007 |
+
Note that the speed advantage of using this is only viable for
|
2008 |
+
very large cases (Like 2048-bit RSA keys) since the
|
2009 |
+
overhead of using pure Python implementation of
|
2010 |
+
:meth:`sympy.ntheory.modular.crt` may overcompensate the
|
2011 |
+
theoretical speed advantage.
|
2012 |
+
|
2013 |
+
Notes
|
2014 |
+
=====
|
2015 |
+
|
2016 |
+
See the ``Notes`` section in the documentation of
|
2017 |
+
:meth:`encipher_rsa`
|
2018 |
+
|
2019 |
+
Examples
|
2020 |
+
========
|
2021 |
+
|
2022 |
+
>>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa
|
2023 |
+
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
|
2024 |
+
|
2025 |
+
Public Key Encryption and Decryption:
|
2026 |
+
|
2027 |
+
>>> p, q, e = 3, 5, 7
|
2028 |
+
>>> prk = rsa_private_key(p, q, e)
|
2029 |
+
>>> puk = rsa_public_key(p, q, e)
|
2030 |
+
>>> msg = 12
|
2031 |
+
>>> new_msg = encipher_rsa(msg, prk)
|
2032 |
+
>>> new_msg
|
2033 |
+
3
|
2034 |
+
>>> decipher_rsa(new_msg, puk)
|
2035 |
+
12
|
2036 |
+
|
2037 |
+
Private Key Encryption and Decryption:
|
2038 |
+
|
2039 |
+
>>> p, q, e = 3, 5, 7
|
2040 |
+
>>> prk = rsa_private_key(p, q, e)
|
2041 |
+
>>> puk = rsa_public_key(p, q, e)
|
2042 |
+
>>> msg = 12
|
2043 |
+
>>> new_msg = encipher_rsa(msg, puk)
|
2044 |
+
>>> new_msg
|
2045 |
+
3
|
2046 |
+
>>> decipher_rsa(new_msg, prk)
|
2047 |
+
12
|
2048 |
+
|
2049 |
+
Decryption using chinese remainder theorem:
|
2050 |
+
|
2051 |
+
>>> decipher_rsa(new_msg, prk, factors=[p, q])
|
2052 |
+
12
|
2053 |
+
|
2054 |
+
See Also
|
2055 |
+
========
|
2056 |
+
|
2057 |
+
encipher_rsa
|
2058 |
+
"""
|
2059 |
+
return _encipher_decipher_rsa(i, key, factors=factors)
|
2060 |
+
|
2061 |
+
|
2062 |
+
#################### kid krypto (kid RSA) #############################
|
2063 |
+
|
2064 |
+
|
2065 |
+
def kid_rsa_public_key(a, b, A, B):
|
2066 |
+
r"""
|
2067 |
+
Kid RSA is a version of RSA useful to teach grade school children
|
2068 |
+
since it does not involve exponentiation.
|
2069 |
+
|
2070 |
+
Explanation
|
2071 |
+
===========
|
2072 |
+
|
2073 |
+
Alice wants to talk to Bob. Bob generates keys as follows.
|
2074 |
+
Key generation:
|
2075 |
+
|
2076 |
+
* Select positive integers `a, b, A, B` at random.
|
2077 |
+
* Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
|
2078 |
+
`n = (e d - 1)//M`.
|
2079 |
+
* The *public key* is `(n, e)`. Bob sends these to Alice.
|
2080 |
+
* The *private key* is `(n, d)`, which Bob keeps secret.
|
2081 |
+
|
2082 |
+
Encryption: If `p` is the plaintext message then the
|
2083 |
+
ciphertext is `c = p e \pmod n`.
|
2084 |
+
|
2085 |
+
Decryption: If `c` is the ciphertext message then the
|
2086 |
+
plaintext is `p = c d \pmod n`.
|
2087 |
+
|
2088 |
+
Examples
|
2089 |
+
========
|
2090 |
+
|
2091 |
+
>>> from sympy.crypto.crypto import kid_rsa_public_key
|
2092 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
2093 |
+
>>> kid_rsa_public_key(a, b, A, B)
|
2094 |
+
(369, 58)
|
2095 |
+
|
2096 |
+
"""
|
2097 |
+
M = a*b - 1
|
2098 |
+
e = A*M + a
|
2099 |
+
d = B*M + b
|
2100 |
+
n = (e*d - 1)//M
|
2101 |
+
return n, e
|
2102 |
+
|
2103 |
+
|
2104 |
+
def kid_rsa_private_key(a, b, A, B):
|
2105 |
+
"""
|
2106 |
+
Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
|
2107 |
+
`n = (e d - 1) / M`. The *private key* is `d`, which Bob
|
2108 |
+
keeps secret.
|
2109 |
+
|
2110 |
+
Examples
|
2111 |
+
========
|
2112 |
+
|
2113 |
+
>>> from sympy.crypto.crypto import kid_rsa_private_key
|
2114 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
2115 |
+
>>> kid_rsa_private_key(a, b, A, B)
|
2116 |
+
(369, 70)
|
2117 |
+
|
2118 |
+
"""
|
2119 |
+
M = a*b - 1
|
2120 |
+
e = A*M + a
|
2121 |
+
d = B*M + b
|
2122 |
+
n = (e*d - 1)//M
|
2123 |
+
return n, d
|
2124 |
+
|
2125 |
+
|
2126 |
+
def encipher_kid_rsa(msg, key):
|
2127 |
+
"""
|
2128 |
+
Here ``msg`` is the plaintext and ``key`` is the public key.
|
2129 |
+
|
2130 |
+
Examples
|
2131 |
+
========
|
2132 |
+
|
2133 |
+
>>> from sympy.crypto.crypto import (
|
2134 |
+
... encipher_kid_rsa, kid_rsa_public_key)
|
2135 |
+
>>> msg = 200
|
2136 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
2137 |
+
>>> key = kid_rsa_public_key(a, b, A, B)
|
2138 |
+
>>> encipher_kid_rsa(msg, key)
|
2139 |
+
161
|
2140 |
+
|
2141 |
+
"""
|
2142 |
+
n, e = key
|
2143 |
+
return (msg*e) % n
|
2144 |
+
|
2145 |
+
|
2146 |
+
def decipher_kid_rsa(msg, key):
|
2147 |
+
"""
|
2148 |
+
Here ``msg`` is the plaintext and ``key`` is the private key.
|
2149 |
+
|
2150 |
+
Examples
|
2151 |
+
========
|
2152 |
+
|
2153 |
+
>>> from sympy.crypto.crypto import (
|
2154 |
+
... kid_rsa_public_key, kid_rsa_private_key,
|
2155 |
+
... decipher_kid_rsa, encipher_kid_rsa)
|
2156 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
2157 |
+
>>> d = kid_rsa_private_key(a, b, A, B)
|
2158 |
+
>>> msg = 200
|
2159 |
+
>>> pub = kid_rsa_public_key(a, b, A, B)
|
2160 |
+
>>> pri = kid_rsa_private_key(a, b, A, B)
|
2161 |
+
>>> ct = encipher_kid_rsa(msg, pub)
|
2162 |
+
>>> decipher_kid_rsa(ct, pri)
|
2163 |
+
200
|
2164 |
+
|
2165 |
+
"""
|
2166 |
+
n, d = key
|
2167 |
+
return (msg*d) % n
|
2168 |
+
|
2169 |
+
|
2170 |
+
#################### Morse Code ######################################
|
2171 |
+
|
2172 |
+
morse_char = {
|
2173 |
+
".-": "A", "-...": "B",
|
2174 |
+
"-.-.": "C", "-..": "D",
|
2175 |
+
".": "E", "..-.": "F",
|
2176 |
+
"--.": "G", "....": "H",
|
2177 |
+
"..": "I", ".---": "J",
|
2178 |
+
"-.-": "K", ".-..": "L",
|
2179 |
+
"--": "M", "-.": "N",
|
2180 |
+
"---": "O", ".--.": "P",
|
2181 |
+
"--.-": "Q", ".-.": "R",
|
2182 |
+
"...": "S", "-": "T",
|
2183 |
+
"..-": "U", "...-": "V",
|
2184 |
+
".--": "W", "-..-": "X",
|
2185 |
+
"-.--": "Y", "--..": "Z",
|
2186 |
+
"-----": "0", ".----": "1",
|
2187 |
+
"..---": "2", "...--": "3",
|
2188 |
+
"....-": "4", ".....": "5",
|
2189 |
+
"-....": "6", "--...": "7",
|
2190 |
+
"---..": "8", "----.": "9",
|
2191 |
+
".-.-.-": ".", "--..--": ",",
|
2192 |
+
"---...": ":", "-.-.-.": ";",
|
2193 |
+
"..--..": "?", "-....-": "-",
|
2194 |
+
"..--.-": "_", "-.--.": "(",
|
2195 |
+
"-.--.-": ")", ".----.": "'",
|
2196 |
+
"-...-": "=", ".-.-.": "+",
|
2197 |
+
"-..-.": "/", ".--.-.": "@",
|
2198 |
+
"...-..-": "$", "-.-.--": "!"}
|
2199 |
+
char_morse = {v: k for k, v in morse_char.items()}
|
2200 |
+
|
2201 |
+
|
2202 |
+
def encode_morse(msg, sep='|', mapping=None):
|
2203 |
+
"""
|
2204 |
+
Encodes a plaintext into popular Morse Code with letters
|
2205 |
+
separated by ``sep`` and words by a double ``sep``.
|
2206 |
+
|
2207 |
+
Examples
|
2208 |
+
========
|
2209 |
+
|
2210 |
+
>>> from sympy.crypto.crypto import encode_morse
|
2211 |
+
>>> msg = 'ATTACK RIGHT FLANK'
|
2212 |
+
>>> encode_morse(msg)
|
2213 |
+
'.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-'
|
2214 |
+
|
2215 |
+
References
|
2216 |
+
==========
|
2217 |
+
|
2218 |
+
.. [1] https://en.wikipedia.org/wiki/Morse_code
|
2219 |
+
|
2220 |
+
"""
|
2221 |
+
|
2222 |
+
mapping = mapping or char_morse
|
2223 |
+
assert sep not in mapping
|
2224 |
+
word_sep = 2*sep
|
2225 |
+
mapping[" "] = word_sep
|
2226 |
+
suffix = msg and msg[-1] in whitespace
|
2227 |
+
|
2228 |
+
# normalize whitespace
|
2229 |
+
msg = (' ' if word_sep else '').join(msg.split())
|
2230 |
+
# omit unmapped chars
|
2231 |
+
chars = set(''.join(msg.split()))
|
2232 |
+
ok = set(mapping.keys())
|
2233 |
+
msg = translate(msg, None, ''.join(chars - ok))
|
2234 |
+
|
2235 |
+
morsestring = []
|
2236 |
+
words = msg.split()
|
2237 |
+
for word in words:
|
2238 |
+
morseword = []
|
2239 |
+
for letter in word:
|
2240 |
+
morseletter = mapping[letter]
|
2241 |
+
morseword.append(morseletter)
|
2242 |
+
|
2243 |
+
word = sep.join(morseword)
|
2244 |
+
morsestring.append(word)
|
2245 |
+
|
2246 |
+
return word_sep.join(morsestring) + (word_sep if suffix else '')
|
2247 |
+
|
2248 |
+
|
2249 |
+
def decode_morse(msg, sep='|', mapping=None):
|
2250 |
+
"""
|
2251 |
+
Decodes a Morse Code with letters separated by ``sep``
|
2252 |
+
(default is '|') and words by `word_sep` (default is '||)
|
2253 |
+
into plaintext.
|
2254 |
+
|
2255 |
+
Examples
|
2256 |
+
========
|
2257 |
+
|
2258 |
+
>>> from sympy.crypto.crypto import decode_morse
|
2259 |
+
>>> mc = '--|---|...-|.||.|.-|...|-'
|
2260 |
+
>>> decode_morse(mc)
|
2261 |
+
'MOVE EAST'
|
2262 |
+
|
2263 |
+
References
|
2264 |
+
==========
|
2265 |
+
|
2266 |
+
.. [1] https://en.wikipedia.org/wiki/Morse_code
|
2267 |
+
|
2268 |
+
"""
|
2269 |
+
|
2270 |
+
mapping = mapping or morse_char
|
2271 |
+
word_sep = 2*sep
|
2272 |
+
characterstring = []
|
2273 |
+
words = msg.strip(word_sep).split(word_sep)
|
2274 |
+
for word in words:
|
2275 |
+
letters = word.split(sep)
|
2276 |
+
chars = [mapping[c] for c in letters]
|
2277 |
+
word = ''.join(chars)
|
2278 |
+
characterstring.append(word)
|
2279 |
+
rv = " ".join(characterstring)
|
2280 |
+
return rv
|
2281 |
+
|
2282 |
+
|
2283 |
+
#################### LFSRs ##########################################
|
2284 |
+
|
2285 |
+
|
2286 |
+
def lfsr_sequence(key, fill, n):
|
2287 |
+
r"""
|
2288 |
+
This function creates an LFSR sequence.
|
2289 |
+
|
2290 |
+
Parameters
|
2291 |
+
==========
|
2292 |
+
|
2293 |
+
key : list
|
2294 |
+
A list of finite field elements, `[c_0, c_1, \ldots, c_k].`
|
2295 |
+
|
2296 |
+
fill : list
|
2297 |
+
The list of the initial terms of the LFSR sequence,
|
2298 |
+
`[x_0, x_1, \ldots, x_k].`
|
2299 |
+
|
2300 |
+
n
|
2301 |
+
Number of terms of the sequence that the function returns.
|
2302 |
+
|
2303 |
+
Returns
|
2304 |
+
=======
|
2305 |
+
|
2306 |
+
L
|
2307 |
+
The LFSR sequence defined by
|
2308 |
+
`x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for
|
2309 |
+
`n \leq k`.
|
2310 |
+
|
2311 |
+
Notes
|
2312 |
+
=====
|
2313 |
+
|
2314 |
+
S. Golomb [G]_ gives a list of three statistical properties a
|
2315 |
+
sequence of numbers `a = \{a_n\}_{n=1}^\infty`,
|
2316 |
+
`a_n \in \{0,1\}`, should display to be considered
|
2317 |
+
"random". Define the autocorrelation of `a` to be
|
2318 |
+
|
2319 |
+
.. math::
|
2320 |
+
|
2321 |
+
C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}.
|
2322 |
+
|
2323 |
+
In the case where `a` is periodic with period
|
2324 |
+
`P` then this reduces to
|
2325 |
+
|
2326 |
+
.. math::
|
2327 |
+
|
2328 |
+
C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}.
|
2329 |
+
|
2330 |
+
Assume `a` is periodic with period `P`.
|
2331 |
+
|
2332 |
+
- balance:
|
2333 |
+
|
2334 |
+
.. math::
|
2335 |
+
|
2336 |
+
\left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1.
|
2337 |
+
|
2338 |
+
- low autocorrelation:
|
2339 |
+
|
2340 |
+
.. math::
|
2341 |
+
|
2342 |
+
C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right.
|
2343 |
+
|
2344 |
+
(For sequences satisfying these first two properties, it is known
|
2345 |
+
that `\epsilon = -1/P` must hold.)
|
2346 |
+
|
2347 |
+
- proportional runs property: In each period, half the runs have
|
2348 |
+
length `1`, one-fourth have length `2`, etc.
|
2349 |
+
Moreover, there are as many runs of `1`'s as there are of
|
2350 |
+
`0`'s.
|
2351 |
+
|
2352 |
+
Examples
|
2353 |
+
========
|
2354 |
+
|
2355 |
+
>>> from sympy.crypto.crypto import lfsr_sequence
|
2356 |
+
>>> from sympy.polys.domains import FF
|
2357 |
+
>>> F = FF(2)
|
2358 |
+
>>> fill = [F(1), F(1), F(0), F(1)]
|
2359 |
+
>>> key = [F(1), F(0), F(0), F(1)]
|
2360 |
+
>>> lfsr_sequence(key, fill, 10)
|
2361 |
+
[1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2,
|
2362 |
+
1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2]
|
2363 |
+
|
2364 |
+
References
|
2365 |
+
==========
|
2366 |
+
|
2367 |
+
.. [G] Solomon Golomb, Shift register sequences, Aegean Park Press,
|
2368 |
+
Laguna Hills, Ca, 1967
|
2369 |
+
|
2370 |
+
"""
|
2371 |
+
if not isinstance(key, list):
|
2372 |
+
raise TypeError("key must be a list")
|
2373 |
+
if not isinstance(fill, list):
|
2374 |
+
raise TypeError("fill must be a list")
|
2375 |
+
p = key[0].mod
|
2376 |
+
F = FF(p)
|
2377 |
+
s = fill
|
2378 |
+
k = len(fill)
|
2379 |
+
L = []
|
2380 |
+
for i in range(n):
|
2381 |
+
s0 = s[:]
|
2382 |
+
L.append(s[0])
|
2383 |
+
s = s[1:k]
|
2384 |
+
x = sum([int(key[i]*s0[i]) for i in range(k)])
|
2385 |
+
s.append(F(x))
|
2386 |
+
return L # use [x.to_int() for x in L] for int version
|
2387 |
+
|
2388 |
+
|
2389 |
+
def lfsr_autocorrelation(L, P, k):
|
2390 |
+
"""
|
2391 |
+
This function computes the LFSR autocorrelation function.
|
2392 |
+
|
2393 |
+
Parameters
|
2394 |
+
==========
|
2395 |
+
|
2396 |
+
L
|
2397 |
+
A periodic sequence of elements of `GF(2)`.
|
2398 |
+
L must have length larger than P.
|
2399 |
+
|
2400 |
+
P
|
2401 |
+
The period of L.
|
2402 |
+
|
2403 |
+
k : int
|
2404 |
+
An integer `k` (`0 < k < P`).
|
2405 |
+
|
2406 |
+
Returns
|
2407 |
+
=======
|
2408 |
+
|
2409 |
+
autocorrelation
|
2410 |
+
The k-th value of the autocorrelation of the LFSR L.
|
2411 |
+
|
2412 |
+
Examples
|
2413 |
+
========
|
2414 |
+
|
2415 |
+
>>> from sympy.crypto.crypto import (
|
2416 |
+
... lfsr_sequence, lfsr_autocorrelation)
|
2417 |
+
>>> from sympy.polys.domains import FF
|
2418 |
+
>>> F = FF(2)
|
2419 |
+
>>> fill = [F(1), F(1), F(0), F(1)]
|
2420 |
+
>>> key = [F(1), F(0), F(0), F(1)]
|
2421 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
2422 |
+
>>> lfsr_autocorrelation(s, 15, 7)
|
2423 |
+
-1/15
|
2424 |
+
>>> lfsr_autocorrelation(s, 15, 0)
|
2425 |
+
1
|
2426 |
+
|
2427 |
+
"""
|
2428 |
+
if not isinstance(L, list):
|
2429 |
+
raise TypeError("L (=%s) must be a list" % L)
|
2430 |
+
P = int(P)
|
2431 |
+
k = int(k)
|
2432 |
+
L0 = L[:P] # slices makes a copy
|
2433 |
+
L1 = L0 + L0[:k]
|
2434 |
+
L2 = [(-1)**(L1[i].to_int() + L1[i + k].to_int()) for i in range(P)]
|
2435 |
+
tot = sum(L2)
|
2436 |
+
return Rational(tot, P)
|
2437 |
+
|
2438 |
+
|
2439 |
+
def lfsr_connection_polynomial(s):
|
2440 |
+
"""
|
2441 |
+
This function computes the LFSR connection polynomial.
|
2442 |
+
|
2443 |
+
Parameters
|
2444 |
+
==========
|
2445 |
+
|
2446 |
+
s
|
2447 |
+
A sequence of elements of even length, with entries in a finite
|
2448 |
+
field.
|
2449 |
+
|
2450 |
+
Returns
|
2451 |
+
=======
|
2452 |
+
|
2453 |
+
C(x)
|
2454 |
+
The connection polynomial of a minimal LFSR yielding s.
|
2455 |
+
|
2456 |
+
This implements the algorithm in section 3 of J. L. Massey's
|
2457 |
+
article [M]_.
|
2458 |
+
|
2459 |
+
Examples
|
2460 |
+
========
|
2461 |
+
|
2462 |
+
>>> from sympy.crypto.crypto import (
|
2463 |
+
... lfsr_sequence, lfsr_connection_polynomial)
|
2464 |
+
>>> from sympy.polys.domains import FF
|
2465 |
+
>>> F = FF(2)
|
2466 |
+
>>> fill = [F(1), F(1), F(0), F(1)]
|
2467 |
+
>>> key = [F(1), F(0), F(0), F(1)]
|
2468 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
2469 |
+
>>> lfsr_connection_polynomial(s)
|
2470 |
+
x**4 + x + 1
|
2471 |
+
>>> fill = [F(1), F(0), F(0), F(1)]
|
2472 |
+
>>> key = [F(1), F(1), F(0), F(1)]
|
2473 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
2474 |
+
>>> lfsr_connection_polynomial(s)
|
2475 |
+
x**3 + 1
|
2476 |
+
>>> fill = [F(1), F(0), F(1)]
|
2477 |
+
>>> key = [F(1), F(1), F(0)]
|
2478 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
2479 |
+
>>> lfsr_connection_polynomial(s)
|
2480 |
+
x**3 + x**2 + 1
|
2481 |
+
>>> fill = [F(1), F(0), F(1)]
|
2482 |
+
>>> key = [F(1), F(0), F(1)]
|
2483 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
2484 |
+
>>> lfsr_connection_polynomial(s)
|
2485 |
+
x**3 + x + 1
|
2486 |
+
|
2487 |
+
References
|
2488 |
+
==========
|
2489 |
+
|
2490 |
+
.. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding."
|
2491 |
+
IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127,
|
2492 |
+
Jan 1969.
|
2493 |
+
|
2494 |
+
"""
|
2495 |
+
# Initialization:
|
2496 |
+
p = s[0].mod
|
2497 |
+
x = Symbol("x")
|
2498 |
+
C = 1*x**0
|
2499 |
+
B = 1*x**0
|
2500 |
+
m = 1
|
2501 |
+
b = 1*x**0
|
2502 |
+
L = 0
|
2503 |
+
N = 0
|
2504 |
+
while N < len(s):
|
2505 |
+
if L > 0:
|
2506 |
+
dC = Poly(C).degree()
|
2507 |
+
r = min(L + 1, dC + 1)
|
2508 |
+
coeffsC = [C.subs(x, 0)] + [C.coeff(x**i)
|
2509 |
+
for i in range(1, dC + 1)]
|
2510 |
+
d = (s[N].to_int() + sum([coeffsC[i]*s[N - i].to_int()
|
2511 |
+
for i in range(1, r)])) % p
|
2512 |
+
if L == 0:
|
2513 |
+
d = s[N].to_int()*x**0
|
2514 |
+
if d == 0:
|
2515 |
+
m += 1
|
2516 |
+
N += 1
|
2517 |
+
if d > 0:
|
2518 |
+
if 2*L > N:
|
2519 |
+
C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
|
2520 |
+
m += 1
|
2521 |
+
N += 1
|
2522 |
+
else:
|
2523 |
+
T = C
|
2524 |
+
C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
|
2525 |
+
L = N + 1 - L
|
2526 |
+
m = 1
|
2527 |
+
b = d
|
2528 |
+
B = T
|
2529 |
+
N += 1
|
2530 |
+
dC = Poly(C).degree()
|
2531 |
+
coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)]
|
2532 |
+
return sum([coeffsC[i] % p*x**i for i in range(dC + 1)
|
2533 |
+
if coeffsC[i] is not None])
|
2534 |
+
|
2535 |
+
|
2536 |
+
#################### ElGamal #############################
|
2537 |
+
|
2538 |
+
|
2539 |
+
def elgamal_private_key(digit=10, seed=None):
|
2540 |
+
r"""
|
2541 |
+
Return three number tuple as private key.
|
2542 |
+
|
2543 |
+
Explanation
|
2544 |
+
===========
|
2545 |
+
|
2546 |
+
Elgamal encryption is based on the mathematical problem
|
2547 |
+
called the Discrete Logarithm Problem (DLP). For example,
|
2548 |
+
|
2549 |
+
`a^{b} \equiv c \pmod p`
|
2550 |
+
|
2551 |
+
In general, if ``a`` and ``b`` are known, ``ct`` is easily
|
2552 |
+
calculated. If ``b`` is unknown, it is hard to use
|
2553 |
+
``a`` and ``ct`` to get ``b``.
|
2554 |
+
|
2555 |
+
Parameters
|
2556 |
+
==========
|
2557 |
+
|
2558 |
+
digit : int
|
2559 |
+
Minimum number of binary digits for key.
|
2560 |
+
|
2561 |
+
Returns
|
2562 |
+
=======
|
2563 |
+
|
2564 |
+
tuple : (p, r, d)
|
2565 |
+
p = prime number.
|
2566 |
+
|
2567 |
+
r = primitive root.
|
2568 |
+
|
2569 |
+
d = random number.
|
2570 |
+
|
2571 |
+
Notes
|
2572 |
+
=====
|
2573 |
+
|
2574 |
+
For testing purposes, the ``seed`` parameter may be set to control
|
2575 |
+
the output of this routine. See sympy.core.random._randrange.
|
2576 |
+
|
2577 |
+
Examples
|
2578 |
+
========
|
2579 |
+
|
2580 |
+
>>> from sympy.crypto.crypto import elgamal_private_key
|
2581 |
+
>>> from sympy.ntheory import is_primitive_root, isprime
|
2582 |
+
>>> a, b, _ = elgamal_private_key()
|
2583 |
+
>>> isprime(a)
|
2584 |
+
True
|
2585 |
+
>>> is_primitive_root(b, a)
|
2586 |
+
True
|
2587 |
+
|
2588 |
+
"""
|
2589 |
+
randrange = _randrange(seed)
|
2590 |
+
p = nextprime(2**digit)
|
2591 |
+
return p, primitive_root(p), randrange(2, p)
|
2592 |
+
|
2593 |
+
|
2594 |
+
def elgamal_public_key(key):
|
2595 |
+
r"""
|
2596 |
+
Return three number tuple as public key.
|
2597 |
+
|
2598 |
+
Parameters
|
2599 |
+
==========
|
2600 |
+
|
2601 |
+
key : (p, r, e)
|
2602 |
+
Tuple generated by ``elgamal_private_key``.
|
2603 |
+
|
2604 |
+
Returns
|
2605 |
+
=======
|
2606 |
+
|
2607 |
+
tuple : (p, r, e)
|
2608 |
+
`e = r**d \bmod p`
|
2609 |
+
|
2610 |
+
`d` is a random number in private key.
|
2611 |
+
|
2612 |
+
Examples
|
2613 |
+
========
|
2614 |
+
|
2615 |
+
>>> from sympy.crypto.crypto import elgamal_public_key
|
2616 |
+
>>> elgamal_public_key((1031, 14, 636))
|
2617 |
+
(1031, 14, 212)
|
2618 |
+
|
2619 |
+
"""
|
2620 |
+
p, r, e = key
|
2621 |
+
return p, r, pow(r, e, p)
|
2622 |
+
|
2623 |
+
|
2624 |
+
def encipher_elgamal(i, key, seed=None):
|
2625 |
+
r"""
|
2626 |
+
Encrypt message with public key.
|
2627 |
+
|
2628 |
+
Explanation
|
2629 |
+
===========
|
2630 |
+
|
2631 |
+
``i`` is a plaintext message expressed as an integer.
|
2632 |
+
``key`` is public key (p, r, e). In order to encrypt
|
2633 |
+
a message, a random number ``a`` in ``range(2, p)``
|
2634 |
+
is generated and the encryped message is returned as
|
2635 |
+
`c_{1}` and `c_{2}` where:
|
2636 |
+
|
2637 |
+
`c_{1} \equiv r^{a} \pmod p`
|
2638 |
+
|
2639 |
+
`c_{2} \equiv m e^{a} \pmod p`
|
2640 |
+
|
2641 |
+
Parameters
|
2642 |
+
==========
|
2643 |
+
|
2644 |
+
msg
|
2645 |
+
int of encoded message.
|
2646 |
+
|
2647 |
+
key
|
2648 |
+
Public key.
|
2649 |
+
|
2650 |
+
Returns
|
2651 |
+
=======
|
2652 |
+
|
2653 |
+
tuple : (c1, c2)
|
2654 |
+
Encipher into two number.
|
2655 |
+
|
2656 |
+
Notes
|
2657 |
+
=====
|
2658 |
+
|
2659 |
+
For testing purposes, the ``seed`` parameter may be set to control
|
2660 |
+
the output of this routine. See sympy.core.random._randrange.
|
2661 |
+
|
2662 |
+
Examples
|
2663 |
+
========
|
2664 |
+
|
2665 |
+
>>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key
|
2666 |
+
>>> pri = elgamal_private_key(5, seed=[3]); pri
|
2667 |
+
(37, 2, 3)
|
2668 |
+
>>> pub = elgamal_public_key(pri); pub
|
2669 |
+
(37, 2, 8)
|
2670 |
+
>>> msg = 36
|
2671 |
+
>>> encipher_elgamal(msg, pub, seed=[3])
|
2672 |
+
(8, 6)
|
2673 |
+
|
2674 |
+
"""
|
2675 |
+
p, r, e = key
|
2676 |
+
if i < 0 or i >= p:
|
2677 |
+
raise ValueError(
|
2678 |
+
'Message (%s) should be in range(%s)' % (i, p))
|
2679 |
+
randrange = _randrange(seed)
|
2680 |
+
a = randrange(2, p)
|
2681 |
+
return pow(r, a, p), i*pow(e, a, p) % p
|
2682 |
+
|
2683 |
+
|
2684 |
+
def decipher_elgamal(msg, key):
|
2685 |
+
r"""
|
2686 |
+
Decrypt message with private key.
|
2687 |
+
|
2688 |
+
`msg = (c_{1}, c_{2})`
|
2689 |
+
|
2690 |
+
`key = (p, r, d)`
|
2691 |
+
|
2692 |
+
According to extended Eucliden theorem,
|
2693 |
+
`u c_{1}^{d} + p n = 1`
|
2694 |
+
|
2695 |
+
`u \equiv 1/{{c_{1}}^d} \pmod p`
|
2696 |
+
|
2697 |
+
`u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p`
|
2698 |
+
|
2699 |
+
`\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p`
|
2700 |
+
|
2701 |
+
Examples
|
2702 |
+
========
|
2703 |
+
|
2704 |
+
>>> from sympy.crypto.crypto import decipher_elgamal
|
2705 |
+
>>> from sympy.crypto.crypto import encipher_elgamal
|
2706 |
+
>>> from sympy.crypto.crypto import elgamal_private_key
|
2707 |
+
>>> from sympy.crypto.crypto import elgamal_public_key
|
2708 |
+
|
2709 |
+
>>> pri = elgamal_private_key(5, seed=[3])
|
2710 |
+
>>> pub = elgamal_public_key(pri); pub
|
2711 |
+
(37, 2, 8)
|
2712 |
+
>>> msg = 17
|
2713 |
+
>>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg
|
2714 |
+
True
|
2715 |
+
|
2716 |
+
"""
|
2717 |
+
p, _, d = key
|
2718 |
+
c1, c2 = msg
|
2719 |
+
u = igcdex(c1**d, p)[0]
|
2720 |
+
return u * c2 % p
|
2721 |
+
|
2722 |
+
|
2723 |
+
################ Diffie-Hellman Key Exchange #########################
|
2724 |
+
|
2725 |
+
def dh_private_key(digit=10, seed=None):
|
2726 |
+
r"""
|
2727 |
+
Return three integer tuple as private key.
|
2728 |
+
|
2729 |
+
Explanation
|
2730 |
+
===========
|
2731 |
+
|
2732 |
+
Diffie-Hellman key exchange is based on the mathematical problem
|
2733 |
+
called the Discrete Logarithm Problem (see ElGamal).
|
2734 |
+
|
2735 |
+
Diffie-Hellman key exchange is divided into the following steps:
|
2736 |
+
|
2737 |
+
* Alice and Bob agree on a base that consist of a prime ``p``
|
2738 |
+
and a primitive root of ``p`` called ``g``
|
2739 |
+
* Alice choses a number ``a`` and Bob choses a number ``b`` where
|
2740 |
+
``a`` and ``b`` are random numbers in range `[2, p)`. These are
|
2741 |
+
their private keys.
|
2742 |
+
* Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends
|
2743 |
+
Alice `g^{b} \pmod p`
|
2744 |
+
* They both raise the received value to their secretly chosen
|
2745 |
+
number (``a`` or ``b``) and now have both as their shared key
|
2746 |
+
`g^{ab} \pmod p`
|
2747 |
+
|
2748 |
+
Parameters
|
2749 |
+
==========
|
2750 |
+
|
2751 |
+
digit
|
2752 |
+
Minimum number of binary digits required in key.
|
2753 |
+
|
2754 |
+
Returns
|
2755 |
+
=======
|
2756 |
+
|
2757 |
+
tuple : (p, g, a)
|
2758 |
+
p = prime number.
|
2759 |
+
|
2760 |
+
g = primitive root of p.
|
2761 |
+
|
2762 |
+
a = random number from 2 through p - 1.
|
2763 |
+
|
2764 |
+
Notes
|
2765 |
+
=====
|
2766 |
+
|
2767 |
+
For testing purposes, the ``seed`` parameter may be set to control
|
2768 |
+
the output of this routine. See sympy.core.random._randrange.
|
2769 |
+
|
2770 |
+
Examples
|
2771 |
+
========
|
2772 |
+
|
2773 |
+
>>> from sympy.crypto.crypto import dh_private_key
|
2774 |
+
>>> from sympy.ntheory import isprime, is_primitive_root
|
2775 |
+
>>> p, g, _ = dh_private_key()
|
2776 |
+
>>> isprime(p)
|
2777 |
+
True
|
2778 |
+
>>> is_primitive_root(g, p)
|
2779 |
+
True
|
2780 |
+
>>> p, g, _ = dh_private_key(5)
|
2781 |
+
>>> isprime(p)
|
2782 |
+
True
|
2783 |
+
>>> is_primitive_root(g, p)
|
2784 |
+
True
|
2785 |
+
|
2786 |
+
"""
|
2787 |
+
p = nextprime(2**digit)
|
2788 |
+
g = primitive_root(p)
|
2789 |
+
randrange = _randrange(seed)
|
2790 |
+
a = randrange(2, p)
|
2791 |
+
return p, g, a
|
2792 |
+
|
2793 |
+
|
2794 |
+
def dh_public_key(key):
|
2795 |
+
r"""
|
2796 |
+
Return three number tuple as public key.
|
2797 |
+
|
2798 |
+
This is the tuple that Alice sends to Bob.
|
2799 |
+
|
2800 |
+
Parameters
|
2801 |
+
==========
|
2802 |
+
|
2803 |
+
key : (p, g, a)
|
2804 |
+
A tuple generated by ``dh_private_key``.
|
2805 |
+
|
2806 |
+
Returns
|
2807 |
+
=======
|
2808 |
+
|
2809 |
+
tuple : int, int, int
|
2810 |
+
A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as
|
2811 |
+
parameters.s
|
2812 |
+
|
2813 |
+
Examples
|
2814 |
+
========
|
2815 |
+
|
2816 |
+
>>> from sympy.crypto.crypto import dh_private_key, dh_public_key
|
2817 |
+
>>> p, g, a = dh_private_key();
|
2818 |
+
>>> _p, _g, x = dh_public_key((p, g, a))
|
2819 |
+
>>> p == _p and g == _g
|
2820 |
+
True
|
2821 |
+
>>> x == pow(g, a, p)
|
2822 |
+
True
|
2823 |
+
|
2824 |
+
"""
|
2825 |
+
p, g, a = key
|
2826 |
+
return p, g, pow(g, a, p)
|
2827 |
+
|
2828 |
+
|
2829 |
+
def dh_shared_key(key, b):
|
2830 |
+
"""
|
2831 |
+
Return an integer that is the shared key.
|
2832 |
+
|
2833 |
+
This is what Bob and Alice can both calculate using the public
|
2834 |
+
keys they received from each other and their private keys.
|
2835 |
+
|
2836 |
+
Parameters
|
2837 |
+
==========
|
2838 |
+
|
2839 |
+
key : (p, g, x)
|
2840 |
+
Tuple `(p, g, x)` generated by ``dh_public_key``.
|
2841 |
+
|
2842 |
+
b
|
2843 |
+
Random number in the range of `2` to `p - 1`
|
2844 |
+
(Chosen by second key exchange member (Bob)).
|
2845 |
+
|
2846 |
+
Returns
|
2847 |
+
=======
|
2848 |
+
|
2849 |
+
int
|
2850 |
+
A shared key.
|
2851 |
+
|
2852 |
+
Examples
|
2853 |
+
========
|
2854 |
+
|
2855 |
+
>>> from sympy.crypto.crypto import (
|
2856 |
+
... dh_private_key, dh_public_key, dh_shared_key)
|
2857 |
+
>>> prk = dh_private_key();
|
2858 |
+
>>> p, g, x = dh_public_key(prk);
|
2859 |
+
>>> sk = dh_shared_key((p, g, x), 1000)
|
2860 |
+
>>> sk == pow(x, 1000, p)
|
2861 |
+
True
|
2862 |
+
|
2863 |
+
"""
|
2864 |
+
p, _, x = key
|
2865 |
+
if 1 >= b or b >= p:
|
2866 |
+
raise ValueError(filldedent('''
|
2867 |
+
Value of b should be greater 1 and less
|
2868 |
+
than prime %s.''' % p))
|
2869 |
+
|
2870 |
+
return pow(x, b, p)
|
2871 |
+
|
2872 |
+
|
2873 |
+
################ Goldwasser-Micali Encryption #########################
|
2874 |
+
|
2875 |
+
|
2876 |
+
def _legendre(a, p):
|
2877 |
+
"""
|
2878 |
+
Returns the legendre symbol of a and p
|
2879 |
+
assuming that p is a prime.
|
2880 |
+
|
2881 |
+
i.e. 1 if a is a quadratic residue mod p
|
2882 |
+
-1 if a is not a quadratic residue mod p
|
2883 |
+
0 if a is divisible by p
|
2884 |
+
|
2885 |
+
Parameters
|
2886 |
+
==========
|
2887 |
+
|
2888 |
+
a : int
|
2889 |
+
The number to test.
|
2890 |
+
|
2891 |
+
p : prime
|
2892 |
+
The prime to test ``a`` against.
|
2893 |
+
|
2894 |
+
Returns
|
2895 |
+
=======
|
2896 |
+
|
2897 |
+
int
|
2898 |
+
Legendre symbol (a / p).
|
2899 |
+
|
2900 |
+
"""
|
2901 |
+
sig = pow(a, (p - 1)//2, p)
|
2902 |
+
if sig == 1:
|
2903 |
+
return 1
|
2904 |
+
elif sig == 0:
|
2905 |
+
return 0
|
2906 |
+
else:
|
2907 |
+
return -1
|
2908 |
+
|
2909 |
+
|
2910 |
+
def _random_coprime_stream(n, seed=None):
|
2911 |
+
randrange = _randrange(seed)
|
2912 |
+
while True:
|
2913 |
+
y = randrange(n)
|
2914 |
+
if gcd(y, n) == 1:
|
2915 |
+
yield y
|
2916 |
+
|
2917 |
+
|
2918 |
+
def gm_private_key(p, q, a=None):
|
2919 |
+
r"""
|
2920 |
+
Check if ``p`` and ``q`` can be used as private keys for
|
2921 |
+
the Goldwasser-Micali encryption. The method works
|
2922 |
+
roughly as follows.
|
2923 |
+
|
2924 |
+
Explanation
|
2925 |
+
===========
|
2926 |
+
|
2927 |
+
#. Pick two large primes $p$ and $q$.
|
2928 |
+
#. Call their product $N$.
|
2929 |
+
#. Given a message as an integer $i$, write $i$ in its bit representation $b_0, \dots, b_n$.
|
2930 |
+
#. For each $k$,
|
2931 |
+
|
2932 |
+
if $b_k = 0$:
|
2933 |
+
let $a_k$ be a random square
|
2934 |
+
(quadratic residue) modulo $p q$
|
2935 |
+
such that ``jacobi_symbol(a, p*q) = 1``
|
2936 |
+
if $b_k = 1$:
|
2937 |
+
let $a_k$ be a random non-square
|
2938 |
+
(non-quadratic residue) modulo $p q$
|
2939 |
+
such that ``jacobi_symbol(a, p*q) = 1``
|
2940 |
+
|
2941 |
+
returns $\left[a_1, a_2, \dots\right]$
|
2942 |
+
|
2943 |
+
$b_k$ can be recovered by checking whether or not
|
2944 |
+
$a_k$ is a residue. And from the $b_k$'s, the message
|
2945 |
+
can be reconstructed.
|
2946 |
+
|
2947 |
+
The idea is that, while ``jacobi_symbol(a, p*q)``
|
2948 |
+
can be easily computed (and when it is equal to $-1$ will
|
2949 |
+
tell you that $a$ is not a square mod $p q$), quadratic
|
2950 |
+
residuosity modulo a composite number is hard to compute
|
2951 |
+
without knowing its factorization.
|
2952 |
+
|
2953 |
+
Moreover, approximately half the numbers coprime to $p q$ have
|
2954 |
+
:func:`~.jacobi_symbol` equal to $1$ . And among those, approximately half
|
2955 |
+
are residues and approximately half are not. This maximizes the
|
2956 |
+
entropy of the code.
|
2957 |
+
|
2958 |
+
Parameters
|
2959 |
+
==========
|
2960 |
+
|
2961 |
+
p, q, a
|
2962 |
+
Initialization variables.
|
2963 |
+
|
2964 |
+
Returns
|
2965 |
+
=======
|
2966 |
+
|
2967 |
+
tuple : (p, q)
|
2968 |
+
The input value ``p`` and ``q``.
|
2969 |
+
|
2970 |
+
Raises
|
2971 |
+
======
|
2972 |
+
|
2973 |
+
ValueError
|
2974 |
+
If ``p`` and ``q`` are not distinct odd primes.
|
2975 |
+
|
2976 |
+
"""
|
2977 |
+
if p == q:
|
2978 |
+
raise ValueError("expected distinct primes, "
|
2979 |
+
"got two copies of %i" % p)
|
2980 |
+
elif not isprime(p) or not isprime(q):
|
2981 |
+
raise ValueError("first two arguments must be prime, "
|
2982 |
+
"got %i of %i" % (p, q))
|
2983 |
+
elif p == 2 or q == 2:
|
2984 |
+
raise ValueError("first two arguments must not be even, "
|
2985 |
+
"got %i of %i" % (p, q))
|
2986 |
+
return p, q
|
2987 |
+
|
2988 |
+
|
2989 |
+
def gm_public_key(p, q, a=None, seed=None):
|
2990 |
+
"""
|
2991 |
+
Compute public keys for ``p`` and ``q``.
|
2992 |
+
Note that in Goldwasser-Micali Encryption,
|
2993 |
+
public keys are randomly selected.
|
2994 |
+
|
2995 |
+
Parameters
|
2996 |
+
==========
|
2997 |
+
|
2998 |
+
p, q, a : int, int, int
|
2999 |
+
Initialization variables.
|
3000 |
+
|
3001 |
+
Returns
|
3002 |
+
=======
|
3003 |
+
|
3004 |
+
tuple : (a, N)
|
3005 |
+
``a`` is the input ``a`` if it is not ``None`` otherwise
|
3006 |
+
some random integer coprime to ``p`` and ``q``.
|
3007 |
+
|
3008 |
+
``N`` is the product of ``p`` and ``q``.
|
3009 |
+
|
3010 |
+
"""
|
3011 |
+
|
3012 |
+
p, q = gm_private_key(p, q)
|
3013 |
+
N = p * q
|
3014 |
+
|
3015 |
+
if a is None:
|
3016 |
+
randrange = _randrange(seed)
|
3017 |
+
while True:
|
3018 |
+
a = randrange(N)
|
3019 |
+
if _legendre(a, p) == _legendre(a, q) == -1:
|
3020 |
+
break
|
3021 |
+
else:
|
3022 |
+
if _legendre(a, p) != -1 or _legendre(a, q) != -1:
|
3023 |
+
return False
|
3024 |
+
return (a, N)
|
3025 |
+
|
3026 |
+
|
3027 |
+
def encipher_gm(i, key, seed=None):
|
3028 |
+
"""
|
3029 |
+
Encrypt integer 'i' using public_key 'key'
|
3030 |
+
Note that gm uses random encryption.
|
3031 |
+
|
3032 |
+
Parameters
|
3033 |
+
==========
|
3034 |
+
|
3035 |
+
i : int
|
3036 |
+
The message to encrypt.
|
3037 |
+
|
3038 |
+
key : (a, N)
|
3039 |
+
The public key.
|
3040 |
+
|
3041 |
+
Returns
|
3042 |
+
=======
|
3043 |
+
|
3044 |
+
list : list of int
|
3045 |
+
The randomized encrypted message.
|
3046 |
+
|
3047 |
+
"""
|
3048 |
+
if i < 0:
|
3049 |
+
raise ValueError(
|
3050 |
+
"message must be a non-negative "
|
3051 |
+
"integer: got %d instead" % i)
|
3052 |
+
a, N = key
|
3053 |
+
bits = []
|
3054 |
+
while i > 0:
|
3055 |
+
bits.append(i % 2)
|
3056 |
+
i //= 2
|
3057 |
+
|
3058 |
+
gen = _random_coprime_stream(N, seed)
|
3059 |
+
rev = reversed(bits)
|
3060 |
+
encode = lambda b: next(gen)**2*pow(a, b) % N
|
3061 |
+
return [ encode(b) for b in rev ]
|
3062 |
+
|
3063 |
+
|
3064 |
+
|
3065 |
+
def decipher_gm(message, key):
|
3066 |
+
"""
|
3067 |
+
Decrypt message 'message' using public_key 'key'.
|
3068 |
+
|
3069 |
+
Parameters
|
3070 |
+
==========
|
3071 |
+
|
3072 |
+
message : list of int
|
3073 |
+
The randomized encrypted message.
|
3074 |
+
|
3075 |
+
key : (p, q)
|
3076 |
+
The private key.
|
3077 |
+
|
3078 |
+
Returns
|
3079 |
+
=======
|
3080 |
+
|
3081 |
+
int
|
3082 |
+
The encrypted message.
|
3083 |
+
|
3084 |
+
"""
|
3085 |
+
p, q = key
|
3086 |
+
res = lambda m, p: _legendre(m, p) > 0
|
3087 |
+
bits = [res(m, p) * res(m, q) for m in message]
|
3088 |
+
m = 0
|
3089 |
+
for b in bits:
|
3090 |
+
m <<= 1
|
3091 |
+
m += not b
|
3092 |
+
return m
|
3093 |
+
|
3094 |
+
|
3095 |
+
|
3096 |
+
########### RailFence Cipher #############
|
3097 |
+
|
3098 |
+
def encipher_railfence(message,rails):
|
3099 |
+
"""
|
3100 |
+
Performs Railfence Encryption on plaintext and returns ciphertext
|
3101 |
+
|
3102 |
+
Examples
|
3103 |
+
========
|
3104 |
+
|
3105 |
+
>>> from sympy.crypto.crypto import encipher_railfence
|
3106 |
+
>>> message = "hello world"
|
3107 |
+
>>> encipher_railfence(message,3)
|
3108 |
+
'horel ollwd'
|
3109 |
+
|
3110 |
+
Parameters
|
3111 |
+
==========
|
3112 |
+
|
3113 |
+
message : string, the message to encrypt.
|
3114 |
+
rails : int, the number of rails.
|
3115 |
+
|
3116 |
+
Returns
|
3117 |
+
=======
|
3118 |
+
|
3119 |
+
The Encrypted string message.
|
3120 |
+
|
3121 |
+
References
|
3122 |
+
==========
|
3123 |
+
.. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher
|
3124 |
+
|
3125 |
+
"""
|
3126 |
+
r = list(range(rails))
|
3127 |
+
p = cycle(r + r[-2:0:-1])
|
3128 |
+
return ''.join(sorted(message, key=lambda i: next(p)))
|
3129 |
+
|
3130 |
+
|
3131 |
+
def decipher_railfence(ciphertext,rails):
|
3132 |
+
"""
|
3133 |
+
Decrypt the message using the given rails
|
3134 |
+
|
3135 |
+
Examples
|
3136 |
+
========
|
3137 |
+
|
3138 |
+
>>> from sympy.crypto.crypto import decipher_railfence
|
3139 |
+
>>> decipher_railfence("horel ollwd",3)
|
3140 |
+
'hello world'
|
3141 |
+
|
3142 |
+
Parameters
|
3143 |
+
==========
|
3144 |
+
|
3145 |
+
message : string, the message to encrypt.
|
3146 |
+
rails : int, the number of rails.
|
3147 |
+
|
3148 |
+
Returns
|
3149 |
+
=======
|
3150 |
+
|
3151 |
+
The Decrypted string message.
|
3152 |
+
|
3153 |
+
"""
|
3154 |
+
r = list(range(rails))
|
3155 |
+
p = cycle(r + r[-2:0:-1])
|
3156 |
+
|
3157 |
+
idx = sorted(range(len(ciphertext)), key=lambda i: next(p))
|
3158 |
+
res = [''] * len(ciphertext)
|
3159 |
+
for i, c in zip(idx, ciphertext):
|
3160 |
+
res[i] = c
|
3161 |
+
return ''.join(res)
|
3162 |
+
|
3163 |
+
|
3164 |
+
################ Blum-Goldwasser cryptosystem #########################
|
3165 |
+
|
3166 |
+
def bg_private_key(p, q):
|
3167 |
+
"""
|
3168 |
+
Check if p and q can be used as private keys for
|
3169 |
+
the Blum-Goldwasser cryptosystem.
|
3170 |
+
|
3171 |
+
Explanation
|
3172 |
+
===========
|
3173 |
+
|
3174 |
+
The three necessary checks for p and q to pass
|
3175 |
+
so that they can be used as private keys:
|
3176 |
+
|
3177 |
+
1. p and q must both be prime
|
3178 |
+
2. p and q must be distinct
|
3179 |
+
3. p and q must be congruent to 3 mod 4
|
3180 |
+
|
3181 |
+
Parameters
|
3182 |
+
==========
|
3183 |
+
|
3184 |
+
p, q
|
3185 |
+
The keys to be checked.
|
3186 |
+
|
3187 |
+
Returns
|
3188 |
+
=======
|
3189 |
+
|
3190 |
+
p, q
|
3191 |
+
Input values.
|
3192 |
+
|
3193 |
+
Raises
|
3194 |
+
======
|
3195 |
+
|
3196 |
+
ValueError
|
3197 |
+
If p and q do not pass the above conditions.
|
3198 |
+
|
3199 |
+
"""
|
3200 |
+
|
3201 |
+
if not isprime(p) or not isprime(q):
|
3202 |
+
raise ValueError("the two arguments must be prime, "
|
3203 |
+
"got %i and %i" %(p, q))
|
3204 |
+
elif p == q:
|
3205 |
+
raise ValueError("the two arguments must be distinct, "
|
3206 |
+
"got two copies of %i. " %p)
|
3207 |
+
elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0:
|
3208 |
+
raise ValueError("the two arguments must be congruent to 3 mod 4, "
|
3209 |
+
"got %i and %i" %(p, q))
|
3210 |
+
return p, q
|
3211 |
+
|
3212 |
+
def bg_public_key(p, q):
|
3213 |
+
"""
|
3214 |
+
Calculates public keys from private keys.
|
3215 |
+
|
3216 |
+
Explanation
|
3217 |
+
===========
|
3218 |
+
|
3219 |
+
The function first checks the validity of
|
3220 |
+
private keys passed as arguments and
|
3221 |
+
then returns their product.
|
3222 |
+
|
3223 |
+
Parameters
|
3224 |
+
==========
|
3225 |
+
|
3226 |
+
p, q
|
3227 |
+
The private keys.
|
3228 |
+
|
3229 |
+
Returns
|
3230 |
+
=======
|
3231 |
+
|
3232 |
+
N
|
3233 |
+
The public key.
|
3234 |
+
|
3235 |
+
"""
|
3236 |
+
p, q = bg_private_key(p, q)
|
3237 |
+
N = p * q
|
3238 |
+
return N
|
3239 |
+
|
3240 |
+
def encipher_bg(i, key, seed=None):
|
3241 |
+
"""
|
3242 |
+
Encrypts the message using public key and seed.
|
3243 |
+
|
3244 |
+
Explanation
|
3245 |
+
===========
|
3246 |
+
|
3247 |
+
ALGORITHM:
|
3248 |
+
1. Encodes i as a string of L bits, m.
|
3249 |
+
2. Select a random element r, where 1 < r < key, and computes
|
3250 |
+
x = r^2 mod key.
|
3251 |
+
3. Use BBS pseudo-random number generator to generate L random bits, b,
|
3252 |
+
using the initial seed as x.
|
3253 |
+
4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L.
|
3254 |
+
5. x_L = x^(2^L) mod key.
|
3255 |
+
6. Return (c, x_L)
|
3256 |
+
|
3257 |
+
Parameters
|
3258 |
+
==========
|
3259 |
+
|
3260 |
+
i
|
3261 |
+
Message, a non-negative integer
|
3262 |
+
|
3263 |
+
key
|
3264 |
+
The public key
|
3265 |
+
|
3266 |
+
Returns
|
3267 |
+
=======
|
3268 |
+
|
3269 |
+
Tuple
|
3270 |
+
(encrypted_message, x_L)
|
3271 |
+
|
3272 |
+
Raises
|
3273 |
+
======
|
3274 |
+
|
3275 |
+
ValueError
|
3276 |
+
If i is negative.
|
3277 |
+
|
3278 |
+
"""
|
3279 |
+
|
3280 |
+
if i < 0:
|
3281 |
+
raise ValueError(
|
3282 |
+
"message must be a non-negative "
|
3283 |
+
"integer: got %d instead" % i)
|
3284 |
+
|
3285 |
+
enc_msg = []
|
3286 |
+
while i > 0:
|
3287 |
+
enc_msg.append(i % 2)
|
3288 |
+
i //= 2
|
3289 |
+
enc_msg.reverse()
|
3290 |
+
L = len(enc_msg)
|
3291 |
+
|
3292 |
+
r = _randint(seed)(2, key - 1)
|
3293 |
+
x = r**2 % key
|
3294 |
+
x_L = pow(int(x), int(2**L), int(key))
|
3295 |
+
|
3296 |
+
rand_bits = []
|
3297 |
+
for _ in range(L):
|
3298 |
+
rand_bits.append(x % 2)
|
3299 |
+
x = x**2 % key
|
3300 |
+
|
3301 |
+
encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)]
|
3302 |
+
|
3303 |
+
return (encrypt_msg, x_L)
|
3304 |
+
|
3305 |
+
def decipher_bg(message, key):
|
3306 |
+
"""
|
3307 |
+
Decrypts the message using private keys.
|
3308 |
+
|
3309 |
+
Explanation
|
3310 |
+
===========
|
3311 |
+
|
3312 |
+
ALGORITHM:
|
3313 |
+
1. Let, c be the encrypted message, y the second number received,
|
3314 |
+
and p and q be the private keys.
|
3315 |
+
2. Compute, r_p = y^((p+1)/4 ^ L) mod p and
|
3316 |
+
r_q = y^((q+1)/4 ^ L) mod q.
|
3317 |
+
3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N.
|
3318 |
+
4. From, recompute the bits using the BBS generator, as in the
|
3319 |
+
encryption algorithm.
|
3320 |
+
5. Compute original message by XORing c and b.
|
3321 |
+
|
3322 |
+
Parameters
|
3323 |
+
==========
|
3324 |
+
|
3325 |
+
message
|
3326 |
+
Tuple of encrypted message and a non-negative integer.
|
3327 |
+
|
3328 |
+
key
|
3329 |
+
Tuple of private keys.
|
3330 |
+
|
3331 |
+
Returns
|
3332 |
+
=======
|
3333 |
+
|
3334 |
+
orig_msg
|
3335 |
+
The original message
|
3336 |
+
|
3337 |
+
"""
|
3338 |
+
|
3339 |
+
p, q = key
|
3340 |
+
encrypt_msg, y = message
|
3341 |
+
public_key = p * q
|
3342 |
+
L = len(encrypt_msg)
|
3343 |
+
p_t = ((p + 1)/4)**L
|
3344 |
+
q_t = ((q + 1)/4)**L
|
3345 |
+
r_p = pow(int(y), int(p_t), int(p))
|
3346 |
+
r_q = pow(int(y), int(q_t), int(q))
|
3347 |
+
|
3348 |
+
x = (q * mod_inverse(q, p) * r_p + p * mod_inverse(p, q) * r_q) % public_key
|
3349 |
+
|
3350 |
+
orig_bits = []
|
3351 |
+
for _ in range(L):
|
3352 |
+
orig_bits.append(x % 2)
|
3353 |
+
x = x**2 % public_key
|
3354 |
+
|
3355 |
+
orig_msg = 0
|
3356 |
+
for (m, b) in zip(encrypt_msg, orig_bits):
|
3357 |
+
orig_msg = orig_msg * 2
|
3358 |
+
orig_msg += (m ^ b)
|
3359 |
+
|
3360 |
+
return orig_msg
|
env-llmeval/lib/python3.10/site-packages/sympy/crypto/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (183 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/test_crypto.cpython-310.pyc
ADDED
Binary file (21 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py
ADDED
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import symbols
|
2 |
+
from sympy.crypto.crypto import (cycle_list,
|
3 |
+
encipher_shift, encipher_affine, encipher_substitution,
|
4 |
+
check_and_join, encipher_vigenere, decipher_vigenere,
|
5 |
+
encipher_hill, decipher_hill, encipher_bifid5, encipher_bifid6,
|
6 |
+
bifid5_square, bifid6_square, bifid5, bifid6,
|
7 |
+
decipher_bifid5, decipher_bifid6, encipher_kid_rsa,
|
8 |
+
decipher_kid_rsa, kid_rsa_private_key, kid_rsa_public_key,
|
9 |
+
decipher_rsa, rsa_private_key, rsa_public_key, encipher_rsa,
|
10 |
+
lfsr_connection_polynomial, lfsr_autocorrelation, lfsr_sequence,
|
11 |
+
encode_morse, decode_morse, elgamal_private_key, elgamal_public_key,
|
12 |
+
encipher_elgamal, decipher_elgamal, dh_private_key, dh_public_key,
|
13 |
+
dh_shared_key, decipher_shift, decipher_affine, encipher_bifid,
|
14 |
+
decipher_bifid, bifid_square, padded_key, uniq, decipher_gm,
|
15 |
+
encipher_gm, gm_public_key, gm_private_key, encipher_bg, decipher_bg,
|
16 |
+
bg_private_key, bg_public_key, encipher_rot13, decipher_rot13,
|
17 |
+
encipher_atbash, decipher_atbash, NonInvertibleCipherWarning,
|
18 |
+
encipher_railfence, decipher_railfence)
|
19 |
+
from sympy.matrices import Matrix
|
20 |
+
from sympy.ntheory import isprime, is_primitive_root
|
21 |
+
from sympy.polys.domains import FF
|
22 |
+
|
23 |
+
from sympy.testing.pytest import raises, warns
|
24 |
+
|
25 |
+
from sympy.core.random import randrange
|
26 |
+
|
27 |
+
def test_encipher_railfence():
|
28 |
+
assert encipher_railfence("hello world",2) == "hlowrdel ol"
|
29 |
+
assert encipher_railfence("hello world",3) == "horel ollwd"
|
30 |
+
assert encipher_railfence("hello world",4) == "hwe olordll"
|
31 |
+
|
32 |
+
def test_decipher_railfence():
|
33 |
+
assert decipher_railfence("hlowrdel ol",2) == "hello world"
|
34 |
+
assert decipher_railfence("horel ollwd",3) == "hello world"
|
35 |
+
assert decipher_railfence("hwe olordll",4) == "hello world"
|
36 |
+
|
37 |
+
|
38 |
+
def test_cycle_list():
|
39 |
+
assert cycle_list(3, 4) == [3, 0, 1, 2]
|
40 |
+
assert cycle_list(-1, 4) == [3, 0, 1, 2]
|
41 |
+
assert cycle_list(1, 4) == [1, 2, 3, 0]
|
42 |
+
|
43 |
+
|
44 |
+
def test_encipher_shift():
|
45 |
+
assert encipher_shift("ABC", 0) == "ABC"
|
46 |
+
assert encipher_shift("ABC", 1) == "BCD"
|
47 |
+
assert encipher_shift("ABC", -1) == "ZAB"
|
48 |
+
assert decipher_shift("ZAB", -1) == "ABC"
|
49 |
+
|
50 |
+
def test_encipher_rot13():
|
51 |
+
assert encipher_rot13("ABC") == "NOP"
|
52 |
+
assert encipher_rot13("NOP") == "ABC"
|
53 |
+
assert decipher_rot13("ABC") == "NOP"
|
54 |
+
assert decipher_rot13("NOP") == "ABC"
|
55 |
+
|
56 |
+
|
57 |
+
def test_encipher_affine():
|
58 |
+
assert encipher_affine("ABC", (1, 0)) == "ABC"
|
59 |
+
assert encipher_affine("ABC", (1, 1)) == "BCD"
|
60 |
+
assert encipher_affine("ABC", (-1, 0)) == "AZY"
|
61 |
+
assert encipher_affine("ABC", (-1, 1), symbols="ABCD") == "BAD"
|
62 |
+
assert encipher_affine("123", (-1, 1), symbols="1234") == "214"
|
63 |
+
assert encipher_affine("ABC", (3, 16)) == "QTW"
|
64 |
+
assert decipher_affine("QTW", (3, 16)) == "ABC"
|
65 |
+
|
66 |
+
def test_encipher_atbash():
|
67 |
+
assert encipher_atbash("ABC") == "ZYX"
|
68 |
+
assert encipher_atbash("ZYX") == "ABC"
|
69 |
+
assert decipher_atbash("ABC") == "ZYX"
|
70 |
+
assert decipher_atbash("ZYX") == "ABC"
|
71 |
+
|
72 |
+
def test_encipher_substitution():
|
73 |
+
assert encipher_substitution("ABC", "BAC", "ABC") == "BAC"
|
74 |
+
assert encipher_substitution("123", "1243", "1234") == "124"
|
75 |
+
|
76 |
+
|
77 |
+
def test_check_and_join():
|
78 |
+
assert check_and_join("abc") == "abc"
|
79 |
+
assert check_and_join(uniq("aaabc")) == "abc"
|
80 |
+
assert check_and_join("ab c".split()) == "abc"
|
81 |
+
assert check_and_join("abc", "a", filter=True) == "a"
|
82 |
+
raises(ValueError, lambda: check_and_join('ab', 'a'))
|
83 |
+
|
84 |
+
|
85 |
+
def test_encipher_vigenere():
|
86 |
+
assert encipher_vigenere("ABC", "ABC") == "ACE"
|
87 |
+
assert encipher_vigenere("ABC", "ABC", symbols="ABCD") == "ACA"
|
88 |
+
assert encipher_vigenere("ABC", "AB", symbols="ABCD") == "ACC"
|
89 |
+
assert encipher_vigenere("AB", "ABC", symbols="ABCD") == "AC"
|
90 |
+
assert encipher_vigenere("A", "ABC", symbols="ABCD") == "A"
|
91 |
+
|
92 |
+
|
93 |
+
def test_decipher_vigenere():
|
94 |
+
assert decipher_vigenere("ABC", "ABC") == "AAA"
|
95 |
+
assert decipher_vigenere("ABC", "ABC", symbols="ABCD") == "AAA"
|
96 |
+
assert decipher_vigenere("ABC", "AB", symbols="ABCD") == "AAC"
|
97 |
+
assert decipher_vigenere("AB", "ABC", symbols="ABCD") == "AA"
|
98 |
+
assert decipher_vigenere("A", "ABC", symbols="ABCD") == "A"
|
99 |
+
|
100 |
+
|
101 |
+
def test_encipher_hill():
|
102 |
+
A = Matrix(2, 2, [1, 2, 3, 5])
|
103 |
+
assert encipher_hill("ABCD", A) == "CFIV"
|
104 |
+
A = Matrix(2, 2, [1, 0, 0, 1])
|
105 |
+
assert encipher_hill("ABCD", A) == "ABCD"
|
106 |
+
assert encipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
|
107 |
+
A = Matrix(2, 2, [1, 2, 3, 5])
|
108 |
+
assert encipher_hill("ABCD", A, symbols="ABCD") == "CBAB"
|
109 |
+
assert encipher_hill("AB", A, symbols="ABCD") == "CB"
|
110 |
+
# message length, n, does not need to be a multiple of k;
|
111 |
+
# it is padded
|
112 |
+
assert encipher_hill("ABA", A) == "CFGC"
|
113 |
+
assert encipher_hill("ABA", A, pad="Z") == "CFYV"
|
114 |
+
|
115 |
+
|
116 |
+
def test_decipher_hill():
|
117 |
+
A = Matrix(2, 2, [1, 2, 3, 5])
|
118 |
+
assert decipher_hill("CFIV", A) == "ABCD"
|
119 |
+
A = Matrix(2, 2, [1, 0, 0, 1])
|
120 |
+
assert decipher_hill("ABCD", A) == "ABCD"
|
121 |
+
assert decipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
|
122 |
+
A = Matrix(2, 2, [1, 2, 3, 5])
|
123 |
+
assert decipher_hill("CBAB", A, symbols="ABCD") == "ABCD"
|
124 |
+
assert decipher_hill("CB", A, symbols="ABCD") == "AB"
|
125 |
+
# n does not need to be a multiple of k
|
126 |
+
assert decipher_hill("CFA", A) == "ABAA"
|
127 |
+
|
128 |
+
|
129 |
+
def test_encipher_bifid5():
|
130 |
+
assert encipher_bifid5("AB", "AB") == "AB"
|
131 |
+
assert encipher_bifid5("AB", "CD") == "CO"
|
132 |
+
assert encipher_bifid5("ab", "c") == "CH"
|
133 |
+
assert encipher_bifid5("a bc", "b") == "BAC"
|
134 |
+
|
135 |
+
|
136 |
+
def test_bifid5_square():
|
137 |
+
A = bifid5
|
138 |
+
f = lambda i, j: symbols(A[5*i + j])
|
139 |
+
M = Matrix(5, 5, f)
|
140 |
+
assert bifid5_square("") == M
|
141 |
+
|
142 |
+
|
143 |
+
def test_decipher_bifid5():
|
144 |
+
assert decipher_bifid5("AB", "AB") == "AB"
|
145 |
+
assert decipher_bifid5("CO", "CD") == "AB"
|
146 |
+
assert decipher_bifid5("ch", "c") == "AB"
|
147 |
+
assert decipher_bifid5("b ac", "b") == "ABC"
|
148 |
+
|
149 |
+
|
150 |
+
def test_encipher_bifid6():
|
151 |
+
assert encipher_bifid6("AB", "AB") == "AB"
|
152 |
+
assert encipher_bifid6("AB", "CD") == "CP"
|
153 |
+
assert encipher_bifid6("ab", "c") == "CI"
|
154 |
+
assert encipher_bifid6("a bc", "b") == "BAC"
|
155 |
+
|
156 |
+
|
157 |
+
def test_decipher_bifid6():
|
158 |
+
assert decipher_bifid6("AB", "AB") == "AB"
|
159 |
+
assert decipher_bifid6("CP", "CD") == "AB"
|
160 |
+
assert decipher_bifid6("ci", "c") == "AB"
|
161 |
+
assert decipher_bifid6("b ac", "b") == "ABC"
|
162 |
+
|
163 |
+
|
164 |
+
def test_bifid6_square():
|
165 |
+
A = bifid6
|
166 |
+
f = lambda i, j: symbols(A[6*i + j])
|
167 |
+
M = Matrix(6, 6, f)
|
168 |
+
assert bifid6_square("") == M
|
169 |
+
|
170 |
+
|
171 |
+
def test_rsa_public_key():
|
172 |
+
assert rsa_public_key(2, 3, 1) == (6, 1)
|
173 |
+
assert rsa_public_key(5, 3, 3) == (15, 3)
|
174 |
+
|
175 |
+
with warns(NonInvertibleCipherWarning):
|
176 |
+
assert rsa_public_key(2, 2, 1) == (4, 1)
|
177 |
+
assert rsa_public_key(8, 8, 8) is False
|
178 |
+
|
179 |
+
|
180 |
+
def test_rsa_private_key():
|
181 |
+
assert rsa_private_key(2, 3, 1) == (6, 1)
|
182 |
+
assert rsa_private_key(5, 3, 3) == (15, 3)
|
183 |
+
assert rsa_private_key(23,29,5) == (667,493)
|
184 |
+
|
185 |
+
with warns(NonInvertibleCipherWarning):
|
186 |
+
assert rsa_private_key(2, 2, 1) == (4, 1)
|
187 |
+
assert rsa_private_key(8, 8, 8) is False
|
188 |
+
|
189 |
+
|
190 |
+
def test_rsa_large_key():
|
191 |
+
# Sample from
|
192 |
+
# http://www.herongyang.com/Cryptography/JCE-Public-Key-RSA-Private-Public-Key-Pair-Sample.html
|
193 |
+
p = int('101565610013301240713207239558950144682174355406589305284428666'\
|
194 |
+
'903702505233009')
|
195 |
+
q = int('894687191887545488935455605955948413812376003053143521429242133'\
|
196 |
+
'12069293984003')
|
197 |
+
e = int('65537')
|
198 |
+
d = int('893650581832704239530398858744759129594796235440844479456143566'\
|
199 |
+
'6999402846577625762582824202269399672579058991442587406384754958587'\
|
200 |
+
'400493169361356902030209')
|
201 |
+
assert rsa_public_key(p, q, e) == (p*q, e)
|
202 |
+
assert rsa_private_key(p, q, e) == (p*q, d)
|
203 |
+
|
204 |
+
|
205 |
+
def test_encipher_rsa():
|
206 |
+
puk = rsa_public_key(2, 3, 1)
|
207 |
+
assert encipher_rsa(2, puk) == 2
|
208 |
+
puk = rsa_public_key(5, 3, 3)
|
209 |
+
assert encipher_rsa(2, puk) == 8
|
210 |
+
|
211 |
+
with warns(NonInvertibleCipherWarning):
|
212 |
+
puk = rsa_public_key(2, 2, 1)
|
213 |
+
assert encipher_rsa(2, puk) == 2
|
214 |
+
|
215 |
+
|
216 |
+
def test_decipher_rsa():
|
217 |
+
prk = rsa_private_key(2, 3, 1)
|
218 |
+
assert decipher_rsa(2, prk) == 2
|
219 |
+
prk = rsa_private_key(5, 3, 3)
|
220 |
+
assert decipher_rsa(8, prk) == 2
|
221 |
+
|
222 |
+
with warns(NonInvertibleCipherWarning):
|
223 |
+
prk = rsa_private_key(2, 2, 1)
|
224 |
+
assert decipher_rsa(2, prk) == 2
|
225 |
+
|
226 |
+
|
227 |
+
def test_mutltiprime_rsa_full_example():
|
228 |
+
# Test example from
|
229 |
+
# https://iopscience.iop.org/article/10.1088/1742-6596/995/1/012030
|
230 |
+
puk = rsa_public_key(2, 3, 5, 7, 11, 13, 7)
|
231 |
+
prk = rsa_private_key(2, 3, 5, 7, 11, 13, 7)
|
232 |
+
assert puk == (30030, 7)
|
233 |
+
assert prk == (30030, 823)
|
234 |
+
|
235 |
+
msg = 10
|
236 |
+
encrypted = encipher_rsa(2 * msg - 15, puk)
|
237 |
+
assert encrypted == 18065
|
238 |
+
decrypted = (decipher_rsa(encrypted, prk) + 15) / 2
|
239 |
+
assert decrypted == msg
|
240 |
+
|
241 |
+
# Test example from
|
242 |
+
# https://www.scirp.org/pdf/JCC_2018032215502008.pdf
|
243 |
+
puk1 = rsa_public_key(53, 41, 43, 47, 41)
|
244 |
+
prk1 = rsa_private_key(53, 41, 43, 47, 41)
|
245 |
+
puk2 = rsa_public_key(53, 41, 43, 47, 97)
|
246 |
+
prk2 = rsa_private_key(53, 41, 43, 47, 97)
|
247 |
+
|
248 |
+
assert puk1 == (4391633, 41)
|
249 |
+
assert prk1 == (4391633, 294041)
|
250 |
+
assert puk2 == (4391633, 97)
|
251 |
+
assert prk2 == (4391633, 455713)
|
252 |
+
|
253 |
+
msg = 12321
|
254 |
+
encrypted = encipher_rsa(encipher_rsa(msg, puk1), puk2)
|
255 |
+
assert encrypted == 1081588
|
256 |
+
decrypted = decipher_rsa(decipher_rsa(encrypted, prk2), prk1)
|
257 |
+
assert decrypted == msg
|
258 |
+
|
259 |
+
|
260 |
+
def test_rsa_crt_extreme():
|
261 |
+
p = int(
|
262 |
+
'10177157607154245068023861503693082120906487143725062283406501' \
|
263 |
+
'54082258226204046999838297167140821364638180697194879500245557' \
|
264 |
+
'65445186962893346463841419427008800341257468600224049986260471' \
|
265 |
+
'92257248163014468841725476918639415726709736077813632961290911' \
|
266 |
+
'0256421232977833028677441206049309220354796014376698325101693')
|
267 |
+
|
268 |
+
q = int(
|
269 |
+
'28752342353095132872290181526607275886182793241660805077850801' \
|
270 |
+
'75689512797754286972952273553128181861830576836289738668745250' \
|
271 |
+
'34028199691128870676414118458442900035778874482624765513861643' \
|
272 |
+
'27966696316822188398336199002306588703902894100476186823849595' \
|
273 |
+
'103239410527279605442148285816149368667083114802852804976893')
|
274 |
+
|
275 |
+
r = int(
|
276 |
+
'17698229259868825776879500736350186838850961935956310134378261' \
|
277 |
+
'89771862186717463067541369694816245225291921138038800171125596' \
|
278 |
+
'07315449521981157084370187887650624061033066022458512942411841' \
|
279 |
+
'18747893789972315277160085086164119879536041875335384844820566' \
|
280 |
+
'0287479617671726408053319619892052000850883994343378882717849')
|
281 |
+
|
282 |
+
s = int(
|
283 |
+
'68925428438585431029269182233502611027091755064643742383515623' \
|
284 |
+
'64321310582896893395529367074942808353187138794422745718419645' \
|
285 |
+
'28291231865157212604266903677599180789896916456120289112752835' \
|
286 |
+
'98502265889669730331688206825220074713977607415178738015831030' \
|
287 |
+
'364290585369150502819743827343552098197095520550865360159439'
|
288 |
+
)
|
289 |
+
|
290 |
+
t = int(
|
291 |
+
'69035483433453632820551311892368908779778144568711455301541094' \
|
292 |
+
'31487047642322695357696860925747923189635033183069823820910521' \
|
293 |
+
'71172909106797748883261493224162414050106920442445896819806600' \
|
294 |
+
'15448444826108008217972129130625571421904893252804729877353352' \
|
295 |
+
'739420480574842850202181462656251626522910618936534699566291'
|
296 |
+
)
|
297 |
+
|
298 |
+
e = 65537
|
299 |
+
puk = rsa_public_key(p, q, r, s, t, e)
|
300 |
+
prk = rsa_private_key(p, q, r, s, t, e)
|
301 |
+
|
302 |
+
plaintext = 1000
|
303 |
+
ciphertext_1 = encipher_rsa(plaintext, puk)
|
304 |
+
ciphertext_2 = encipher_rsa(plaintext, puk, [p, q, r, s, t])
|
305 |
+
assert ciphertext_1 == ciphertext_2
|
306 |
+
assert decipher_rsa(ciphertext_1, prk) == \
|
307 |
+
decipher_rsa(ciphertext_1, prk, [p, q, r, s, t])
|
308 |
+
|
309 |
+
|
310 |
+
def test_rsa_exhaustive():
|
311 |
+
p, q = 61, 53
|
312 |
+
e = 17
|
313 |
+
puk = rsa_public_key(p, q, e, totient='Carmichael')
|
314 |
+
prk = rsa_private_key(p, q, e, totient='Carmichael')
|
315 |
+
|
316 |
+
for msg in range(puk[0]):
|
317 |
+
encrypted = encipher_rsa(msg, puk)
|
318 |
+
decrypted = decipher_rsa(encrypted, prk)
|
319 |
+
try:
|
320 |
+
assert decrypted == msg
|
321 |
+
except AssertionError:
|
322 |
+
raise AssertionError(
|
323 |
+
"The RSA is not correctly decrypted " \
|
324 |
+
"(Original : {}, Encrypted : {}, Decrypted : {})" \
|
325 |
+
.format(msg, encrypted, decrypted)
|
326 |
+
)
|
327 |
+
|
328 |
+
|
329 |
+
def test_rsa_multiprime_exhanstive():
|
330 |
+
primes = [3, 5, 7, 11]
|
331 |
+
e = 7
|
332 |
+
args = primes + [e]
|
333 |
+
puk = rsa_public_key(*args, totient='Carmichael')
|
334 |
+
prk = rsa_private_key(*args, totient='Carmichael')
|
335 |
+
n = puk[0]
|
336 |
+
|
337 |
+
for msg in range(n):
|
338 |
+
encrypted = encipher_rsa(msg, puk)
|
339 |
+
decrypted = decipher_rsa(encrypted, prk)
|
340 |
+
try:
|
341 |
+
assert decrypted == msg
|
342 |
+
except AssertionError:
|
343 |
+
raise AssertionError(
|
344 |
+
"The RSA is not correctly decrypted " \
|
345 |
+
"(Original : {}, Encrypted : {}, Decrypted : {})" \
|
346 |
+
.format(msg, encrypted, decrypted)
|
347 |
+
)
|
348 |
+
|
349 |
+
|
350 |
+
def test_rsa_multipower_exhanstive():
|
351 |
+
from sympy.core.numbers import igcd
|
352 |
+
primes = [5, 5, 7]
|
353 |
+
e = 7
|
354 |
+
args = primes + [e]
|
355 |
+
puk = rsa_public_key(*args, multipower=True)
|
356 |
+
prk = rsa_private_key(*args, multipower=True)
|
357 |
+
n = puk[0]
|
358 |
+
|
359 |
+
for msg in range(n):
|
360 |
+
if igcd(msg, n) != 1:
|
361 |
+
continue
|
362 |
+
|
363 |
+
encrypted = encipher_rsa(msg, puk)
|
364 |
+
decrypted = decipher_rsa(encrypted, prk)
|
365 |
+
try:
|
366 |
+
assert decrypted == msg
|
367 |
+
except AssertionError:
|
368 |
+
raise AssertionError(
|
369 |
+
"The RSA is not correctly decrypted " \
|
370 |
+
"(Original : {}, Encrypted : {}, Decrypted : {})" \
|
371 |
+
.format(msg, encrypted, decrypted)
|
372 |
+
)
|
373 |
+
|
374 |
+
|
375 |
+
def test_kid_rsa_public_key():
|
376 |
+
assert kid_rsa_public_key(1, 2, 1, 1) == (5, 2)
|
377 |
+
assert kid_rsa_public_key(1, 2, 2, 1) == (8, 3)
|
378 |
+
assert kid_rsa_public_key(1, 2, 1, 2) == (7, 2)
|
379 |
+
|
380 |
+
|
381 |
+
def test_kid_rsa_private_key():
|
382 |
+
assert kid_rsa_private_key(1, 2, 1, 1) == (5, 3)
|
383 |
+
assert kid_rsa_private_key(1, 2, 2, 1) == (8, 3)
|
384 |
+
assert kid_rsa_private_key(1, 2, 1, 2) == (7, 4)
|
385 |
+
|
386 |
+
|
387 |
+
def test_encipher_kid_rsa():
|
388 |
+
assert encipher_kid_rsa(1, (5, 2)) == 2
|
389 |
+
assert encipher_kid_rsa(1, (8, 3)) == 3
|
390 |
+
assert encipher_kid_rsa(1, (7, 2)) == 2
|
391 |
+
|
392 |
+
|
393 |
+
def test_decipher_kid_rsa():
|
394 |
+
assert decipher_kid_rsa(2, (5, 3)) == 1
|
395 |
+
assert decipher_kid_rsa(3, (8, 3)) == 1
|
396 |
+
assert decipher_kid_rsa(2, (7, 4)) == 1
|
397 |
+
|
398 |
+
|
399 |
+
def test_encode_morse():
|
400 |
+
assert encode_morse('ABC') == '.-|-...|-.-.'
|
401 |
+
assert encode_morse('SMS ') == '...|--|...||'
|
402 |
+
assert encode_morse('SMS\n') == '...|--|...||'
|
403 |
+
assert encode_morse('') == ''
|
404 |
+
assert encode_morse(' ') == '||'
|
405 |
+
assert encode_morse(' ', sep='`') == '``'
|
406 |
+
assert encode_morse(' ', sep='``') == '````'
|
407 |
+
assert encode_morse('!@#$%^&*()_+') == '-.-.--|.--.-.|...-..-|-.--.|-.--.-|..--.-|.-.-.'
|
408 |
+
assert encode_morse('12345') == '.----|..---|...--|....-|.....'
|
409 |
+
assert encode_morse('67890') == '-....|--...|---..|----.|-----'
|
410 |
+
|
411 |
+
|
412 |
+
def test_decode_morse():
|
413 |
+
assert decode_morse('-.-|.|-.--') == 'KEY'
|
414 |
+
assert decode_morse('.-.|..-|-.||') == 'RUN'
|
415 |
+
raises(KeyError, lambda: decode_morse('.....----'))
|
416 |
+
|
417 |
+
|
418 |
+
def test_lfsr_sequence():
|
419 |
+
raises(TypeError, lambda: lfsr_sequence(1, [1], 1))
|
420 |
+
raises(TypeError, lambda: lfsr_sequence([1], 1, 1))
|
421 |
+
F = FF(2)
|
422 |
+
assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
|
423 |
+
assert lfsr_sequence([F(0)], [F(1)], 2) == [F(1), F(0)]
|
424 |
+
F = FF(3)
|
425 |
+
assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
|
426 |
+
assert lfsr_sequence([F(0)], [F(2)], 2) == [F(2), F(0)]
|
427 |
+
assert lfsr_sequence([F(1)], [F(2)], 2) == [F(2), F(2)]
|
428 |
+
|
429 |
+
|
430 |
+
def test_lfsr_autocorrelation():
|
431 |
+
raises(TypeError, lambda: lfsr_autocorrelation(1, 2, 3))
|
432 |
+
F = FF(2)
|
433 |
+
s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
|
434 |
+
assert lfsr_autocorrelation(s, 2, 0) == 1
|
435 |
+
assert lfsr_autocorrelation(s, 2, 1) == -1
|
436 |
+
|
437 |
+
|
438 |
+
def test_lfsr_connection_polynomial():
|
439 |
+
F = FF(2)
|
440 |
+
x = symbols("x")
|
441 |
+
s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
|
442 |
+
assert lfsr_connection_polynomial(s) == x**2 + 1
|
443 |
+
s = lfsr_sequence([F(1), F(1)], [F(0), F(1)], 5)
|
444 |
+
assert lfsr_connection_polynomial(s) == x**2 + x + 1
|
445 |
+
|
446 |
+
|
447 |
+
def test_elgamal_private_key():
|
448 |
+
a, b, _ = elgamal_private_key(digit=100)
|
449 |
+
assert isprime(a)
|
450 |
+
assert is_primitive_root(b, a)
|
451 |
+
assert len(bin(a)) >= 102
|
452 |
+
|
453 |
+
|
454 |
+
def test_elgamal():
|
455 |
+
dk = elgamal_private_key(5)
|
456 |
+
ek = elgamal_public_key(dk)
|
457 |
+
P = ek[0]
|
458 |
+
assert P - 1 == decipher_elgamal(encipher_elgamal(P - 1, ek), dk)
|
459 |
+
raises(ValueError, lambda: encipher_elgamal(P, dk))
|
460 |
+
raises(ValueError, lambda: encipher_elgamal(-1, dk))
|
461 |
+
|
462 |
+
|
463 |
+
def test_dh_private_key():
|
464 |
+
p, g, _ = dh_private_key(digit = 100)
|
465 |
+
assert isprime(p)
|
466 |
+
assert is_primitive_root(g, p)
|
467 |
+
assert len(bin(p)) >= 102
|
468 |
+
|
469 |
+
|
470 |
+
def test_dh_public_key():
|
471 |
+
p1, g1, a = dh_private_key(digit = 100)
|
472 |
+
p2, g2, ga = dh_public_key((p1, g1, a))
|
473 |
+
assert p1 == p2
|
474 |
+
assert g1 == g2
|
475 |
+
assert ga == pow(g1, a, p1)
|
476 |
+
|
477 |
+
|
478 |
+
def test_dh_shared_key():
|
479 |
+
prk = dh_private_key(digit = 100)
|
480 |
+
p, _, ga = dh_public_key(prk)
|
481 |
+
b = randrange(2, p)
|
482 |
+
sk = dh_shared_key((p, _, ga), b)
|
483 |
+
assert sk == pow(ga, b, p)
|
484 |
+
raises(ValueError, lambda: dh_shared_key((1031, 14, 565), 2000))
|
485 |
+
|
486 |
+
|
487 |
+
def test_padded_key():
|
488 |
+
assert padded_key('b', 'ab') == 'ba'
|
489 |
+
raises(ValueError, lambda: padded_key('ab', 'ace'))
|
490 |
+
raises(ValueError, lambda: padded_key('ab', 'abba'))
|
491 |
+
|
492 |
+
|
493 |
+
def test_bifid():
|
494 |
+
raises(ValueError, lambda: encipher_bifid('abc', 'b', 'abcde'))
|
495 |
+
assert encipher_bifid('abc', 'b', 'abcd') == 'bdb'
|
496 |
+
raises(ValueError, lambda: decipher_bifid('bdb', 'b', 'abcde'))
|
497 |
+
assert encipher_bifid('bdb', 'b', 'abcd') == 'abc'
|
498 |
+
raises(ValueError, lambda: bifid_square('abcde'))
|
499 |
+
assert bifid5_square("B") == \
|
500 |
+
bifid5_square('BACDEFGHIKLMNOPQRSTUVWXYZ')
|
501 |
+
assert bifid6_square('B0') == \
|
502 |
+
bifid6_square('B0ACDEFGHIJKLMNOPQRSTUVWXYZ123456789')
|
503 |
+
|
504 |
+
|
505 |
+
def test_encipher_decipher_gm():
|
506 |
+
ps = [131, 137, 139, 149, 151, 157, 163, 167,
|
507 |
+
173, 179, 181, 191, 193, 197, 199]
|
508 |
+
qs = [89, 97, 101, 103, 107, 109, 113, 127,
|
509 |
+
131, 137, 139, 149, 151, 157, 47]
|
510 |
+
messages = [
|
511 |
+
0, 32855, 34303, 14805, 1280, 75859, 38368,
|
512 |
+
724, 60356, 51675, 76697, 61854, 18661,
|
513 |
+
]
|
514 |
+
for p, q in zip(ps, qs):
|
515 |
+
pri = gm_private_key(p, q)
|
516 |
+
for msg in messages:
|
517 |
+
pub = gm_public_key(p, q)
|
518 |
+
enc = encipher_gm(msg, pub)
|
519 |
+
dec = decipher_gm(enc, pri)
|
520 |
+
assert dec == msg
|
521 |
+
|
522 |
+
|
523 |
+
def test_gm_private_key():
|
524 |
+
raises(ValueError, lambda: gm_public_key(13, 15))
|
525 |
+
raises(ValueError, lambda: gm_public_key(0, 0))
|
526 |
+
raises(ValueError, lambda: gm_public_key(0, 5))
|
527 |
+
assert 17, 19 == gm_public_key(17, 19)
|
528 |
+
|
529 |
+
|
530 |
+
def test_gm_public_key():
|
531 |
+
assert 323 == gm_public_key(17, 19)[1]
|
532 |
+
assert 15 == gm_public_key(3, 5)[1]
|
533 |
+
raises(ValueError, lambda: gm_public_key(15, 19))
|
534 |
+
|
535 |
+
def test_encipher_decipher_bg():
|
536 |
+
ps = [67, 7, 71, 103, 11, 43, 107, 47,
|
537 |
+
79, 19, 83, 23, 59, 127, 31]
|
538 |
+
qs = qs = [7, 71, 103, 11, 43, 107, 47,
|
539 |
+
79, 19, 83, 23, 59, 127, 31, 67]
|
540 |
+
messages = [
|
541 |
+
0, 328, 343, 148, 1280, 758, 383,
|
542 |
+
724, 603, 516, 766, 618, 186,
|
543 |
+
]
|
544 |
+
|
545 |
+
for p, q in zip(ps, qs):
|
546 |
+
pri = bg_private_key(p, q)
|
547 |
+
for msg in messages:
|
548 |
+
pub = bg_public_key(p, q)
|
549 |
+
enc = encipher_bg(msg, pub)
|
550 |
+
dec = decipher_bg(enc, pri)
|
551 |
+
assert dec == msg
|
552 |
+
|
553 |
+
def test_bg_private_key():
|
554 |
+
raises(ValueError, lambda: bg_private_key(8, 16))
|
555 |
+
raises(ValueError, lambda: bg_private_key(8, 8))
|
556 |
+
raises(ValueError, lambda: bg_private_key(13, 17))
|
557 |
+
assert 23, 31 == bg_private_key(23, 31)
|
558 |
+
|
559 |
+
def test_bg_public_key():
|
560 |
+
assert 5293 == bg_public_key(67, 79)
|
561 |
+
assert 713 == bg_public_key(23, 31)
|
562 |
+
raises(ValueError, lambda: bg_private_key(13, 17))
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (191 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_gaussopt.cpython-310.pyc
ADDED
Binary file (4.11 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_medium.cpython-310.pyc
ADDED
Binary file (2.17 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_polarization.cpython-310.pyc
ADDED
Binary file (2.21 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_utils.cpython-310.pyc
ADDED
Binary file (8.23 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/__pycache__/test_waves.cpython-310.pyc
ADDED
Binary file (3.54 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_gaussopt.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.evalf import N
|
2 |
+
from sympy.core.numbers import (Float, I, oo, pi)
|
3 |
+
from sympy.core.symbol import symbols
|
4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
5 |
+
from sympy.functions.elementary.trigonometric import atan2
|
6 |
+
from sympy.matrices.dense import Matrix
|
7 |
+
from sympy.polys.polytools import factor
|
8 |
+
|
9 |
+
from sympy.physics.optics import (BeamParameter, CurvedMirror,
|
10 |
+
CurvedRefraction, FlatMirror, FlatRefraction, FreeSpace, GeometricRay,
|
11 |
+
RayTransferMatrix, ThinLens, conjugate_gauss_beams,
|
12 |
+
gaussian_conj, geometric_conj_ab, geometric_conj_af, geometric_conj_bf,
|
13 |
+
rayleigh2waist, waist2rayleigh)
|
14 |
+
|
15 |
+
|
16 |
+
def streq(a, b):
|
17 |
+
return str(a) == str(b)
|
18 |
+
|
19 |
+
|
20 |
+
def test_gauss_opt():
|
21 |
+
mat = RayTransferMatrix(1, 2, 3, 4)
|
22 |
+
assert mat == Matrix([[1, 2], [3, 4]])
|
23 |
+
assert mat == RayTransferMatrix( Matrix([[1, 2], [3, 4]]) )
|
24 |
+
assert [mat.A, mat.B, mat.C, mat.D] == [1, 2, 3, 4]
|
25 |
+
|
26 |
+
d, f, h, n1, n2, R = symbols('d f h n1 n2 R')
|
27 |
+
lens = ThinLens(f)
|
28 |
+
assert lens == Matrix([[ 1, 0], [-1/f, 1]])
|
29 |
+
assert lens.C == -1/f
|
30 |
+
assert FreeSpace(d) == Matrix([[ 1, d], [0, 1]])
|
31 |
+
assert FlatRefraction(n1, n2) == Matrix([[1, 0], [0, n1/n2]])
|
32 |
+
assert CurvedRefraction(
|
33 |
+
R, n1, n2) == Matrix([[1, 0], [(n1 - n2)/(R*n2), n1/n2]])
|
34 |
+
assert FlatMirror() == Matrix([[1, 0], [0, 1]])
|
35 |
+
assert CurvedMirror(R) == Matrix([[ 1, 0], [-2/R, 1]])
|
36 |
+
assert ThinLens(f) == Matrix([[ 1, 0], [-1/f, 1]])
|
37 |
+
|
38 |
+
mul = CurvedMirror(R)*FreeSpace(d)
|
39 |
+
mul_mat = Matrix([[ 1, 0], [-2/R, 1]])*Matrix([[ 1, d], [0, 1]])
|
40 |
+
assert mul.A == mul_mat[0, 0]
|
41 |
+
assert mul.B == mul_mat[0, 1]
|
42 |
+
assert mul.C == mul_mat[1, 0]
|
43 |
+
assert mul.D == mul_mat[1, 1]
|
44 |
+
|
45 |
+
angle = symbols('angle')
|
46 |
+
assert GeometricRay(h, angle) == Matrix([[ h], [angle]])
|
47 |
+
assert FreeSpace(
|
48 |
+
d)*GeometricRay(h, angle) == Matrix([[angle*d + h], [angle]])
|
49 |
+
assert GeometricRay( Matrix( ((h,), (angle,)) ) ) == Matrix([[h], [angle]])
|
50 |
+
assert (FreeSpace(d)*GeometricRay(h, angle)).height == angle*d + h
|
51 |
+
assert (FreeSpace(d)*GeometricRay(h, angle)).angle == angle
|
52 |
+
|
53 |
+
p = BeamParameter(530e-9, 1, w=1e-3)
|
54 |
+
assert streq(p.q, 1 + 1.88679245283019*I*pi)
|
55 |
+
assert streq(N(p.q), 1.0 + 5.92753330865999*I)
|
56 |
+
assert streq(N(p.w_0), Float(0.00100000000000000))
|
57 |
+
assert streq(N(p.z_r), Float(5.92753330865999))
|
58 |
+
fs = FreeSpace(10)
|
59 |
+
p1 = fs*p
|
60 |
+
assert streq(N(p.w), Float(0.00101413072159615))
|
61 |
+
assert streq(N(p1.w), Float(0.00210803120913829))
|
62 |
+
|
63 |
+
w, wavelen = symbols('w wavelen')
|
64 |
+
assert waist2rayleigh(w, wavelen) == pi*w**2/wavelen
|
65 |
+
z_r, wavelen = symbols('z_r wavelen')
|
66 |
+
assert rayleigh2waist(z_r, wavelen) == sqrt(wavelen*z_r)/sqrt(pi)
|
67 |
+
|
68 |
+
a, b, f = symbols('a b f')
|
69 |
+
assert geometric_conj_ab(a, b) == a*b/(a + b)
|
70 |
+
assert geometric_conj_af(a, f) == a*f/(a - f)
|
71 |
+
assert geometric_conj_bf(b, f) == b*f/(b - f)
|
72 |
+
assert geometric_conj_ab(oo, b) == b
|
73 |
+
assert geometric_conj_ab(a, oo) == a
|
74 |
+
|
75 |
+
s_in, z_r_in, f = symbols('s_in z_r_in f')
|
76 |
+
assert gaussian_conj(
|
77 |
+
s_in, z_r_in, f)[0] == 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
|
78 |
+
assert gaussian_conj(
|
79 |
+
s_in, z_r_in, f)[1] == z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
|
80 |
+
assert gaussian_conj(
|
81 |
+
s_in, z_r_in, f)[2] == 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
|
82 |
+
|
83 |
+
l, w_i, w_o, f = symbols('l w_i w_o f')
|
84 |
+
assert conjugate_gauss_beams(l, w_i, w_o, f=f)[0] == f*(
|
85 |
+
-sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)) + 1)
|
86 |
+
assert factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1]) == f*w_o**2*(
|
87 |
+
w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))/w_i**2
|
88 |
+
assert conjugate_gauss_beams(l, w_i, w_o, f=f)[2] == f
|
89 |
+
|
90 |
+
z, l, w_0 = symbols('z l w_0', positive=True)
|
91 |
+
p = BeamParameter(l, z, w=w_0)
|
92 |
+
assert p.radius == z*(pi**2*w_0**4/(l**2*z**2) + 1)
|
93 |
+
assert p.w == w_0*sqrt(l**2*z**2/(pi**2*w_0**4) + 1)
|
94 |
+
assert p.w_0 == w_0
|
95 |
+
assert p.divergence == l/(pi*w_0)
|
96 |
+
assert p.gouy == atan2(z, pi*w_0**2/l)
|
97 |
+
assert p.waist_approximation_limit == 2*l/pi
|
98 |
+
|
99 |
+
p = BeamParameter(530e-9, 1, w=1e-3, n=2)
|
100 |
+
assert streq(p.q, 1 + 3.77358490566038*I*pi)
|
101 |
+
assert streq(N(p.z_r), Float(11.8550666173200))
|
102 |
+
assert streq(N(p.w_0), Float(0.00100000000000000))
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_medium.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
2 |
+
from sympy.physics.optics import Medium
|
3 |
+
from sympy.abc import epsilon, mu, n
|
4 |
+
from sympy.physics.units import speed_of_light, u0, e0, m, kg, s, A
|
5 |
+
|
6 |
+
from sympy.testing.pytest import raises
|
7 |
+
|
8 |
+
c = speed_of_light.convert_to(m/s)
|
9 |
+
e0 = e0.convert_to(A**2*s**4/(kg*m**3))
|
10 |
+
u0 = u0.convert_to(m*kg/(A**2*s**2))
|
11 |
+
|
12 |
+
|
13 |
+
def test_medium():
|
14 |
+
m1 = Medium('m1')
|
15 |
+
assert m1.intrinsic_impedance == sqrt(u0/e0)
|
16 |
+
assert m1.speed == 1/sqrt(e0*u0)
|
17 |
+
assert m1.refractive_index == c*sqrt(e0*u0)
|
18 |
+
assert m1.permittivity == e0
|
19 |
+
assert m1.permeability == u0
|
20 |
+
m2 = Medium('m2', epsilon, mu)
|
21 |
+
assert m2.intrinsic_impedance == sqrt(mu/epsilon)
|
22 |
+
assert m2.speed == 1/sqrt(epsilon*mu)
|
23 |
+
assert m2.refractive_index == c*sqrt(epsilon*mu)
|
24 |
+
assert m2.permittivity == epsilon
|
25 |
+
assert m2.permeability == mu
|
26 |
+
# Increasing electric permittivity and magnetic permeability
|
27 |
+
# by small amount from its value in vacuum.
|
28 |
+
m3 = Medium('m3', 9.0*10**(-12)*s**4*A**2/(m**3*kg), 1.45*10**(-6)*kg*m/(A**2*s**2))
|
29 |
+
assert m3.refractive_index > m1.refractive_index
|
30 |
+
assert m3 != m1
|
31 |
+
# Decreasing electric permittivity and magnetic permeability
|
32 |
+
# by small amount from its value in vacuum.
|
33 |
+
m4 = Medium('m4', 7.0*10**(-12)*s**4*A**2/(m**3*kg), 1.15*10**(-6)*kg*m/(A**2*s**2))
|
34 |
+
assert m4.refractive_index < m1.refractive_index
|
35 |
+
m5 = Medium('m5', permittivity=710*10**(-12)*s**4*A**2/(m**3*kg), n=1.33)
|
36 |
+
assert abs(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) \
|
37 |
+
< 1e-12*kg*m**2/(A**2*s**3)
|
38 |
+
assert abs(m5.speed - 225407863.157895*m/s) < 1e-6*m/s
|
39 |
+
assert abs(m5.refractive_index - 1.33000000000000) < 1e-12
|
40 |
+
assert abs(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) \
|
41 |
+
< 1e-20*A**2*s**4/(kg*m**3)
|
42 |
+
assert abs(m5.permeability - 2.77206575232851e-8*kg*m/(A**2*s**2)) \
|
43 |
+
< 1e-20*kg*m/(A**2*s**2)
|
44 |
+
m6 = Medium('m6', None, mu, n)
|
45 |
+
assert m6.permittivity == n**2/(c**2*mu)
|
46 |
+
# test for equality of refractive indices
|
47 |
+
assert Medium('m7').refractive_index == Medium('m8', e0, u0).refractive_index
|
48 |
+
raises(ValueError, lambda:Medium('m9', e0, u0, 2))
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_polarization.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.physics.optics.polarization import (jones_vector, stokes_vector,
|
2 |
+
jones_2_stokes, linear_polarizer, phase_retarder, half_wave_retarder,
|
3 |
+
quarter_wave_retarder, transmissive_filter, reflective_filter,
|
4 |
+
mueller_matrix, polarizing_beam_splitter)
|
5 |
+
from sympy.core.numbers import (I, pi)
|
6 |
+
from sympy.core.singleton import S
|
7 |
+
from sympy.core.symbol import symbols
|
8 |
+
from sympy.functions.elementary.exponential import exp
|
9 |
+
from sympy.matrices.dense import Matrix
|
10 |
+
|
11 |
+
|
12 |
+
def test_polarization():
|
13 |
+
assert jones_vector(0, 0) == Matrix([1, 0])
|
14 |
+
assert jones_vector(pi/2, 0) == Matrix([0, 1])
|
15 |
+
#################################################################
|
16 |
+
assert stokes_vector(0, 0) == Matrix([1, 1, 0, 0])
|
17 |
+
assert stokes_vector(pi/2, 0) == Matrix([1, -1, 0, 0])
|
18 |
+
#################################################################
|
19 |
+
H = jones_vector(0, 0)
|
20 |
+
V = jones_vector(pi/2, 0)
|
21 |
+
D = jones_vector(pi/4, 0)
|
22 |
+
A = jones_vector(-pi/4, 0)
|
23 |
+
R = jones_vector(0, pi/4)
|
24 |
+
L = jones_vector(0, -pi/4)
|
25 |
+
|
26 |
+
res = [Matrix([1, 1, 0, 0]),
|
27 |
+
Matrix([1, -1, 0, 0]),
|
28 |
+
Matrix([1, 0, 1, 0]),
|
29 |
+
Matrix([1, 0, -1, 0]),
|
30 |
+
Matrix([1, 0, 0, 1]),
|
31 |
+
Matrix([1, 0, 0, -1])]
|
32 |
+
|
33 |
+
assert [jones_2_stokes(e) for e in [H, V, D, A, R, L]] == res
|
34 |
+
#################################################################
|
35 |
+
assert linear_polarizer(0) == Matrix([[1, 0], [0, 0]])
|
36 |
+
#################################################################
|
37 |
+
delta = symbols("delta", real=True)
|
38 |
+
res = Matrix([[exp(-I*delta/2), 0], [0, exp(I*delta/2)]])
|
39 |
+
assert phase_retarder(0, delta) == res
|
40 |
+
#################################################################
|
41 |
+
assert half_wave_retarder(0) == Matrix([[-I, 0], [0, I]])
|
42 |
+
#################################################################
|
43 |
+
res = Matrix([[exp(-I*pi/4), 0], [0, I*exp(-I*pi/4)]])
|
44 |
+
assert quarter_wave_retarder(0) == res
|
45 |
+
#################################################################
|
46 |
+
assert transmissive_filter(1) == Matrix([[1, 0], [0, 1]])
|
47 |
+
#################################################################
|
48 |
+
assert reflective_filter(1) == Matrix([[1, 0], [0, -1]])
|
49 |
+
|
50 |
+
res = Matrix([[S(1)/2, S(1)/2, 0, 0],
|
51 |
+
[S(1)/2, S(1)/2, 0, 0],
|
52 |
+
[0, 0, 0, 0],
|
53 |
+
[0, 0, 0, 0]])
|
54 |
+
assert mueller_matrix(linear_polarizer(0)) == res
|
55 |
+
#################################################################
|
56 |
+
res = Matrix([[1, 0, 0, 0], [0, 0, 0, -I], [0, 0, 1, 0], [0, -I, 0, 0]])
|
57 |
+
assert polarizing_beam_splitter() == res
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_utils.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import comp, Rational
|
2 |
+
from sympy.physics.optics.utils import (refraction_angle, fresnel_coefficients,
|
3 |
+
deviation, brewster_angle, critical_angle, lens_makers_formula,
|
4 |
+
mirror_formula, lens_formula, hyperfocal_distance,
|
5 |
+
transverse_magnification)
|
6 |
+
from sympy.physics.optics.medium import Medium
|
7 |
+
from sympy.physics.units import e0
|
8 |
+
|
9 |
+
from sympy.core.numbers import oo
|
10 |
+
from sympy.core.symbol import symbols
|
11 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
12 |
+
from sympy.matrices.dense import Matrix
|
13 |
+
from sympy.geometry.point import Point3D
|
14 |
+
from sympy.geometry.line import Ray3D
|
15 |
+
from sympy.geometry.plane import Plane
|
16 |
+
|
17 |
+
from sympy.testing.pytest import raises
|
18 |
+
|
19 |
+
|
20 |
+
ae = lambda a, b, n: comp(a, b, 10**-n)
|
21 |
+
|
22 |
+
|
23 |
+
def test_refraction_angle():
|
24 |
+
n1, n2 = symbols('n1, n2')
|
25 |
+
m1 = Medium('m1')
|
26 |
+
m2 = Medium('m2')
|
27 |
+
r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
|
28 |
+
i = Matrix([1, 1, 1])
|
29 |
+
n = Matrix([0, 0, 1])
|
30 |
+
normal_ray = Ray3D(Point3D(0, 0, 0), Point3D(0, 0, 1))
|
31 |
+
P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
|
32 |
+
assert refraction_angle(r1, 1, 1, n) == Matrix([
|
33 |
+
[ 1],
|
34 |
+
[ 1],
|
35 |
+
[-1]])
|
36 |
+
assert refraction_angle([1, 1, 1], 1, 1, n) == Matrix([
|
37 |
+
[ 1],
|
38 |
+
[ 1],
|
39 |
+
[-1]])
|
40 |
+
assert refraction_angle((1, 1, 1), 1, 1, n) == Matrix([
|
41 |
+
[ 1],
|
42 |
+
[ 1],
|
43 |
+
[-1]])
|
44 |
+
assert refraction_angle(i, 1, 1, [0, 0, 1]) == Matrix([
|
45 |
+
[ 1],
|
46 |
+
[ 1],
|
47 |
+
[-1]])
|
48 |
+
assert refraction_angle(i, 1, 1, (0, 0, 1)) == Matrix([
|
49 |
+
[ 1],
|
50 |
+
[ 1],
|
51 |
+
[-1]])
|
52 |
+
assert refraction_angle(i, 1, 1, normal_ray) == Matrix([
|
53 |
+
[ 1],
|
54 |
+
[ 1],
|
55 |
+
[-1]])
|
56 |
+
assert refraction_angle(i, 1, 1, plane=P) == Matrix([
|
57 |
+
[ 1],
|
58 |
+
[ 1],
|
59 |
+
[-1]])
|
60 |
+
assert refraction_angle(r1, 1, 1, plane=P) == \
|
61 |
+
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
|
62 |
+
assert refraction_angle(r1, m1, 1.33, plane=P) == \
|
63 |
+
Ray3D(Point3D(0, 0, 0), Point3D(Rational(100, 133), Rational(100, 133), -789378201649271*sqrt(3)/1000000000000000))
|
64 |
+
assert refraction_angle(r1, 1, m2, plane=P) == \
|
65 |
+
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
|
66 |
+
assert refraction_angle(r1, n1, n2, plane=P) == \
|
67 |
+
Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
|
68 |
+
assert refraction_angle(r1, 1.33, 1, plane=P) == 0 # TIR
|
69 |
+
assert refraction_angle(r1, 1, 1, normal_ray) == \
|
70 |
+
Ray3D(Point3D(0, 0, 0), direction_ratio=[1, 1, -1])
|
71 |
+
assert ae(refraction_angle(0.5, 1, 2), 0.24207, 5)
|
72 |
+
assert ae(refraction_angle(0.5, 2, 1), 1.28293, 5)
|
73 |
+
raises(ValueError, lambda: refraction_angle(r1, m1, m2, normal_ray, P))
|
74 |
+
raises(TypeError, lambda: refraction_angle(m1, m1, m2)) # can add other values for arg[0]
|
75 |
+
raises(TypeError, lambda: refraction_angle(r1, m1, m2, None, i))
|
76 |
+
raises(TypeError, lambda: refraction_angle(r1, m1, m2, m2))
|
77 |
+
|
78 |
+
|
79 |
+
def test_fresnel_coefficients():
|
80 |
+
assert all(ae(i, j, 5) for i, j in zip(
|
81 |
+
fresnel_coefficients(0.5, 1, 1.33),
|
82 |
+
[0.11163, -0.17138, 0.83581, 0.82862]))
|
83 |
+
assert all(ae(i, j, 5) for i, j in zip(
|
84 |
+
fresnel_coefficients(0.5, 1.33, 1),
|
85 |
+
[-0.07726, 0.20482, 1.22724, 1.20482]))
|
86 |
+
m1 = Medium('m1')
|
87 |
+
m2 = Medium('m2', n=2)
|
88 |
+
assert all(ae(i, j, 5) for i, j in zip(
|
89 |
+
fresnel_coefficients(0.3, m1, m2),
|
90 |
+
[0.31784, -0.34865, 0.65892, 0.65135]))
|
91 |
+
ans = [[-0.23563, -0.97184], [0.81648, -0.57738]]
|
92 |
+
got = fresnel_coefficients(0.6, m2, m1)
|
93 |
+
for i, j in zip(got, ans):
|
94 |
+
for a, b in zip(i.as_real_imag(), j):
|
95 |
+
assert ae(a, b, 5)
|
96 |
+
|
97 |
+
|
98 |
+
def test_deviation():
|
99 |
+
n1, n2 = symbols('n1, n2')
|
100 |
+
r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
|
101 |
+
n = Matrix([0, 0, 1])
|
102 |
+
i = Matrix([-1, -1, -1])
|
103 |
+
normal_ray = Ray3D(Point3D(0, 0, 0), Point3D(0, 0, 1))
|
104 |
+
P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
|
105 |
+
assert deviation(r1, 1, 1, normal=n) == 0
|
106 |
+
assert deviation(r1, 1, 1, plane=P) == 0
|
107 |
+
assert deviation(r1, 1, 1.1, plane=P).evalf(3) + 0.119 < 1e-3
|
108 |
+
assert deviation(i, 1, 1.1, normal=normal_ray).evalf(3) + 0.119 < 1e-3
|
109 |
+
assert deviation(r1, 1.33, 1, plane=P) is None # TIR
|
110 |
+
assert deviation(r1, 1, 1, normal=[0, 0, 1]) == 0
|
111 |
+
assert deviation([-1, -1, -1], 1, 1, normal=[0, 0, 1]) == 0
|
112 |
+
assert ae(deviation(0.5, 1, 2), -0.25793, 5)
|
113 |
+
assert ae(deviation(0.5, 2, 1), 0.78293, 5)
|
114 |
+
|
115 |
+
|
116 |
+
def test_brewster_angle():
|
117 |
+
m1 = Medium('m1', n=1)
|
118 |
+
m2 = Medium('m2', n=1.33)
|
119 |
+
assert ae(brewster_angle(m1, m2), 0.93, 2)
|
120 |
+
m1 = Medium('m1', permittivity=e0, n=1)
|
121 |
+
m2 = Medium('m2', permittivity=e0, n=1.33)
|
122 |
+
assert ae(brewster_angle(m1, m2), 0.93, 2)
|
123 |
+
assert ae(brewster_angle(1, 1.33), 0.93, 2)
|
124 |
+
|
125 |
+
|
126 |
+
def test_critical_angle():
|
127 |
+
m1 = Medium('m1', n=1)
|
128 |
+
m2 = Medium('m2', n=1.33)
|
129 |
+
assert ae(critical_angle(m2, m1), 0.85, 2)
|
130 |
+
|
131 |
+
|
132 |
+
def test_lens_makers_formula():
|
133 |
+
n1, n2 = symbols('n1, n2')
|
134 |
+
m1 = Medium('m1', permittivity=e0, n=1)
|
135 |
+
m2 = Medium('m2', permittivity=e0, n=1.33)
|
136 |
+
assert lens_makers_formula(n1, n2, 10, -10) == 5.0*n2/(n1 - n2)
|
137 |
+
assert ae(lens_makers_formula(m1, m2, 10, -10), -20.15, 2)
|
138 |
+
assert ae(lens_makers_formula(1.33, 1, 10, -10), 15.15, 2)
|
139 |
+
|
140 |
+
|
141 |
+
def test_mirror_formula():
|
142 |
+
u, v, f = symbols('u, v, f')
|
143 |
+
assert mirror_formula(focal_length=f, u=u) == f*u/(-f + u)
|
144 |
+
assert mirror_formula(focal_length=f, v=v) == f*v/(-f + v)
|
145 |
+
assert mirror_formula(u=u, v=v) == u*v/(u + v)
|
146 |
+
assert mirror_formula(u=oo, v=v) == v
|
147 |
+
assert mirror_formula(u=oo, v=oo) is oo
|
148 |
+
assert mirror_formula(focal_length=oo, u=u) == -u
|
149 |
+
assert mirror_formula(u=u, v=oo) == u
|
150 |
+
assert mirror_formula(focal_length=oo, v=oo) is oo
|
151 |
+
assert mirror_formula(focal_length=f, v=oo) == f
|
152 |
+
assert mirror_formula(focal_length=oo, v=v) == -v
|
153 |
+
assert mirror_formula(focal_length=oo, u=oo) is oo
|
154 |
+
assert mirror_formula(focal_length=f, u=oo) == f
|
155 |
+
assert mirror_formula(focal_length=oo, u=u) == -u
|
156 |
+
raises(ValueError, lambda: mirror_formula(focal_length=f, u=u, v=v))
|
157 |
+
|
158 |
+
|
159 |
+
def test_lens_formula():
|
160 |
+
u, v, f = symbols('u, v, f')
|
161 |
+
assert lens_formula(focal_length=f, u=u) == f*u/(f + u)
|
162 |
+
assert lens_formula(focal_length=f, v=v) == f*v/(f - v)
|
163 |
+
assert lens_formula(u=u, v=v) == u*v/(u - v)
|
164 |
+
assert lens_formula(u=oo, v=v) == v
|
165 |
+
assert lens_formula(u=oo, v=oo) is oo
|
166 |
+
assert lens_formula(focal_length=oo, u=u) == u
|
167 |
+
assert lens_formula(u=u, v=oo) == -u
|
168 |
+
assert lens_formula(focal_length=oo, v=oo) is -oo
|
169 |
+
assert lens_formula(focal_length=oo, v=v) == v
|
170 |
+
assert lens_formula(focal_length=f, v=oo) == -f
|
171 |
+
assert lens_formula(focal_length=oo, u=oo) is oo
|
172 |
+
assert lens_formula(focal_length=oo, u=u) == u
|
173 |
+
assert lens_formula(focal_length=f, u=oo) == f
|
174 |
+
raises(ValueError, lambda: lens_formula(focal_length=f, u=u, v=v))
|
175 |
+
|
176 |
+
|
177 |
+
def test_hyperfocal_distance():
|
178 |
+
f, N, c = symbols('f, N, c')
|
179 |
+
assert hyperfocal_distance(f=f, N=N, c=c) == f**2/(N*c)
|
180 |
+
assert ae(hyperfocal_distance(f=0.5, N=8, c=0.0033), 9.47, 2)
|
181 |
+
|
182 |
+
|
183 |
+
def test_transverse_magnification():
|
184 |
+
si, so = symbols('si, so')
|
185 |
+
assert transverse_magnification(si, so) == -si/so
|
186 |
+
assert transverse_magnification(30, 15) == -2
|
187 |
+
|
188 |
+
|
189 |
+
def test_lens_makers_formula_thick_lens():
|
190 |
+
n1, n2 = symbols('n1, n2')
|
191 |
+
m1 = Medium('m1', permittivity=e0, n=1)
|
192 |
+
m2 = Medium('m2', permittivity=e0, n=1.33)
|
193 |
+
assert ae(lens_makers_formula(m1, m2, 10, -10, d=1), -19.82, 2)
|
194 |
+
assert lens_makers_formula(n1, n2, 1, -1, d=0.1) == n2/((2.0 - (0.1*n1 - 0.1*n2)/n1)*(n1 - n2))
|
195 |
+
|
196 |
+
|
197 |
+
def test_lens_makers_formula_plano_lens():
|
198 |
+
n1, n2 = symbols('n1, n2')
|
199 |
+
m1 = Medium('m1', permittivity=e0, n=1)
|
200 |
+
m2 = Medium('m2', permittivity=e0, n=1.33)
|
201 |
+
assert ae(lens_makers_formula(m1, m2, 10, oo), -40.30, 2)
|
202 |
+
assert lens_makers_formula(n1, n2, 10, oo) == 10.0*n2/(n1 - n2)
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/tests/test_waves.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.function import (Derivative, Function)
|
2 |
+
from sympy.core.numbers import (I, pi)
|
3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
5 |
+
from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
|
6 |
+
from sympy.simplify.simplify import simplify
|
7 |
+
from sympy.abc import epsilon, mu
|
8 |
+
from sympy.functions.elementary.exponential import exp
|
9 |
+
from sympy.physics.units import speed_of_light, m, s
|
10 |
+
from sympy.physics.optics import TWave
|
11 |
+
|
12 |
+
from sympy.testing.pytest import raises
|
13 |
+
|
14 |
+
c = speed_of_light.convert_to(m/s)
|
15 |
+
|
16 |
+
def test_twave():
|
17 |
+
A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
|
18 |
+
n = Symbol('n') # Refractive index
|
19 |
+
t = Symbol('t') # Time
|
20 |
+
x = Symbol('x') # Spatial variable
|
21 |
+
E = Function('E')
|
22 |
+
w1 = TWave(A1, f, phi1)
|
23 |
+
w2 = TWave(A2, f, phi2)
|
24 |
+
assert w1.amplitude == A1
|
25 |
+
assert w1.frequency == f
|
26 |
+
assert w1.phase == phi1
|
27 |
+
assert w1.wavelength == c/(f*n)
|
28 |
+
assert w1.time_period == 1/f
|
29 |
+
assert w1.angular_velocity == 2*pi*f
|
30 |
+
assert w1.wavenumber == 2*pi*f*n/c
|
31 |
+
assert w1.speed == c/n
|
32 |
+
|
33 |
+
w3 = w1 + w2
|
34 |
+
assert w3.amplitude == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
|
35 |
+
assert w3.frequency == f
|
36 |
+
assert w3.phase == atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))
|
37 |
+
assert w3.wavelength == c/(f*n)
|
38 |
+
assert w3.time_period == 1/f
|
39 |
+
assert w3.angular_velocity == 2*pi*f
|
40 |
+
assert w3.wavenumber == 2*pi*f*n/c
|
41 |
+
assert w3.speed == c/n
|
42 |
+
assert simplify(w3.rewrite(sin) - w2.rewrite(sin) - w1.rewrite(sin)) == 0
|
43 |
+
assert w3.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
|
44 |
+
assert w3.rewrite(cos) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
|
45 |
+
+ A2**2)*cos(pi*f*n*x*s/(149896229*m) - 2*pi*f*t + atan2(A1*sin(phi1)
|
46 |
+
+ A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)))
|
47 |
+
assert w3.rewrite(exp) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
|
48 |
+
+ A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1)
|
49 |
+
+ A2*cos(phi2)) + pi*s*f*n*x/(149896229*m)))
|
50 |
+
|
51 |
+
w4 = TWave(A1, None, 0, 1/f)
|
52 |
+
assert w4.frequency == f
|
53 |
+
|
54 |
+
w5 = w1 - w2
|
55 |
+
assert w5.amplitude == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2) + A2**2)
|
56 |
+
assert w5.frequency == f
|
57 |
+
assert w5.phase == atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1) - A2*cos(phi2))
|
58 |
+
assert w5.wavelength == c/(f*n)
|
59 |
+
assert w5.time_period == 1/f
|
60 |
+
assert w5.angular_velocity == 2*pi*f
|
61 |
+
assert w5.wavenumber == 2*pi*f*n/c
|
62 |
+
assert w5.speed == c/n
|
63 |
+
assert simplify(w5.rewrite(sin) - w1.rewrite(sin) + w2.rewrite(sin)) == 0
|
64 |
+
assert w5.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
|
65 |
+
assert w5.rewrite(cos) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2)
|
66 |
+
+ A2**2)*cos(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1)
|
67 |
+
- A2*cos(phi2)) + pi*s*f*n*x/(149896229*m))
|
68 |
+
assert w5.rewrite(exp) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2)
|
69 |
+
+ A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1)
|
70 |
+
- A2*cos(phi2)) + pi*s*f*n*x/(149896229*m)))
|
71 |
+
|
72 |
+
w6 = 2*w1
|
73 |
+
assert w6.amplitude == 2*A1
|
74 |
+
assert w6.frequency == f
|
75 |
+
assert w6.phase == phi1
|
76 |
+
w7 = -w6
|
77 |
+
assert w7.amplitude == -2*A1
|
78 |
+
assert w7.frequency == f
|
79 |
+
assert w7.phase == phi1
|
80 |
+
|
81 |
+
raises(ValueError, lambda:TWave(A1))
|
82 |
+
raises(ValueError, lambda:TWave(A1, f, phi1, t))
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (12.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/quantities.cpython-310.pyc
ADDED
Binary file (5.29 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (477 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/cgs.cpython-310.pyc
ADDED
Binary file (2.39 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/length_weight_time.cpython-310.pyc
ADDED
Binary file (4.87 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/mks.cpython-310.pyc
ADDED
Binary file (1.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/mksa.cpython-310.pyc
ADDED
Binary file (1.69 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/natural.cpython-310.pyc
ADDED
Binary file (1.13 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/si.cpython-310.pyc
ADDED
Binary file (7.77 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/systems/si.py
ADDED
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
SI unit system.
|
3 |
+
Based on MKSA, which stands for "meter, kilogram, second, ampere".
|
4 |
+
Added kelvin, candela and mole.
|
5 |
+
|
6 |
+
"""
|
7 |
+
|
8 |
+
from __future__ import annotations
|
9 |
+
|
10 |
+
from sympy.physics.units import DimensionSystem, Dimension, dHg0
|
11 |
+
|
12 |
+
from sympy.physics.units.quantities import Quantity
|
13 |
+
|
14 |
+
from sympy.core.numbers import (Rational, pi)
|
15 |
+
from sympy.core.singleton import S
|
16 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
17 |
+
from sympy.physics.units.definitions.dimension_definitions import (
|
18 |
+
acceleration, action, current, impedance, length, mass, time, velocity,
|
19 |
+
amount_of_substance, temperature, information, frequency, force, pressure,
|
20 |
+
energy, power, charge, voltage, capacitance, conductance, magnetic_flux,
|
21 |
+
magnetic_density, inductance, luminous_intensity
|
22 |
+
)
|
23 |
+
from sympy.physics.units.definitions import (
|
24 |
+
kilogram, newton, second, meter, gram, cd, K, joule, watt, pascal, hertz,
|
25 |
+
coulomb, volt, ohm, siemens, farad, henry, tesla, weber, dioptre, lux,
|
26 |
+
katal, gray, becquerel, inch, liter, julian_year, gravitational_constant,
|
27 |
+
speed_of_light, elementary_charge, planck, hbar, electronvolt,
|
28 |
+
avogadro_number, avogadro_constant, boltzmann_constant, electron_rest_mass,
|
29 |
+
stefan_boltzmann_constant, Da, atomic_mass_constant, molar_gas_constant,
|
30 |
+
faraday_constant, josephson_constant, von_klitzing_constant,
|
31 |
+
acceleration_due_to_gravity, magnetic_constant, vacuum_permittivity,
|
32 |
+
vacuum_impedance, coulomb_constant, atmosphere, bar, pound, psi, mmHg,
|
33 |
+
milli_mass_unit, quart, lightyear, astronomical_unit, planck_mass,
|
34 |
+
planck_time, planck_temperature, planck_length, planck_charge, planck_area,
|
35 |
+
planck_volume, planck_momentum, planck_energy, planck_force, planck_power,
|
36 |
+
planck_density, planck_energy_density, planck_intensity,
|
37 |
+
planck_angular_frequency, planck_pressure, planck_current, planck_voltage,
|
38 |
+
planck_impedance, planck_acceleration, bit, byte, kibibyte, mebibyte,
|
39 |
+
gibibyte, tebibyte, pebibyte, exbibyte, curie, rutherford, radian, degree,
|
40 |
+
steradian, angular_mil, atomic_mass_unit, gee, kPa, ampere, u0, c, kelvin,
|
41 |
+
mol, mole, candela, m, kg, s, electric_constant, G, boltzmann
|
42 |
+
)
|
43 |
+
from sympy.physics.units.prefixes import PREFIXES, prefix_unit
|
44 |
+
from sympy.physics.units.systems.mksa import MKSA, dimsys_MKSA
|
45 |
+
|
46 |
+
derived_dims = (frequency, force, pressure, energy, power, charge, voltage,
|
47 |
+
capacitance, conductance, magnetic_flux,
|
48 |
+
magnetic_density, inductance, luminous_intensity)
|
49 |
+
base_dims = (amount_of_substance, luminous_intensity, temperature)
|
50 |
+
|
51 |
+
units = [mol, cd, K, lux, hertz, newton, pascal, joule, watt, coulomb, volt,
|
52 |
+
farad, ohm, siemens, weber, tesla, henry, candela, lux, becquerel,
|
53 |
+
gray, katal]
|
54 |
+
|
55 |
+
all_units: list[Quantity] = []
|
56 |
+
for u in units:
|
57 |
+
all_units.extend(prefix_unit(u, PREFIXES))
|
58 |
+
|
59 |
+
all_units.extend(units)
|
60 |
+
all_units.extend([mol, cd, K, lux])
|
61 |
+
|
62 |
+
|
63 |
+
dimsys_SI = dimsys_MKSA.extend(
|
64 |
+
[
|
65 |
+
# Dimensional dependencies for other base dimensions:
|
66 |
+
temperature,
|
67 |
+
amount_of_substance,
|
68 |
+
luminous_intensity,
|
69 |
+
])
|
70 |
+
|
71 |
+
dimsys_default = dimsys_SI.extend(
|
72 |
+
[information],
|
73 |
+
)
|
74 |
+
|
75 |
+
SI = MKSA.extend(base=(mol, cd, K), units=all_units, name='SI', dimension_system=dimsys_SI, derived_units={
|
76 |
+
power: watt,
|
77 |
+
magnetic_flux: weber,
|
78 |
+
time: second,
|
79 |
+
impedance: ohm,
|
80 |
+
pressure: pascal,
|
81 |
+
current: ampere,
|
82 |
+
voltage: volt,
|
83 |
+
length: meter,
|
84 |
+
frequency: hertz,
|
85 |
+
inductance: henry,
|
86 |
+
temperature: kelvin,
|
87 |
+
amount_of_substance: mole,
|
88 |
+
luminous_intensity: candela,
|
89 |
+
conductance: siemens,
|
90 |
+
mass: kilogram,
|
91 |
+
magnetic_density: tesla,
|
92 |
+
charge: coulomb,
|
93 |
+
force: newton,
|
94 |
+
capacitance: farad,
|
95 |
+
energy: joule,
|
96 |
+
velocity: meter/second,
|
97 |
+
})
|
98 |
+
|
99 |
+
One = S.One
|
100 |
+
|
101 |
+
SI.set_quantity_dimension(radian, One)
|
102 |
+
|
103 |
+
SI.set_quantity_scale_factor(ampere, One)
|
104 |
+
|
105 |
+
SI.set_quantity_scale_factor(kelvin, One)
|
106 |
+
|
107 |
+
SI.set_quantity_scale_factor(mole, One)
|
108 |
+
|
109 |
+
SI.set_quantity_scale_factor(candela, One)
|
110 |
+
|
111 |
+
# MKSA extension to MKS: derived units
|
112 |
+
|
113 |
+
SI.set_quantity_scale_factor(coulomb, One)
|
114 |
+
|
115 |
+
SI.set_quantity_scale_factor(volt, joule/coulomb)
|
116 |
+
|
117 |
+
SI.set_quantity_scale_factor(ohm, volt/ampere)
|
118 |
+
|
119 |
+
SI.set_quantity_scale_factor(siemens, ampere/volt)
|
120 |
+
|
121 |
+
SI.set_quantity_scale_factor(farad, coulomb/volt)
|
122 |
+
|
123 |
+
SI.set_quantity_scale_factor(henry, volt*second/ampere)
|
124 |
+
|
125 |
+
SI.set_quantity_scale_factor(tesla, volt*second/meter**2)
|
126 |
+
|
127 |
+
SI.set_quantity_scale_factor(weber, joule/ampere)
|
128 |
+
|
129 |
+
|
130 |
+
SI.set_quantity_dimension(lux, luminous_intensity / length ** 2)
|
131 |
+
SI.set_quantity_scale_factor(lux, steradian*candela/meter**2)
|
132 |
+
|
133 |
+
# katal is the SI unit of catalytic activity
|
134 |
+
|
135 |
+
SI.set_quantity_dimension(katal, amount_of_substance / time)
|
136 |
+
SI.set_quantity_scale_factor(katal, mol/second)
|
137 |
+
|
138 |
+
# gray is the SI unit of absorbed dose
|
139 |
+
|
140 |
+
SI.set_quantity_dimension(gray, energy / mass)
|
141 |
+
SI.set_quantity_scale_factor(gray, meter**2/second**2)
|
142 |
+
|
143 |
+
# becquerel is the SI unit of radioactivity
|
144 |
+
|
145 |
+
SI.set_quantity_dimension(becquerel, 1 / time)
|
146 |
+
SI.set_quantity_scale_factor(becquerel, 1/second)
|
147 |
+
|
148 |
+
#### CONSTANTS ####
|
149 |
+
|
150 |
+
# elementary charge
|
151 |
+
# REF: NIST SP 959 (June 2019)
|
152 |
+
|
153 |
+
SI.set_quantity_dimension(elementary_charge, charge)
|
154 |
+
SI.set_quantity_scale_factor(elementary_charge, 1.602176634e-19*coulomb)
|
155 |
+
|
156 |
+
# Electronvolt
|
157 |
+
# REF: NIST SP 959 (June 2019)
|
158 |
+
|
159 |
+
SI.set_quantity_dimension(electronvolt, energy)
|
160 |
+
SI.set_quantity_scale_factor(electronvolt, 1.602176634e-19*joule)
|
161 |
+
|
162 |
+
# Avogadro number
|
163 |
+
# REF: NIST SP 959 (June 2019)
|
164 |
+
|
165 |
+
SI.set_quantity_dimension(avogadro_number, One)
|
166 |
+
SI.set_quantity_scale_factor(avogadro_number, 6.02214076e23)
|
167 |
+
|
168 |
+
# Avogadro constant
|
169 |
+
|
170 |
+
SI.set_quantity_dimension(avogadro_constant, amount_of_substance ** -1)
|
171 |
+
SI.set_quantity_scale_factor(avogadro_constant, avogadro_number / mol)
|
172 |
+
|
173 |
+
# Boltzmann constant
|
174 |
+
# REF: NIST SP 959 (June 2019)
|
175 |
+
|
176 |
+
SI.set_quantity_dimension(boltzmann_constant, energy / temperature)
|
177 |
+
SI.set_quantity_scale_factor(boltzmann_constant, 1.380649e-23*joule/kelvin)
|
178 |
+
|
179 |
+
# Stefan-Boltzmann constant
|
180 |
+
# REF: NIST SP 959 (June 2019)
|
181 |
+
|
182 |
+
SI.set_quantity_dimension(stefan_boltzmann_constant, energy * time ** -1 * length ** -2 * temperature ** -4)
|
183 |
+
SI.set_quantity_scale_factor(stefan_boltzmann_constant, pi**2 * boltzmann_constant**4 / (60 * hbar**3 * speed_of_light ** 2))
|
184 |
+
|
185 |
+
# Atomic mass
|
186 |
+
# REF: NIST SP 959 (June 2019)
|
187 |
+
|
188 |
+
SI.set_quantity_dimension(atomic_mass_constant, mass)
|
189 |
+
SI.set_quantity_scale_factor(atomic_mass_constant, 1.66053906660e-24*gram)
|
190 |
+
|
191 |
+
# Molar gas constant
|
192 |
+
# REF: NIST SP 959 (June 2019)
|
193 |
+
|
194 |
+
SI.set_quantity_dimension(molar_gas_constant, energy / (temperature * amount_of_substance))
|
195 |
+
SI.set_quantity_scale_factor(molar_gas_constant, boltzmann_constant * avogadro_constant)
|
196 |
+
|
197 |
+
# Faraday constant
|
198 |
+
|
199 |
+
SI.set_quantity_dimension(faraday_constant, charge / amount_of_substance)
|
200 |
+
SI.set_quantity_scale_factor(faraday_constant, elementary_charge * avogadro_constant)
|
201 |
+
|
202 |
+
# Josephson constant
|
203 |
+
|
204 |
+
SI.set_quantity_dimension(josephson_constant, frequency / voltage)
|
205 |
+
SI.set_quantity_scale_factor(josephson_constant, 0.5 * planck / elementary_charge)
|
206 |
+
|
207 |
+
# Von Klitzing constant
|
208 |
+
|
209 |
+
SI.set_quantity_dimension(von_klitzing_constant, voltage / current)
|
210 |
+
SI.set_quantity_scale_factor(von_klitzing_constant, hbar / elementary_charge ** 2)
|
211 |
+
|
212 |
+
# Acceleration due to gravity (on the Earth surface)
|
213 |
+
|
214 |
+
SI.set_quantity_dimension(acceleration_due_to_gravity, acceleration)
|
215 |
+
SI.set_quantity_scale_factor(acceleration_due_to_gravity, 9.80665*meter/second**2)
|
216 |
+
|
217 |
+
# magnetic constant:
|
218 |
+
|
219 |
+
SI.set_quantity_dimension(magnetic_constant, force / current ** 2)
|
220 |
+
SI.set_quantity_scale_factor(magnetic_constant, 4*pi/10**7 * newton/ampere**2)
|
221 |
+
|
222 |
+
# electric constant:
|
223 |
+
|
224 |
+
SI.set_quantity_dimension(vacuum_permittivity, capacitance / length)
|
225 |
+
SI.set_quantity_scale_factor(vacuum_permittivity, 1/(u0 * c**2))
|
226 |
+
|
227 |
+
# vacuum impedance:
|
228 |
+
|
229 |
+
SI.set_quantity_dimension(vacuum_impedance, impedance)
|
230 |
+
SI.set_quantity_scale_factor(vacuum_impedance, u0 * c)
|
231 |
+
|
232 |
+
# Electron rest mass
|
233 |
+
SI.set_quantity_dimension(electron_rest_mass, mass)
|
234 |
+
SI.set_quantity_scale_factor(electron_rest_mass, 9.1093837015e-31*kilogram)
|
235 |
+
|
236 |
+
# Coulomb's constant:
|
237 |
+
SI.set_quantity_dimension(coulomb_constant, force * length ** 2 / charge ** 2)
|
238 |
+
SI.set_quantity_scale_factor(coulomb_constant, 1/(4*pi*vacuum_permittivity))
|
239 |
+
|
240 |
+
SI.set_quantity_dimension(psi, pressure)
|
241 |
+
SI.set_quantity_scale_factor(psi, pound * gee / inch ** 2)
|
242 |
+
|
243 |
+
SI.set_quantity_dimension(mmHg, pressure)
|
244 |
+
SI.set_quantity_scale_factor(mmHg, dHg0 * acceleration_due_to_gravity * kilogram / meter**2)
|
245 |
+
|
246 |
+
SI.set_quantity_dimension(milli_mass_unit, mass)
|
247 |
+
SI.set_quantity_scale_factor(milli_mass_unit, atomic_mass_unit/1000)
|
248 |
+
|
249 |
+
SI.set_quantity_dimension(quart, length ** 3)
|
250 |
+
SI.set_quantity_scale_factor(quart, Rational(231, 4) * inch**3)
|
251 |
+
|
252 |
+
# Other convenient units and magnitudes
|
253 |
+
|
254 |
+
SI.set_quantity_dimension(lightyear, length)
|
255 |
+
SI.set_quantity_scale_factor(lightyear, speed_of_light*julian_year)
|
256 |
+
|
257 |
+
SI.set_quantity_dimension(astronomical_unit, length)
|
258 |
+
SI.set_quantity_scale_factor(astronomical_unit, 149597870691*meter)
|
259 |
+
|
260 |
+
# Fundamental Planck units:
|
261 |
+
|
262 |
+
SI.set_quantity_dimension(planck_mass, mass)
|
263 |
+
SI.set_quantity_scale_factor(planck_mass, sqrt(hbar*speed_of_light/G))
|
264 |
+
|
265 |
+
SI.set_quantity_dimension(planck_time, time)
|
266 |
+
SI.set_quantity_scale_factor(planck_time, sqrt(hbar*G/speed_of_light**5))
|
267 |
+
|
268 |
+
SI.set_quantity_dimension(planck_temperature, temperature)
|
269 |
+
SI.set_quantity_scale_factor(planck_temperature, sqrt(hbar*speed_of_light**5/G/boltzmann**2))
|
270 |
+
|
271 |
+
SI.set_quantity_dimension(planck_length, length)
|
272 |
+
SI.set_quantity_scale_factor(planck_length, sqrt(hbar*G/speed_of_light**3))
|
273 |
+
|
274 |
+
SI.set_quantity_dimension(planck_charge, charge)
|
275 |
+
SI.set_quantity_scale_factor(planck_charge, sqrt(4*pi*electric_constant*hbar*speed_of_light))
|
276 |
+
|
277 |
+
# Derived Planck units:
|
278 |
+
|
279 |
+
SI.set_quantity_dimension(planck_area, length ** 2)
|
280 |
+
SI.set_quantity_scale_factor(planck_area, planck_length**2)
|
281 |
+
|
282 |
+
SI.set_quantity_dimension(planck_volume, length ** 3)
|
283 |
+
SI.set_quantity_scale_factor(planck_volume, planck_length**3)
|
284 |
+
|
285 |
+
SI.set_quantity_dimension(planck_momentum, mass * velocity)
|
286 |
+
SI.set_quantity_scale_factor(planck_momentum, planck_mass * speed_of_light)
|
287 |
+
|
288 |
+
SI.set_quantity_dimension(planck_energy, energy)
|
289 |
+
SI.set_quantity_scale_factor(planck_energy, planck_mass * speed_of_light**2)
|
290 |
+
|
291 |
+
SI.set_quantity_dimension(planck_force, force)
|
292 |
+
SI.set_quantity_scale_factor(planck_force, planck_energy / planck_length)
|
293 |
+
|
294 |
+
SI.set_quantity_dimension(planck_power, power)
|
295 |
+
SI.set_quantity_scale_factor(planck_power, planck_energy / planck_time)
|
296 |
+
|
297 |
+
SI.set_quantity_dimension(planck_density, mass / length ** 3)
|
298 |
+
SI.set_quantity_scale_factor(planck_density, planck_mass / planck_length**3)
|
299 |
+
|
300 |
+
SI.set_quantity_dimension(planck_energy_density, energy / length ** 3)
|
301 |
+
SI.set_quantity_scale_factor(planck_energy_density, planck_energy / planck_length**3)
|
302 |
+
|
303 |
+
SI.set_quantity_dimension(planck_intensity, mass * time ** (-3))
|
304 |
+
SI.set_quantity_scale_factor(planck_intensity, planck_energy_density * speed_of_light)
|
305 |
+
|
306 |
+
SI.set_quantity_dimension(planck_angular_frequency, 1 / time)
|
307 |
+
SI.set_quantity_scale_factor(planck_angular_frequency, 1 / planck_time)
|
308 |
+
|
309 |
+
SI.set_quantity_dimension(planck_pressure, pressure)
|
310 |
+
SI.set_quantity_scale_factor(planck_pressure, planck_force / planck_length**2)
|
311 |
+
|
312 |
+
SI.set_quantity_dimension(planck_current, current)
|
313 |
+
SI.set_quantity_scale_factor(planck_current, planck_charge / planck_time)
|
314 |
+
|
315 |
+
SI.set_quantity_dimension(planck_voltage, voltage)
|
316 |
+
SI.set_quantity_scale_factor(planck_voltage, planck_energy / planck_charge)
|
317 |
+
|
318 |
+
SI.set_quantity_dimension(planck_impedance, impedance)
|
319 |
+
SI.set_quantity_scale_factor(planck_impedance, planck_voltage / planck_current)
|
320 |
+
|
321 |
+
SI.set_quantity_dimension(planck_acceleration, acceleration)
|
322 |
+
SI.set_quantity_scale_factor(planck_acceleration, speed_of_light / planck_time)
|
323 |
+
|
324 |
+
# Older units for radioactivity
|
325 |
+
|
326 |
+
SI.set_quantity_dimension(curie, 1 / time)
|
327 |
+
SI.set_quantity_scale_factor(curie, 37000000000*becquerel)
|
328 |
+
|
329 |
+
SI.set_quantity_dimension(rutherford, 1 / time)
|
330 |
+
SI.set_quantity_scale_factor(rutherford, 1000000*becquerel)
|
331 |
+
|
332 |
+
|
333 |
+
# check that scale factors are the right SI dimensions:
|
334 |
+
for _scale_factor, _dimension in zip(
|
335 |
+
SI._quantity_scale_factors.values(),
|
336 |
+
SI._quantity_dimension_map.values()
|
337 |
+
):
|
338 |
+
dimex = SI.get_dimensional_expr(_scale_factor)
|
339 |
+
if dimex != 1:
|
340 |
+
# XXX: equivalent_dims is an instance method taking two arguments in
|
341 |
+
# addition to self so this can not work:
|
342 |
+
if not DimensionSystem.equivalent_dims(_dimension, Dimension(dimex)): # type: ignore
|
343 |
+
raise ValueError("quantity value and dimension mismatch")
|
344 |
+
del _scale_factor, _dimension
|
345 |
+
|
346 |
+
__all__ = [
|
347 |
+
'mmHg', 'atmosphere', 'inductance', 'newton', 'meter',
|
348 |
+
'vacuum_permittivity', 'pascal', 'magnetic_constant', 'voltage',
|
349 |
+
'angular_mil', 'luminous_intensity', 'all_units',
|
350 |
+
'julian_year', 'weber', 'exbibyte', 'liter',
|
351 |
+
'molar_gas_constant', 'faraday_constant', 'avogadro_constant',
|
352 |
+
'lightyear', 'planck_density', 'gee', 'mol', 'bit', 'gray',
|
353 |
+
'planck_momentum', 'bar', 'magnetic_density', 'prefix_unit', 'PREFIXES',
|
354 |
+
'planck_time', 'dimex', 'gram', 'candela', 'force', 'planck_intensity',
|
355 |
+
'energy', 'becquerel', 'planck_acceleration', 'speed_of_light',
|
356 |
+
'conductance', 'frequency', 'coulomb_constant', 'degree', 'lux', 'planck',
|
357 |
+
'current', 'planck_current', 'tebibyte', 'planck_power', 'MKSA', 'power',
|
358 |
+
'K', 'planck_volume', 'quart', 'pressure', 'amount_of_substance',
|
359 |
+
'joule', 'boltzmann_constant', 'Dimension', 'c', 'planck_force', 'length',
|
360 |
+
'watt', 'action', 'hbar', 'gibibyte', 'DimensionSystem', 'cd', 'volt',
|
361 |
+
'planck_charge', 'dioptre', 'vacuum_impedance', 'dimsys_default', 'farad',
|
362 |
+
'charge', 'gravitational_constant', 'temperature', 'u0', 'hertz',
|
363 |
+
'capacitance', 'tesla', 'steradian', 'planck_mass', 'josephson_constant',
|
364 |
+
'planck_area', 'stefan_boltzmann_constant', 'base_dims',
|
365 |
+
'astronomical_unit', 'radian', 'planck_voltage', 'impedance',
|
366 |
+
'planck_energy', 'Da', 'atomic_mass_constant', 'rutherford', 'second', 'inch',
|
367 |
+
'elementary_charge', 'SI', 'electronvolt', 'dimsys_SI', 'henry',
|
368 |
+
'planck_angular_frequency', 'ohm', 'pound', 'planck_pressure', 'G', 'psi',
|
369 |
+
'dHg0', 'von_klitzing_constant', 'planck_length', 'avogadro_number',
|
370 |
+
'mole', 'acceleration', 'information', 'planck_energy_density',
|
371 |
+
'mebibyte', 's', 'acceleration_due_to_gravity', 'electron_rest_mass',
|
372 |
+
'planck_temperature', 'units', 'mass', 'dimsys_MKSA', 'kelvin', 'kPa',
|
373 |
+
'boltzmann', 'milli_mass_unit', 'planck_impedance', 'electric_constant',
|
374 |
+
'derived_dims', 'kg', 'coulomb', 'siemens', 'byte', 'magnetic_flux',
|
375 |
+
'atomic_mass_unit', 'm', 'kibibyte', 'kilogram', 'One', 'curie', 'u',
|
376 |
+
'time', 'pebibyte', 'velocity', 'ampere', 'katal',
|
377 |
+
]
|
env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2020 Tsuyoshi Hombashi
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/METADATA
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: tcolorpy
|
3 |
+
Version: 0.1.4
|
4 |
+
Summary: tcolopy is a Python library to apply true color for terminal text.
|
5 |
+
Home-page: https://github.com/thombashi/tcolorpy
|
6 |
+
Author: Tsuyoshi Hombashi
|
7 |
+
Author-email: [email protected]
|
8 |
+
License: MIT License
|
9 |
+
Project-URL: Source, https://github.com/thombashi/tcolorpy
|
10 |
+
Project-URL: Tracker, https://github.com/thombashi/tcolorpy/issues
|
11 |
+
Keywords: ANSI escape,terminal color,truecolor
|
12 |
+
Classifier: Development Status :: 4 - Beta
|
13 |
+
Classifier: Intended Audience :: Information Technology
|
14 |
+
Classifier: License :: OSI Approved :: MIT License
|
15 |
+
Classifier: Operating System :: OS Independent
|
16 |
+
Classifier: Programming Language :: Python :: 3
|
17 |
+
Classifier: Programming Language :: Python :: 3.7
|
18 |
+
Classifier: Programming Language :: Python :: 3.8
|
19 |
+
Classifier: Programming Language :: Python :: 3.9
|
20 |
+
Classifier: Programming Language :: Python :: 3.10
|
21 |
+
Classifier: Programming Language :: Python :: 3.11
|
22 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
23 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
24 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
25 |
+
Classifier: Topic :: Software Development :: Libraries
|
26 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
27 |
+
Classifier: Topic :: Terminals
|
28 |
+
Classifier: Topic :: Text Processing
|
29 |
+
Requires-Python: >=3.7
|
30 |
+
Description-Content-Type: text/x-rst
|
31 |
+
License-File: LICENSE
|
32 |
+
Provides-Extra: test
|
33 |
+
Requires-Dist: pytest >=6.0.1 ; extra == 'test'
|
34 |
+
Requires-Dist: pytest-md-report >=0.4.1 ; extra == 'test'
|
35 |
+
|
36 |
+
.. contents:: **tcolorpy**
|
37 |
+
:backlinks: top
|
38 |
+
:depth: 2
|
39 |
+
|
40 |
+
|
41 |
+
Summary
|
42 |
+
============================================
|
43 |
+
tcolopy is a Python library to apply true color for terminal text.
|
44 |
+
|
45 |
+
.. image:: https://badge.fury.io/py/tcolorpy.svg
|
46 |
+
:target: https://badge.fury.io/py/tcolorpy
|
47 |
+
:alt: PyPI package version
|
48 |
+
|
49 |
+
.. image:: https://anaconda.org/conda-forge/tcolorpy/badges/version.svg
|
50 |
+
:target: https://anaconda.org/conda-forge/tcolorpy
|
51 |
+
:alt: conda-forge package version
|
52 |
+
|
53 |
+
.. image:: https://img.shields.io/pypi/pyversions/tcolorpy.svg
|
54 |
+
:target: https://pypi.org/project/tcolorpy
|
55 |
+
:alt: Supported Python versions
|
56 |
+
|
57 |
+
.. image:: https://img.shields.io/pypi/implementation/tcolorpy.svg
|
58 |
+
:target: https://pypi.org/project/tcolorpy
|
59 |
+
:alt: Supported Python implementations
|
60 |
+
|
61 |
+
.. image:: https://github.com/thombashi/tcolorpy/workflows/Tests/badge.svg
|
62 |
+
:target: https://github.com/thombashi/tcolorpy/actions?query=workflow%3ATests
|
63 |
+
:alt: Linux/macOS/Windows CI status
|
64 |
+
|
65 |
+
.. image:: https://coveralls.io/repos/github/thombashi/tcolorpy/badge.svg?branch=master
|
66 |
+
:target: https://coveralls.io/github/thombashi/tcolorpy?branch=master
|
67 |
+
:alt: Test coverage: coveralls
|
68 |
+
|
69 |
+
|
70 |
+
Installation
|
71 |
+
============================================
|
72 |
+
|
73 |
+
Installation: pip
|
74 |
+
------------------------------
|
75 |
+
::
|
76 |
+
|
77 |
+
pip install tcolorpy
|
78 |
+
|
79 |
+
Installation: conda
|
80 |
+
------------------------------
|
81 |
+
::
|
82 |
+
|
83 |
+
conda install -c conda-forge tcolorpy
|
84 |
+
|
85 |
+
|
86 |
+
Usage
|
87 |
+
============================================
|
88 |
+
|
89 |
+
Library usage
|
90 |
+
--------------------------------------------
|
91 |
+
|
92 |
+
:Sample Code:
|
93 |
+
.. code-block:: python
|
94 |
+
|
95 |
+
from tcolorpy import tcolor
|
96 |
+
|
97 |
+
print(tcolor("tcolopy example", color="#ee1177", styles=["bold", "italic", "underline"]))
|
98 |
+
|
99 |
+
:Output:
|
100 |
+
.. figure:: https://cdn.jsdelivr.net/gh/thombashi/tcolorpy@master/ss/oneline.png
|
101 |
+
:scale: 60%
|
102 |
+
:alt: https://github.com/thombashi/tcolorpy/blob/master/ss/oneline.png
|
103 |
+
|
104 |
+
You can set the following ``tcolor`` arguments:
|
105 |
+
|
106 |
+
- ``color``/``bg_color``
|
107 |
+
- color names (``"red"``, ``"green"``, etc.) or color code (``"#RRGGBB"``)
|
108 |
+
- ``styles``
|
109 |
+
- ``"bold"``, ``"italic"``, etc.
|
110 |
+
|
111 |
+
|
112 |
+
Other examples
|
113 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
114 |
+
Apply true color and styles to text:
|
115 |
+
|
116 |
+
.. figure:: https://cdn.jsdelivr.net/gh/thombashi/tcolorpy@master/ss/styles.png
|
117 |
+
:scale: 60%
|
118 |
+
:alt: https://github.com/thombashi/tcolorpy/blob/master/ss/styles.png
|
119 |
+
|
120 |
+
`example source code <https://github.com/thombashi/tcolorpy/blob/master/examples/ansi_styles.py>`__
|
121 |
+
|
122 |
+
You can also specify colors by name:
|
123 |
+
|
124 |
+
.. figure:: https://cdn.jsdelivr.net/gh/thombashi/tcolorpy@master/ss/ansi_colors.png
|
125 |
+
:scale: 60%
|
126 |
+
:alt: https://github.com/thombashi/tcolorpy/blob/master/ss/ansi_colors.png
|
127 |
+
|
128 |
+
`example source code <https://github.com/thombashi/tcolorpy/blob/master/examples/ansi_colors.py>`__
|
129 |
+
|
130 |
+
|
131 |
+
CLI usage
|
132 |
+
--------------------------------------------
|
133 |
+
``tcolorpy`` can be used via CLI:
|
134 |
+
|
135 |
+
::
|
136 |
+
|
137 |
+
$ python3 -m tcolorpy "tcolopy example" -c "#ee1177" -s bold,italic,underline
|
138 |
+
|
139 |
+
Command help
|
140 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
141 |
+
::
|
142 |
+
|
143 |
+
usage: __main__.py [-h] [-c COLOR] [-b BG_COLOR] [-s STYLES] [--encode ENCODE] string
|
144 |
+
|
145 |
+
positional arguments:
|
146 |
+
string string to apply styles.
|
147 |
+
|
148 |
+
options:
|
149 |
+
-h, --help show this help message and exit
|
150 |
+
-c COLOR, --color COLOR
|
151 |
+
specify a color code (#XXXXXX) or a name. valid names are: black, red, green, yellow, blue, magenta, cyan, white, lightblack, lightred, lightgreen, lightyellow, lightblue, lightmagenta, lightcyan, lightwhite
|
152 |
+
-b BG_COLOR, --bg-color BG_COLOR
|
153 |
+
specify a background color code (#XXXXXX) or a name. valid names are: black, red, green, yellow, blue, magenta, cyan, white, lightblack, lightred, lightgreen, lightyellow, lightblue, lightmagenta, lightcyan, lightwhite
|
154 |
+
-s STYLES, --styles STYLES
|
155 |
+
specify a comma-separated style. valid values are: bold, dim, italic, underline, blink, invert, strike
|
156 |
+
--encode ENCODE output a text encoded with the specified encoding
|
157 |
+
|
158 |
+
|
159 |
+
Dependencies
|
160 |
+
============================================
|
161 |
+
Python 3.7+
|
162 |
+
no external dependencies.
|
env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/RECORD
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
tcolorpy-0.1.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
tcolorpy-0.1.4.dist-info/LICENSE,sha256=9BoEVtXyu6Jf1NflC1GpXeMEdw_x21p5UV0DOXqRTY0,1074
|
3 |
+
tcolorpy-0.1.4.dist-info/METADATA,sha256=rFyw79V_YbDAiIAncjF7kdjKdHq0v7CJAlcy0ImSQFw,5716
|
4 |
+
tcolorpy-0.1.4.dist-info/RECORD,,
|
5 |
+
tcolorpy-0.1.4.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
|
6 |
+
tcolorpy-0.1.4.dist-info/top_level.txt,sha256=g8LDaQz0FVP61jibPz7OTwQqiseVV9pxUYDeGp2lFAI,9
|
7 |
+
tcolorpy/__init__.py,sha256=729PMIfmOYicXFInfS4Uml-uA17tRllqPJ1ZFmSsIQ0,705
|
8 |
+
tcolorpy/__main__.py,sha256=gjNpi78hE-X6CpY20ZLMmQ_yaWYIh_eOu2XrLnoGkBE,1701
|
9 |
+
tcolorpy/__pycache__/__init__.cpython-310.pyc,,
|
10 |
+
tcolorpy/__pycache__/__main__.cpython-310.pyc,,
|
11 |
+
tcolorpy/__pycache__/__version__.cpython-310.pyc,,
|
12 |
+
tcolorpy/__pycache__/_const.cpython-310.pyc,,
|
13 |
+
tcolorpy/__pycache__/_truecolor.cpython-310.pyc,,
|
14 |
+
tcolorpy/__version__.py,sha256=uzTkOQkPBiZDuqTer6QpBlWsMYzrB5PZ-7rn53qkbaQ,201
|
15 |
+
tcolorpy/_const.py,sha256=XS2rzsxY7SKxg0HreYTR_kEGeSi_59gOrrntI2_kG1o,1080
|
16 |
+
tcolorpy/_truecolor.py,sha256=nzu2GCc6Tu_4no5_Qcksm88-Vm75sCdeOMDQHG_2DhM,7495
|
17 |
+
tcolorpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/WHEEL
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.41.2)
|
3 |
+
Root-Is-Purelib: true
|
4 |
+
Tag: py3-none-any
|
5 |
+
|
env-llmeval/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
tcolorpy
|
env-llmeval/lib/python3.10/site-packages/yaml/__init__.py
ADDED
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from .error import *
|
3 |
+
|
4 |
+
from .tokens import *
|
5 |
+
from .events import *
|
6 |
+
from .nodes import *
|
7 |
+
|
8 |
+
from .loader import *
|
9 |
+
from .dumper import *
|
10 |
+
|
11 |
+
__version__ = '6.0.1'
|
12 |
+
try:
|
13 |
+
from .cyaml import *
|
14 |
+
__with_libyaml__ = True
|
15 |
+
except ImportError:
|
16 |
+
__with_libyaml__ = False
|
17 |
+
|
18 |
+
import io
|
19 |
+
|
20 |
+
#------------------------------------------------------------------------------
|
21 |
+
# XXX "Warnings control" is now deprecated. Leaving in the API function to not
|
22 |
+
# break code that uses it.
|
23 |
+
#------------------------------------------------------------------------------
|
24 |
+
def warnings(settings=None):
|
25 |
+
if settings is None:
|
26 |
+
return {}
|
27 |
+
|
28 |
+
#------------------------------------------------------------------------------
|
29 |
+
def scan(stream, Loader=Loader):
|
30 |
+
"""
|
31 |
+
Scan a YAML stream and produce scanning tokens.
|
32 |
+
"""
|
33 |
+
loader = Loader(stream)
|
34 |
+
try:
|
35 |
+
while loader.check_token():
|
36 |
+
yield loader.get_token()
|
37 |
+
finally:
|
38 |
+
loader.dispose()
|
39 |
+
|
40 |
+
def parse(stream, Loader=Loader):
|
41 |
+
"""
|
42 |
+
Parse a YAML stream and produce parsing events.
|
43 |
+
"""
|
44 |
+
loader = Loader(stream)
|
45 |
+
try:
|
46 |
+
while loader.check_event():
|
47 |
+
yield loader.get_event()
|
48 |
+
finally:
|
49 |
+
loader.dispose()
|
50 |
+
|
51 |
+
def compose(stream, Loader=Loader):
|
52 |
+
"""
|
53 |
+
Parse the first YAML document in a stream
|
54 |
+
and produce the corresponding representation tree.
|
55 |
+
"""
|
56 |
+
loader = Loader(stream)
|
57 |
+
try:
|
58 |
+
return loader.get_single_node()
|
59 |
+
finally:
|
60 |
+
loader.dispose()
|
61 |
+
|
62 |
+
def compose_all(stream, Loader=Loader):
|
63 |
+
"""
|
64 |
+
Parse all YAML documents in a stream
|
65 |
+
and produce corresponding representation trees.
|
66 |
+
"""
|
67 |
+
loader = Loader(stream)
|
68 |
+
try:
|
69 |
+
while loader.check_node():
|
70 |
+
yield loader.get_node()
|
71 |
+
finally:
|
72 |
+
loader.dispose()
|
73 |
+
|
74 |
+
def load(stream, Loader):
|
75 |
+
"""
|
76 |
+
Parse the first YAML document in a stream
|
77 |
+
and produce the corresponding Python object.
|
78 |
+
"""
|
79 |
+
loader = Loader(stream)
|
80 |
+
try:
|
81 |
+
return loader.get_single_data()
|
82 |
+
finally:
|
83 |
+
loader.dispose()
|
84 |
+
|
85 |
+
def load_all(stream, Loader):
|
86 |
+
"""
|
87 |
+
Parse all YAML documents in a stream
|
88 |
+
and produce corresponding Python objects.
|
89 |
+
"""
|
90 |
+
loader = Loader(stream)
|
91 |
+
try:
|
92 |
+
while loader.check_data():
|
93 |
+
yield loader.get_data()
|
94 |
+
finally:
|
95 |
+
loader.dispose()
|
96 |
+
|
97 |
+
def full_load(stream):
|
98 |
+
"""
|
99 |
+
Parse the first YAML document in a stream
|
100 |
+
and produce the corresponding Python object.
|
101 |
+
|
102 |
+
Resolve all tags except those known to be
|
103 |
+
unsafe on untrusted input.
|
104 |
+
"""
|
105 |
+
return load(stream, FullLoader)
|
106 |
+
|
107 |
+
def full_load_all(stream):
|
108 |
+
"""
|
109 |
+
Parse all YAML documents in a stream
|
110 |
+
and produce corresponding Python objects.
|
111 |
+
|
112 |
+
Resolve all tags except those known to be
|
113 |
+
unsafe on untrusted input.
|
114 |
+
"""
|
115 |
+
return load_all(stream, FullLoader)
|
116 |
+
|
117 |
+
def safe_load(stream):
|
118 |
+
"""
|
119 |
+
Parse the first YAML document in a stream
|
120 |
+
and produce the corresponding Python object.
|
121 |
+
|
122 |
+
Resolve only basic YAML tags. This is known
|
123 |
+
to be safe for untrusted input.
|
124 |
+
"""
|
125 |
+
return load(stream, SafeLoader)
|
126 |
+
|
127 |
+
def safe_load_all(stream):
|
128 |
+
"""
|
129 |
+
Parse all YAML documents in a stream
|
130 |
+
and produce corresponding Python objects.
|
131 |
+
|
132 |
+
Resolve only basic YAML tags. This is known
|
133 |
+
to be safe for untrusted input.
|
134 |
+
"""
|
135 |
+
return load_all(stream, SafeLoader)
|
136 |
+
|
137 |
+
def unsafe_load(stream):
|
138 |
+
"""
|
139 |
+
Parse the first YAML document in a stream
|
140 |
+
and produce the corresponding Python object.
|
141 |
+
|
142 |
+
Resolve all tags, even those known to be
|
143 |
+
unsafe on untrusted input.
|
144 |
+
"""
|
145 |
+
return load(stream, UnsafeLoader)
|
146 |
+
|
147 |
+
def unsafe_load_all(stream):
|
148 |
+
"""
|
149 |
+
Parse all YAML documents in a stream
|
150 |
+
and produce corresponding Python objects.
|
151 |
+
|
152 |
+
Resolve all tags, even those known to be
|
153 |
+
unsafe on untrusted input.
|
154 |
+
"""
|
155 |
+
return load_all(stream, UnsafeLoader)
|
156 |
+
|
157 |
+
def emit(events, stream=None, Dumper=Dumper,
|
158 |
+
canonical=None, indent=None, width=None,
|
159 |
+
allow_unicode=None, line_break=None):
|
160 |
+
"""
|
161 |
+
Emit YAML parsing events into a stream.
|
162 |
+
If stream is None, return the produced string instead.
|
163 |
+
"""
|
164 |
+
getvalue = None
|
165 |
+
if stream is None:
|
166 |
+
stream = io.StringIO()
|
167 |
+
getvalue = stream.getvalue
|
168 |
+
dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
|
169 |
+
allow_unicode=allow_unicode, line_break=line_break)
|
170 |
+
try:
|
171 |
+
for event in events:
|
172 |
+
dumper.emit(event)
|
173 |
+
finally:
|
174 |
+
dumper.dispose()
|
175 |
+
if getvalue:
|
176 |
+
return getvalue()
|
177 |
+
|
178 |
+
def serialize_all(nodes, stream=None, Dumper=Dumper,
|
179 |
+
canonical=None, indent=None, width=None,
|
180 |
+
allow_unicode=None, line_break=None,
|
181 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
182 |
+
version=None, tags=None):
|
183 |
+
"""
|
184 |
+
Serialize a sequence of representation trees into a YAML stream.
|
185 |
+
If stream is None, return the produced string instead.
|
186 |
+
"""
|
187 |
+
getvalue = None
|
188 |
+
if stream is None:
|
189 |
+
if encoding is None:
|
190 |
+
stream = io.StringIO()
|
191 |
+
else:
|
192 |
+
stream = io.BytesIO()
|
193 |
+
getvalue = stream.getvalue
|
194 |
+
dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
|
195 |
+
allow_unicode=allow_unicode, line_break=line_break,
|
196 |
+
encoding=encoding, version=version, tags=tags,
|
197 |
+
explicit_start=explicit_start, explicit_end=explicit_end)
|
198 |
+
try:
|
199 |
+
dumper.open()
|
200 |
+
for node in nodes:
|
201 |
+
dumper.serialize(node)
|
202 |
+
dumper.close()
|
203 |
+
finally:
|
204 |
+
dumper.dispose()
|
205 |
+
if getvalue:
|
206 |
+
return getvalue()
|
207 |
+
|
208 |
+
def serialize(node, stream=None, Dumper=Dumper, **kwds):
|
209 |
+
"""
|
210 |
+
Serialize a representation tree into a YAML stream.
|
211 |
+
If stream is None, return the produced string instead.
|
212 |
+
"""
|
213 |
+
return serialize_all([node], stream, Dumper=Dumper, **kwds)
|
214 |
+
|
215 |
+
def dump_all(documents, stream=None, Dumper=Dumper,
|
216 |
+
default_style=None, default_flow_style=False,
|
217 |
+
canonical=None, indent=None, width=None,
|
218 |
+
allow_unicode=None, line_break=None,
|
219 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
220 |
+
version=None, tags=None, sort_keys=True):
|
221 |
+
"""
|
222 |
+
Serialize a sequence of Python objects into a YAML stream.
|
223 |
+
If stream is None, return the produced string instead.
|
224 |
+
"""
|
225 |
+
getvalue = None
|
226 |
+
if stream is None:
|
227 |
+
if encoding is None:
|
228 |
+
stream = io.StringIO()
|
229 |
+
else:
|
230 |
+
stream = io.BytesIO()
|
231 |
+
getvalue = stream.getvalue
|
232 |
+
dumper = Dumper(stream, default_style=default_style,
|
233 |
+
default_flow_style=default_flow_style,
|
234 |
+
canonical=canonical, indent=indent, width=width,
|
235 |
+
allow_unicode=allow_unicode, line_break=line_break,
|
236 |
+
encoding=encoding, version=version, tags=tags,
|
237 |
+
explicit_start=explicit_start, explicit_end=explicit_end, sort_keys=sort_keys)
|
238 |
+
try:
|
239 |
+
dumper.open()
|
240 |
+
for data in documents:
|
241 |
+
dumper.represent(data)
|
242 |
+
dumper.close()
|
243 |
+
finally:
|
244 |
+
dumper.dispose()
|
245 |
+
if getvalue:
|
246 |
+
return getvalue()
|
247 |
+
|
248 |
+
def dump(data, stream=None, Dumper=Dumper, **kwds):
|
249 |
+
"""
|
250 |
+
Serialize a Python object into a YAML stream.
|
251 |
+
If stream is None, return the produced string instead.
|
252 |
+
"""
|
253 |
+
return dump_all([data], stream, Dumper=Dumper, **kwds)
|
254 |
+
|
255 |
+
def safe_dump_all(documents, stream=None, **kwds):
|
256 |
+
"""
|
257 |
+
Serialize a sequence of Python objects into a YAML stream.
|
258 |
+
Produce only basic YAML tags.
|
259 |
+
If stream is None, return the produced string instead.
|
260 |
+
"""
|
261 |
+
return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
|
262 |
+
|
263 |
+
def safe_dump(data, stream=None, **kwds):
|
264 |
+
"""
|
265 |
+
Serialize a Python object into a YAML stream.
|
266 |
+
Produce only basic YAML tags.
|
267 |
+
If stream is None, return the produced string instead.
|
268 |
+
"""
|
269 |
+
return dump_all([data], stream, Dumper=SafeDumper, **kwds)
|
270 |
+
|
271 |
+
def add_implicit_resolver(tag, regexp, first=None,
|
272 |
+
Loader=None, Dumper=Dumper):
|
273 |
+
"""
|
274 |
+
Add an implicit scalar detector.
|
275 |
+
If an implicit scalar value matches the given regexp,
|
276 |
+
the corresponding tag is assigned to the scalar.
|
277 |
+
first is a sequence of possible initial characters or None.
|
278 |
+
"""
|
279 |
+
if Loader is None:
|
280 |
+
loader.Loader.add_implicit_resolver(tag, regexp, first)
|
281 |
+
loader.FullLoader.add_implicit_resolver(tag, regexp, first)
|
282 |
+
loader.UnsafeLoader.add_implicit_resolver(tag, regexp, first)
|
283 |
+
else:
|
284 |
+
Loader.add_implicit_resolver(tag, regexp, first)
|
285 |
+
Dumper.add_implicit_resolver(tag, regexp, first)
|
286 |
+
|
287 |
+
def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=Dumper):
|
288 |
+
"""
|
289 |
+
Add a path based resolver for the given tag.
|
290 |
+
A path is a list of keys that forms a path
|
291 |
+
to a node in the representation tree.
|
292 |
+
Keys can be string values, integers, or None.
|
293 |
+
"""
|
294 |
+
if Loader is None:
|
295 |
+
loader.Loader.add_path_resolver(tag, path, kind)
|
296 |
+
loader.FullLoader.add_path_resolver(tag, path, kind)
|
297 |
+
loader.UnsafeLoader.add_path_resolver(tag, path, kind)
|
298 |
+
else:
|
299 |
+
Loader.add_path_resolver(tag, path, kind)
|
300 |
+
Dumper.add_path_resolver(tag, path, kind)
|
301 |
+
|
302 |
+
def add_constructor(tag, constructor, Loader=None):
|
303 |
+
"""
|
304 |
+
Add a constructor for the given tag.
|
305 |
+
Constructor is a function that accepts a Loader instance
|
306 |
+
and a node object and produces the corresponding Python object.
|
307 |
+
"""
|
308 |
+
if Loader is None:
|
309 |
+
loader.Loader.add_constructor(tag, constructor)
|
310 |
+
loader.FullLoader.add_constructor(tag, constructor)
|
311 |
+
loader.UnsafeLoader.add_constructor(tag, constructor)
|
312 |
+
else:
|
313 |
+
Loader.add_constructor(tag, constructor)
|
314 |
+
|
315 |
+
def add_multi_constructor(tag_prefix, multi_constructor, Loader=None):
|
316 |
+
"""
|
317 |
+
Add a multi-constructor for the given tag prefix.
|
318 |
+
Multi-constructor is called for a node if its tag starts with tag_prefix.
|
319 |
+
Multi-constructor accepts a Loader instance, a tag suffix,
|
320 |
+
and a node object and produces the corresponding Python object.
|
321 |
+
"""
|
322 |
+
if Loader is None:
|
323 |
+
loader.Loader.add_multi_constructor(tag_prefix, multi_constructor)
|
324 |
+
loader.FullLoader.add_multi_constructor(tag_prefix, multi_constructor)
|
325 |
+
loader.UnsafeLoader.add_multi_constructor(tag_prefix, multi_constructor)
|
326 |
+
else:
|
327 |
+
Loader.add_multi_constructor(tag_prefix, multi_constructor)
|
328 |
+
|
329 |
+
def add_representer(data_type, representer, Dumper=Dumper):
|
330 |
+
"""
|
331 |
+
Add a representer for the given type.
|
332 |
+
Representer is a function accepting a Dumper instance
|
333 |
+
and an instance of the given data type
|
334 |
+
and producing the corresponding representation node.
|
335 |
+
"""
|
336 |
+
Dumper.add_representer(data_type, representer)
|
337 |
+
|
338 |
+
def add_multi_representer(data_type, multi_representer, Dumper=Dumper):
|
339 |
+
"""
|
340 |
+
Add a representer for the given type.
|
341 |
+
Multi-representer is a function accepting a Dumper instance
|
342 |
+
and an instance of the given data type or subtype
|
343 |
+
and producing the corresponding representation node.
|
344 |
+
"""
|
345 |
+
Dumper.add_multi_representer(data_type, multi_representer)
|
346 |
+
|
347 |
+
class YAMLObjectMetaclass(type):
|
348 |
+
"""
|
349 |
+
The metaclass for YAMLObject.
|
350 |
+
"""
|
351 |
+
def __init__(cls, name, bases, kwds):
|
352 |
+
super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
|
353 |
+
if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
|
354 |
+
if isinstance(cls.yaml_loader, list):
|
355 |
+
for loader in cls.yaml_loader:
|
356 |
+
loader.add_constructor(cls.yaml_tag, cls.from_yaml)
|
357 |
+
else:
|
358 |
+
cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml)
|
359 |
+
|
360 |
+
cls.yaml_dumper.add_representer(cls, cls.to_yaml)
|
361 |
+
|
362 |
+
class YAMLObject(metaclass=YAMLObjectMetaclass):
|
363 |
+
"""
|
364 |
+
An object that can dump itself to a YAML stream
|
365 |
+
and load itself from a YAML stream.
|
366 |
+
"""
|
367 |
+
|
368 |
+
__slots__ = () # no direct instantiation, so allow immutable subclasses
|
369 |
+
|
370 |
+
yaml_loader = [Loader, FullLoader, UnsafeLoader]
|
371 |
+
yaml_dumper = Dumper
|
372 |
+
|
373 |
+
yaml_tag = None
|
374 |
+
yaml_flow_style = None
|
375 |
+
|
376 |
+
@classmethod
|
377 |
+
def from_yaml(cls, loader, node):
|
378 |
+
"""
|
379 |
+
Convert a representation node to a Python object.
|
380 |
+
"""
|
381 |
+
return loader.construct_yaml_object(node, cls)
|
382 |
+
|
383 |
+
@classmethod
|
384 |
+
def to_yaml(cls, dumper, data):
|
385 |
+
"""
|
386 |
+
Convert a Python object to a representation node.
|
387 |
+
"""
|
388 |
+
return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
|
389 |
+
flow_style=cls.yaml_flow_style)
|
390 |
+
|
env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (10.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/composer.cpython-310.pyc
ADDED
Binary file (3.61 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/constructor.cpython-310.pyc
ADDED
Binary file (20.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/cyaml.cpython-310.pyc
ADDED
Binary file (2.87 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/dumper.cpython-310.pyc
ADDED
Binary file (1.52 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/emitter.cpython-310.pyc
ADDED
Binary file (25.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/error.cpython-310.pyc
ADDED
Binary file (2.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/yaml/__pycache__/events.cpython-310.pyc
ADDED
Binary file (3.81 kB). View file
|
|