pax_global_header00006660000000000000000000000064124063412010014503gustar00rootroot0000000000000052 comment=58734a5aec563600fa8d82fb48ea9d6b8e26556c libfte-0.1.0/000077500000000000000000000000001240634120100127465ustar00rootroot00000000000000libfte-0.1.0/.gitignore000066400000000000000000000001011240634120100147260ustar00rootroot00000000000000*.pyc *.so *.swp build doc/build fte.egg-info thirdparty/re2/obj libfte-0.1.0/.travis.yml000066400000000000000000000004261240634120100150610ustar00rootroot00000000000000language: - python - cpp compiler: - gcc - clang before_install: - sudo apt-get update -qq - sudo apt-get install -y libgmp-dev python: - "2.6" - "2.7" install: - "pip install -r requirements.txt" - "python setup.py build" script: - "python setup.py test" libfte-0.1.0/BUILDING.md000066400000000000000000000023031240634120100144630ustar00rootroot00000000000000libfte Build Instructions =========================== Ubuntu/Debian ------------- Install the following packages. ``` sudo apt-get install python-dev python-pip libgmp-dev git sudo pip install crypto ``` Then, clone and build libfte. ``` git clone https://github.com/kpdyer/libfte.git cd libfte sudo python setup.py install ``` OSX --- Install homebrew [1], if you don't have it already. ``` ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)" ``` Install the following packages. ``` brew install --build-from-source python gmp git sudo pip install --upgrade crypto ``` Then, clone and build libfte. ``` git clone https://github.com/kpdyer/libfte.git cd libfte sudo python setup.py install ``` Note: if on OSX 10.9, you may experience a ```clang: warning: argument unused during compilation: '-mno-fused-madd'``` error. This can be resolved by setting the following evnironmental variables: ``` export CFLAGS=-Qunused-arguments export CPPFLAGS=-Qunused-arguments ``` Windows ------- If you must build libfte on Windows, please see [2] for guidance. ### References * [1] http://brew.sh/ * [2] https://github.com/kpdyer/libfte-builder/blob/master/build/windows-i386/build_libfte.sh libfte-0.1.0/LICENSE000066400000000000000000000260731240634120100137630ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.libfte-0.1.0/MANIFEST.in000066400000000000000000000002021240634120100144760ustar00rootroot00000000000000recursive-include examples * recursive-include thirdparty * include Makefile include fte/VERSION include fte/*.cc include fte/*.h libfte-0.1.0/README000066400000000000000000000013671240634120100136350ustar00rootroot00000000000000Requires: GMP 5.1.x (https://gmplib.org/), PyCrypto (https://www.dlitz.net/software/pycrypto/) Format-Transforming Encryption (FTE) is a cryptographic primitive explored in the paper *Protocol Misidentification Made Easy with Format-Transforming Encryption* [1]. FTE allows a user to specify the format of their ouput ciphertexts using regular expressions. The libfte library implements the primitive presented in [1]. If you are interested in the *proxy system* that uses FTE to bypass DPI systems, please see fteproxy (https://github.com/kpdyer/fteproxy). [1] Protocol Misidentification Made Easy with Format-Transforming Encryption, Kevin P. Dyer, Scott E. Coull, Thomas Ristenpart and Thomas Shrimpton, https://kpdyer.com/publications/ccs2013-fte.pdf libfte-0.1.0/README.md000066400000000000000000000041551240634120100142320ustar00rootroot00000000000000libfte ====== [![Build Status](https://travis-ci.org/kpdyer/libfte.svg?branch=master)](https://travis-ci.org/kpdyer/libfte) Overview -------- Format-Transforming Encryption (FTE) is a cryptographic primitive explored in the paper *Protocol Misidentification Made Easy with Format-Transforming Encryption* [1]. FTE allows a user to specify the format of their ouput ciphertexts using regular expressions. The libfte library implements the primitive presented in [1]. If you are interested in the *proxy system* that uses FTE to bypass DPI systems, please see [fteproxy](https://github.com/kpdyer/fteproxy). Dependencies ------------ * Build tools (e.g., gcc, g++, etc.) * Python 2.6.x/2.7.x (https://python.org/) * GMP 5.1.x (https://gmplib.org/) * PyCrypto 2.6.x (https://www.dlitz.net/software/pycrypto/) Installation --------------------- To install libfte as a python module, please do the following: ``` python setup.py install ``` You can verify that libfte was built correctly by running: ``` python setup.py test ``` To verify that libfte was installed correctly, try running one of the scripts in the ```examples/``` directory. Example Usage ------------- The following is an example usage of libfte. ```python import fte.encoder regex = '^(a|b)+$' fixed_slice = 256 input_plaintext = 'test' fteObj = fte.encoder.RegexEncoder(regex, fixed_slice) ciphertext = fteObj.encode(input_plaintext) output_plaintext = fteObj.decode(ciphertext) print 'input_plaintext='+input_plaintext print 'ciphertext='+ciphertext[:16]+'...'+ciphertext[-16:] print 'output_plaintext='+output_plaintext ``` And the ouput of the above script would be the following, where the ouput ciphertext is a ```fixed_slice```-length string consisting of the characters ```a``` and ```b```, as defined by the ```regex``` variable. ```python input_plaintext=test ciphertext=aaaaaaaabaaaaaba...aabbbbbbbbaababb output_plaintext=test ``` References ---------- [1] [Protocol Misidentification Made Easy with Format-Transforming Encryption](https://kpdyer.com/publications/ccs2013-fte.pdf) Kevin P. Dyer, Scott E. Coull, Thomas Ristenpart and Thomas Shrimpton libfte-0.1.0/doc/000077500000000000000000000000001240634120100135135ustar00rootroot00000000000000libfte-0.1.0/doc/Makefile000066400000000000000000000130671240634120100151620ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Format-TransformingEncryptionfteproxy.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Format-TransformingEncryptionfteproxy.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Format-TransformingEncryptionFTE" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Format-TransformingEncryptionFTE" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." libfte-0.1.0/doc/make.bat000066400000000000000000000120571240634120100151250ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source set I18NSPHINXOPTS=%SPHINXOPTS% source if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Format-TransformingEncryptionfteproxy.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Format-TransformingEncryptionfteproxy.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end libfte-0.1.0/doc/source/000077500000000000000000000000001240634120100150135ustar00rootroot00000000000000libfte-0.1.0/doc/source/_static000066400000000000000000000000001240634120100163520ustar00rootroot00000000000000libfte-0.1.0/doc/source/automata.rst000066400000000000000000000004061240634120100173600ustar00rootroot00000000000000:mod:`fte.automata` Module ************************** Overview -------- This is a class used internally by fteproxy and should not be invoked directly. Interface --------- .. automodule:: fte.automata :members: :undoc-members: :show-inheritance: libfte-0.1.0/doc/source/bit_ops.rst000066400000000000000000000020401240634120100172000ustar00rootroot00000000000000:mod:`fte.bit_ops` Module ************************* Overview -------- The ``fte.bit_ops`` module is an internal module used by modules such as ``fte.encrypter`` and ``fte.encoder``. Interface --------- .. automodule:: fte.bit_ops :members: :undoc-members: :show-inheritance: Examples -------- In its simplest form, you can use the default keys to perform encryption. .. code-block:: python >>> fte.bit_ops.random_bytes(8) 'N\xa1\x1aa\x93\xe2\xda+' >>> fte.bit_ops.random_bytes(16) 'WZ\xddS\x83\x86`\xd9\x15\xe91p\xd8\xfdS\x00' >>> fte.bit_ops.random_bytes(32) '\x86\xc6Pq\xe5\xb8w@\x80=_r\x08X\x02\n\xfa^\x1f\x05\xe0\xa4\x95\xd8br\xe6\x95y\xeb\x05i' .. code-block:: python >>> fte.bit_ops.long_to_bytes(2**20) '\x10\x00\x00' >>> fte.bit_ops.long_to_bytes(2**100-1) '\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' .. code-block:: python >>> fte.bit_ops.bytes_to_long('\x10\x00\x00') mpz(1048576) >>> fte.bit_ops.bytes_to_long('\xff\xff\xff\xff') mpz(4294967295L) libfte-0.1.0/doc/source/cDFA.rst000066400000000000000000000003731240634120100163050ustar00rootroot00000000000000:mod:`fte.cDFA` Module *********************** Overview -------- This is a class used internally by fteproxy and should not be invoked directly. Interface --------- .. automodule:: fte.cDFA :members: :undoc-members: :show-inheritance: libfte-0.1.0/doc/source/conf.py000066400000000000000000000201111240634120100163050ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Format-Transforming Encryption (FTE) documentation build configuration file, created by # sphinx-quickstart on Wed Oct 23 04:52:22 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append('..') sys.path.append('../..') sys.path.append('../../..') # -- General configuration ----------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage', 'sphinx.ext.pngmath'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'fteproxy' copyright = u'2013, Kevin P. Dyer' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. with open('../../fte/VERSION') as fh: FTEPROXY_RELEASE = fh.read().strip() version = FTEPROXY_RELEASE # The full version, including alpha/beta/rc tags. release = '' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Format-TransformingEncryptionFTEdoc' # -- Options for LaTeX output -------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Format-TransformingEncryptionfteproxy.tex', u'fteproxy Documentation', u'Kevin P. Dyer', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'format-transformingencryptionfte', u'fteproxy Documentation', [u'Kevin P. Dyer'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Format-TransformingEncryptionFTE', u'fteproxy Documentation', u'Kevin P. Dyer', 'Format-TransformingEncryptionFTE', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} libfte-0.1.0/doc/source/dfa.rst000066400000000000000000000012331240634120100162760ustar00rootroot00000000000000:mod:`fte.dfa` Module *********************** Overview -------- This is a class used internally by fteproxy and should not be invoked directly. Interface --------- .. automodule:: fte.dfa :members: :undoc-members: :show-inheritance: Examples -------- .. code-block:: python >>> import fte.dfa >>> dfaObj = fte.dfa.from_regex('^(A|B)+$',16) >>> dfaObj.unrank(0) 'AAAAAAAAAAAAAAAA' >>> dfaObj.rank('AAAAAAAAAAAAAAAA') 0 .. code-block:: python >>> import fte.dfa >>> dfaObj = fte.dfa.from_regex('^(0|1)+$', 16) >>> dfaObj.unrank(2**16 - 1) '1111111111111111' >>> dfaObj.rank('1111111111111111') 65535 libfte-0.1.0/doc/source/encoder.rst000066400000000000000000000020201240634120100171560ustar00rootroot00000000000000:mod:`fte.encoder` Module ************************* Overview -------- The core class that performs encoding/decoding w.r.t. an input ``regex``. Interface --------- .. automodule:: fte.encoder :members: :undoc-members: :show-inheritance: The following is an example usage of the fte.encoder API. .. code-block:: python import fte.encoder regex = '^(a|b)+$' fixed_slice = 512 input_plaintext = 'test' fteObj = fte.encoder.RegexEncoder(regex, fixed_slice) ciphertext = fteObj.encode(input_plaintext) output_plaintext = fteObj.decode(ciphertext) print 'regex='+regex print 'fixed_slice='+str(fixed_slice) print 'input_plaintext='+input_plaintext print 'ciphertext='+ciphertext[:16]+'...'+ciphertext[-16:] print 'output_plaintext='+output_plaintext[0] The above script would result in the following output. .. code-block:: python regex=^(a|b)+$ fixed_slice=512 input_plaintext=test ciphertext=aaaaaaaaabbabbba...babbaaaaababbaab output_plaintext=test libfte-0.1.0/doc/source/encrypter.rst000066400000000000000000000042561240634120100175670ustar00rootroot00000000000000:mod:`fte.encrypter` Module *************************** Overview -------- The ``fte.encrypter`` module implements an authenticated encryption (AE) scheme designed to be used with the initial release of the Format-Transforming Encryption (FTE) Proxy. An AE scheme used with with the fteproxy proxy must have the following four properties. - Stateless - Randomized - Provably secure - Output of ``encrypt`` must be uniformly random For more details about the scheme and its design, please see https://kpdyer.com/publications/ccs2013-fte.pdf. Interface --------- .. automodule:: fte.encrypter :members: :undoc-members: Examples -------- In its simplest form, you can use the default keys to perform encryption. .. code-block:: python >>> encrypter = fte.encrypter.Encrypter() >>> C = encrypter.encrypt('Hello, World!') >>> P = encrypter.decrypt(C) >>> >>> C.encode('hex') '6705f231c062cdc75d5f358c3131bfa03ddc6f0e3bbc2ccbef9f8af74d2f164fc9f7b97f2412c787ac1e9a0407' >>> print P 'Hello, World!' Next, because the AE scheme is randomized, notice that the same input will not produce the same output. Two invocations of ``fte.encrypter.encrypt`` on the same string ``"Hello, World!`` will result in two completely different ciphertexts. .. code-block:: python >>> encrypter = fte.encrypter.Encrypter() >>> C = encrypter.encrypt('Hello, World!') >>> C.encode('hex') '37df241180b90785a203f66c0c651866de7008cf92f4bb37448a45b9c5b2eaee5575b6423d4e455fcec7387328' >>> C = encrypter.encrypt('Hello, World!') >>> C.encode('hex') 'b369b9eb369260154ca687eba71c7c188af56579bb8b3ac4f6aee646cab1e4aaf51928a18321805ea1cdfd3227' If you do wish to supply your own keys, you can may specify ``K1`` and/or ``K2`` in the construction of ``fte.encrypter.Encrypter``. .. code-block:: python >>> K1 = os.urandom(16) >>> K2 = os.urandom(16) >>> encrypter = fte.encrypter.Encrypter(K1, K2) >>> >>> K1.encode('hex') '23c5ae56db7c94e973ff10d9150293f3' >>> >>> C = encrypter.encrypt('Hello, World!') >>> C.encode('hex') '211b49ce34dc06f4284c1229dc281993c453f2b84dfad61479c5c2faf372b1ba0bdd7a5a55c9849079d152c036' libfte-0.1.0/doc/source/index.rst000066400000000000000000000007211240634120100166540ustar00rootroot00000000000000Low-Level fteproxy API ********************** The libfte module provides an implementation of Format-Transforming Encryption. Given a regular expression R, key K, and message M, it's the job of an FTE primitive to return a ciphertext C in the language L(R). Public-facing interfaces. .. toctree:: :maxdepth: 1 encoder.rst Supporting interfaces. .. toctree:: :maxdepth: 1 automata.rst bit_ops.rst dfa.rst encrypter.rst rank_unrank.rst libfte-0.1.0/examples/000077500000000000000000000000001240634120100145645ustar00rootroot00000000000000libfte-0.1.0/examples/example1.py000066400000000000000000000006611240634120100166550ustar00rootroot00000000000000import fte.encoder regex = '^(a|b)+$' fixed_slice = 512 input_plaintext = 'test' fteObj = fte.encoder.RegexEncoder(regex, fixed_slice) ciphertext = fteObj.encode(input_plaintext) output_plaintext = fteObj.decode(ciphertext) print 'regex='+regex print 'fixed_slice='+str(fixed_slice) print 'input_plaintext='+input_plaintext print 'ciphertext='+ciphertext[:16]+'...'+ciphertext[-16:] print 'output_plaintext='+output_plaintext[0] libfte-0.1.0/fte/000077500000000000000000000000001240634120100135245ustar00rootroot00000000000000libfte-0.1.0/fte/VERSION000066400000000000000000000000061240634120100145700ustar00rootroot000000000000000.1.0 libfte-0.1.0/fte/__init__.py000066400000000000000000000000001240634120100156230ustar00rootroot00000000000000libfte-0.1.0/fte/bit_ops.py000077500000000000000000000024421240634120100155420ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import binascii import Crypto.Random def random_bytes(N): """Given an input integer ``N``, ``random_bytes`` returns a string of exactly ``N`` uniformly-random bytes. """ return Crypto.Random.get_random_bytes(N) def long_to_bytes(N, blocksize=1): """Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes. If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes, such that the return values length is a multiple of ``blocksize``. """ bytestring = hex(N) bytestring = bytestring[2:] if bytestring.startswith('0x') else bytestring bytestring = bytestring[:-1] if bytestring.endswith('L') else bytestring bytestring = '0' + bytestring if (len(bytestring) % 2) != 0 else bytestring bytestring = binascii.unhexlify(bytestring) if blocksize > 0 and len(bytestring) % blocksize != 0: bytestring = '\x00' * \ (blocksize - (len(bytestring) % blocksize)) + bytestring return bytestring def bytes_to_long(bytestring): """Given a ``bytestring`` returns its integer representation ``N``. """ bytestring = '\x00' + bytestring N = int(bytestring.encode('hex'), 16) return N libfte-0.1.0/fte/cDFA.cc000077500000000000000000000170021240634120100145730ustar00rootroot00000000000000#include #include #include /* * This is a wrapper around rank_unrank.cc, to create the fte.cDFA * python module. */ // Our custom DFAObject for holding and transporting a DFA*. typedef struct { PyObject_HEAD DFA *obj; } DFAObject; // Our dealloc function for cleaning up when our fte.cDFA.DFA object is deleted. static void DFA_dealloc(PyObject* self) { DFAObject *pDFAObject = (DFAObject*)self; if (pDFAObject->obj != NULL) delete pDFAObject->obj; if (self != NULL) PyObject_Del(self); } // The wrapper for calling DFA::rank. // Takes a string as input and returns an integer. static PyObject * DFA__rank(PyObject *self, PyObject *args) { char* word; uint32_t len; if (!PyArg_ParseTuple(args, "s#", &word, &len)) return NULL; // Copy our input word into a string. // We have to do the following, because we may have NUL-bytes in our strings. const std::string str_word = std::string(word, len); // Verify our environment is sane and perform ranking. DFAObject *pDFAObject = (DFAObject*)self; if (pDFAObject->obj == NULL) return NULL; mpz_class result; try { result = pDFAObject->obj->rank(str_word); } catch (std::exception& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return 0; } // Set our c_out value uint32_t base = 10; std::string to_convert = result.get_str(base); PyObject *retval = PyLong_FromString((char*)(to_convert.c_str()), NULL, base); return retval; } // Wrapper for DFA::unrank. // On input of an integer, returns a string. static PyObject * DFA__unrank(PyObject *self, PyObject *args) { PyObject* c; if (!PyArg_ParseTuple(args, "O", &c)) return NULL; //PyNumber to mpz_class int base = 16; PyObject* b64 = PyNumber_ToBase(c, base); if (!b64) { return NULL; } const char* the_c_str = PyString_AsString(b64); if (!the_c_str) { Py_DECREF(b64); return NULL; } mpz_class to_unrank(the_c_str, 0); Py_DECREF(b64); Py_DECREF(the_c_str); // Verify our environment is sane and perform unranking. DFAObject *pDFAObject = (DFAObject*)self; if (pDFAObject->obj == NULL) return NULL; std::string result; try { result = pDFAObject->obj->unrank(to_unrank); } catch (std::exception& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return 0; } // Format our std::string as a python string and return it. PyObject* retval = Py_BuildValue("s#", result.c_str(), result.length()); return retval; } // Takes as input two integers [min, max]. // Returns the number of strings in our language that are at least // length min and no longer than length max, inclusive. static PyObject * DFA__getNumWordsInLanguage(PyObject *self, PyObject *args) { PyObject* retval; uint32_t min_val; uint32_t max_val; if (!PyArg_ParseTuple(args, "ii", &min_val, &max_val)) return NULL; // Verify our environment is sane, then call getNumWordsInLanguage. DFAObject *pDFAObject = (DFAObject*)self; if (pDFAObject->obj == NULL) return NULL; mpz_class num_words = pDFAObject->obj->getNumWordsInLanguage(min_val, max_val); // Convert the resulting integer to a string. // -- Is there a better way? uint32_t base = 10; uint32_t num_words_str_len = num_words.get_str().length(); char *num_words_str = new char[num_words_str_len + 1]; strcpy(num_words_str, num_words.get_str().c_str()); retval = PyLong_FromString(num_words_str, NULL, base); // cleanup delete [] num_words_str; return retval; } // Boilerplat python object alloc. static PyObject * DFA_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { DFAObject *self; self = (DFAObject *)type->tp_alloc(type, 0); return (PyObject *)self; } // Our initialization function for fte.cDFA.DFA // On input of a [str, int], where str is a regex, // returns an fte.cDFA.DFA object that can perform ranking/unranking // See rank_unrank.h for the significance of the input parameters. static int DFA_init(DFAObject *self, PyObject *args, PyObject *kwds) { // TODO: Figure out why the standard PyArg_ParseTuple pattern // doesn't work. // see: https://github.com/kpdyer/libfte/issues/94 //if (!PyArg_ParseTuple(args, "s#i", ®ex, &len, &max_len)) // return -1; PyObject *arg0 = PyTuple_GetItem(args, 0); if (!PyString_Check(arg0)) { PyErr_SetString(PyExc_RuntimeError, "First argument must be a string"); return 0; } const char* regex = PyString_AsString(arg0); PyObject *arg1 = PyTuple_GetItem(args, 1); if (!PyInt_Check(arg1)) { PyErr_SetString(PyExc_RuntimeError, "Second argument must be an int"); return 0; } uint32_t max_len = PyInt_AsLong(arg1); // Try to initialize our DFA object. // An exception is thrown if the input AT&T FST is not formatted as we expect. // See DFA::_validate for a list of assumptions. try { const std::string str_regex = std::string(regex); DFA *dfa = new DFA(str_regex, max_len); self->obj = dfa; } catch (std::exception& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return 0; } return 0; } // Methods in fte.cDFA.DFA static PyMethodDef DFA_methods[] = { {"rank", DFA__rank, METH_VARARGS, NULL}, {"unrank", DFA__unrank, METH_VARARGS, NULL}, {"getNumWordsInLanguage", DFA__getNumWordsInLanguage, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; // Boilerplate DFAType structure that contains the structure of the fte.cDFA.DFA type static PyTypeObject DFAType = { PyObject_HEAD_INIT(NULL) 0, "DFA", sizeof(DFAObject), 0, DFA_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ DFA_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)DFA_init, /* tp_init */ 0, /* tp_alloc */ DFA_new, /* tp_new */ 0, /* tp_free */ }; // Methods in our fte.cDFA package static PyMethodDef ftecDFAMethods[] = { {NULL, NULL, 0, NULL} }; // Main entry point for the fte.cDFA module. #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC initcDFA(void) { if (PyType_Ready(&DFAType) < 0) return; PyObject *m; m = Py_InitModule("cDFA", ftecDFAMethods); if (m == NULL) return; Py_INCREF(&DFAType); PyModule_AddObject(m, "DFA", (PyObject *)&DFAType); } libfte-0.1.0/fte/conf.py000077500000000000000000000020021240634120100150200ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys def getValue(key): return conf[key] def setValue(key, value): conf[key] = value def we_are_frozen(): # All of the modules are built-in to the interpreter, e.g., by py2exe return hasattr(sys, "frozen") def module_path(): if we_are_frozen(): return os.path.dirname(sys.executable) else: return os.path.dirname(__file__) conf = {} """The base path for the location of the fte.* modules.""" if we_are_frozen(): conf['general.base_dir'] = module_path() else: conf['general.base_dir'] = os.path.join(module_path(), '..') """The path for fte *.json definition files.""" if we_are_frozen(): conf['general.defs_dir'] = os.path.join(module_path(), 'fte', 'defs') else: conf['general.defs_dir'] = os.path.join(module_path(), '..', 'fte', 'defs') """Our loglevel = 0|1|2""" conf['runtime.loglevel'] = 1 """The default AE scheme key.""" conf['runtime.fte.encrypter.key'] = 'FF' * 16 + '00' * 16 libfte-0.1.0/fte/dfa.py000066400000000000000000000034631240634120100146360ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import math import fte.cDFA class LanguageIsEmptySetException(Exception): """Raised when the input language results in a set that is not rankable. """ pass class IntegerOutOfRangeException(Exception): pass class InvalidRegexParametersException(Exception): pass class DFA(object): def __init__(self, cDFA, fixed_slice): self._cDFA = cDFA self.fixed_slice = fixed_slice self._words_in_language = self._cDFA.getNumWordsInLanguage( 0, self.fixed_slice) self._words_in_slice = self._cDFA.getNumWordsInLanguage( self.fixed_slice, self.fixed_slice) self._offset = self._words_in_language - self._words_in_slice if self._words_in_slice == 0: raise LanguageIsEmptySetException() self._capacity = int(math.floor(math.log(self._words_in_slice, 2))) - 1 def rank(self, X): """Given a string ``X`` return ``c``, where ``c`` is the lexicographical rank of ``X`` in the language of all strings of length ``fixed_slice`` generated by ``regex``. """ retval = self._cDFA.rank(X) return retval def unrank(self, c): """The inverse of ``rank``. """ retval = self._cDFA.unrank(c) return retval def getCapacity(self): """Returns the size, in bits, of the language of our input ``regex``. Calculated as the floor of log (base 2) of the cardinality of the set of strings up to length ``fixed_slice`` in the language generated by the input ``regex``. """ return self._capacity def getNumWordsInSlice(self, n): """Returns the number of words in the language of length ``n``""" return self._cDFA.getNumWordsInLanguage(n, n) libfte-0.1.0/fte/encoder.py000077500000000000000000000131371240634120100155250ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import string import math import fte.conf import fte.bit_ops import fte.dfa import fte.encrypter class InvalidSeedLength(Exception): """Seed is not the right length.""" pass class InsufficientCapacityException(Exception): """Raised when the language doesn't have enough capacity to support a payload""" pass class InvalidInputException(Exception): """Raised when the input to ``fte.encoder.DfaEncoder.encode`` or ``fte.encoder.DfaEncoder.decode`` is not a string. """ pass class DecodeFailureError(Exception): """Raised when ``decode`` fails to properly recover a message. """ pass _instance = {} class DfaEncoder(object): """A proxy object used for caching invocations of ``DfaEncoderObject``. If a ``DfaEncoder`` is invoked twice in one process, we want to invoke ``DfaEncoderObject.__init__`` only once. """ def __new__(self, dfa, fixed_slice): global _instance if not _instance.get((dfa, fixed_slice)): _instance[(dfa, fixed_slice)] = DfaEncoderObject( dfa, fixed_slice) return _instance[(dfa, fixed_slice)] class DfaEncoderObject(object): _COVERTEXT_HEADER_LEN_PLAINTEXT = 8 _COVERTEXT_HEADER_LEN_CIPHERTTEXT = 16 def __init__(self, dfa, fixed_slice): """Constructs a new object that can be used for encoding/decoding. The value ``dfa`` is our regular language. The value ``fixed_slice`` is the subset of the language we will use for (un)ranking. That is, ``encode`` will output strings of the format ``unrank(X[:n]) || X[n:]``, where unrank(X[:n]) is always of length ``fixed_slice``. """ self._fixed_slice = fixed_slice cDFA = fte.cDFA.DFA(dfa, fixed_slice) self._dfa = fte.dfa.DFA(cDFA, self._fixed_slice) self._encrypter = fte.encrypter.Encrypter() def getCapacity(self): """Returns the size, in bits, of the language of our input ``dfa``. Calculated as the floor of log (base 2) of the cardinality of the set of strings up to length ``fixed_slice`` in the language generated by the input ``dfa``. """ return self._dfa._capacity def encode(self, X, seed=None): """Given a string ``X``, returns ``unrank(X[:n]) || X[n:]`` where ``n`` is the the maximum number of bytes that can be unranked w.r.t. the capacity of the input ``dfa`` and ``unrank`` is w.r.t. to the input ``dfa``. """ if not X: return '' if not isinstance(X, str): raise InvalidInputException('Input must be of type string.') if seed is not None and len(seed) != 8: raise InvalidSeedLength('The seed is not 8 bytes long, seed length: '+str(len(seed))) ciphertext = self._encrypter.encrypt(X) maximumBytesToRank = int(math.floor(self.getCapacity() / 8.0)) unrank_payload_len = ( maximumBytesToRank - DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT) unrank_payload_len = min(len(ciphertext), unrank_payload_len) if unrank_payload_len <= 0: raise InsufficientCapacityException('Language doesn\'t have enough capacity') msg_len_header = fte.bit_ops.long_to_bytes(unrank_payload_len) msg_len_header = string.rjust( msg_len_header, DfaEncoderObject._COVERTEXT_HEADER_LEN_PLAINTEXT, '\x00') random_bytes = seed if seed is not None else fte.bit_ops.random_bytes(8) msg_len_header = random_bytes + msg_len_header msg_len_header = self._encrypter.encryptOneBlock(msg_len_header) unrank_payload = msg_len_header + \ ciphertext[:maximumBytesToRank - DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT] random_padding_bytes = maximumBytesToRank - len(unrank_payload) if random_padding_bytes > 0: unrank_payload += fte.bit_ops.random_bytes(random_padding_bytes) unrank_payload = fte.bit_ops.bytes_to_long(unrank_payload) formatted_covertext_header = self._dfa.unrank(unrank_payload) unformatted_covertext_body = ciphertext[ maximumBytesToRank - DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT:] covertext = formatted_covertext_header + unformatted_covertext_body return covertext def decode(self, covertext): """Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. """ if not isinstance(covertext, str): raise InvalidInputException('Input must be of type string.') insufficient = (len(covertext) < self._fixed_slice) if insufficient: raise DecodeFailureError( "Covertext is shorter than self._fixed_slice, can't decode.") maximumBytesToRank = int(math.floor(self.getCapacity() / 8.0)) rank_payload = self._dfa.rank(covertext[:self._fixed_slice]) X = fte.bit_ops.long_to_bytes(rank_payload) X = string.rjust(X, maximumBytesToRank, '\x00') msg_len_header = self._encrypter.decryptOneBlock( X[:DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT]) msg_len_header = msg_len_header[8:16] msg_len = fte.bit_ops.bytes_to_long( msg_len_header[:DfaEncoderObject._COVERTEXT_HEADER_LEN_PLAINTEXT]) retval = X[16:16 + msg_len] retval += covertext[self._fixed_slice:] ctxt_len = self._encrypter.getCiphertextLen(retval) remaining_buffer = retval[ctxt_len:] retval = retval[:ctxt_len] retval = self._encrypter.decrypt(retval) return retval, remaining_buffer libfte-0.1.0/fte/encrypter.py000077500000000000000000000170701240634120100161210ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from Crypto.Cipher import AES from Crypto.Hash import HMAC from Crypto.Hash import SHA512 from Crypto.Util import Counter import fte.bit_ops class InvalidKeyLengthError(Exception): """Raised when the input key length is not the correct size. """ pass class PlaintextTypeError(Exception): """Raised when the plaintext input to encrypt is not a string. """ pass class CiphertextTypeError(Exception): """Raised when the ciphertext input to decrypt is not a string. """ pass class RecoverableDecryptionError(Exception): """Raised when a non-fatal decryption error occurs, such as attempting to decrypt a substring of a valid ciphertext. """ pass class UnrecoverableDecryptionError(Exception): """Raised when a fatal decryption error occurs, such as an invalid MAC. """ pass class Encrypter(object): """On initialization, accepts optional keys ``K1`` and ``K2`` which much be exactly 16 bytes each. Object is a stateless encryption scheme with ``encrypt`` and ``decrypt`` functions. See https://kpdyer.com/publications/ccs2013-fte.pdf for a description of the scheme. If ``K1`` is not specified, its default value is ``0xffffffffffffffffffffffffffffffff``. If ``K2`` is not specified, its default value is ``0x00000000000000000000000000000000``. """ _MAC_LENGTH = AES.block_size _IV_LENGTH = 7 _MSG_COUNTER_LENGTH = 8 _CTXT_EXPANSION = 1 + _IV_LENGTH + _MSG_COUNTER_LENGTH + _MAC_LENGTH def __init__(self, K1=None, K2=None): if K1 is not None: is_correct_length = (len(K1) == AES.block_size) if not is_correct_length: raise InvalidKeyLengthError( 'K1 must be exactly 16 bytes long.') if K2 is not None: is_correct_length = (len(K2) == AES.block_size) if not is_correct_length: raise InvalidKeyLengthError( 'K2 must be exactly 16 bytes long.') self.K1 = K1 if K1 else '\xFF' * AES.block_size self.K2 = K2 if K2 else '\x00' * AES.block_size self._ecb_enc_K1 = AES.new(self.K1, AES.MODE_ECB) self._ecb_enc_K2 = AES.new(self.K2, AES.MODE_ECB) def encrypt(self, plaintext, iv_bytes=None): """Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``. Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``. The input ``plaintext`` can be ``''``. Raises ``PlaintextTypeError`` if input plaintext is not a string. """ if not isinstance(plaintext, str): raise PlaintextTypeError("Input plaintext is not of type string") if iv_bytes is None: iv_bytes = fte.bit_ops.random_bytes(Encrypter._IV_LENGTH) iv1_bytes = '\x01' + iv_bytes iv2_bytes = '\x02' + iv_bytes W1 = iv1_bytes W1 += fte.bit_ops.long_to_bytes( len(plaintext), Encrypter._MSG_COUNTER_LENGTH) W1 = self._ecb_enc_K1.encrypt(W1) counter_length_in_bits = AES.block_size * 8 counter_val = fte.bit_ops.bytes_to_long(iv2_bytes) counter = Counter.new( counter_length_in_bits, initial_value=counter_val) ctr_enc = AES.new(key=self.K1, mode=AES.MODE_CTR, IV='\x00' * 8 + iv2_bytes, counter=counter) W2 = ctr_enc.encrypt(plaintext) mac = HMAC.new(self.K2, W1 + W2, SHA512) T = mac.digest() T = T[:Encrypter._MAC_LENGTH] ciphertext = W1 + W2 + T return ciphertext def decrypt(self, ciphertext): """Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``. Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string. Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative message length greater than the ciphertext length. Raises ``UnrecoverableDecryptionError`` if invalid padding is detected, or the the MAC is invalid. """ if not isinstance(ciphertext, str): raise CiphertextTypeError("Input ciphertext is not of type string") plaintext_length = self.getPlaintextLen(ciphertext) ciphertext_length = self.getCiphertextLen(ciphertext) ciphertext_complete = (len(ciphertext) >= ciphertext_length) if ciphertext_complete is False: raise RecoverableDecryptionError('Incomplete ciphertext: ('+str(len(ciphertext))+' of '+str(ciphertext_length)+').') ciphertext = ciphertext[:ciphertext_length] W1_start = 0 W1_end = AES.block_size W1 = ciphertext[W1_start:W1_end] W2_start = AES.block_size W2_end = AES.block_size + plaintext_length W2 = ciphertext[W2_start:W2_end] T_start = AES.block_size + plaintext_length T_end = AES.block_size + plaintext_length + Encrypter._MAC_LENGTH T_expected = ciphertext[T_start:T_end] mac = HMAC.new(self.K2, W1 + W2, SHA512) T_actual = mac.digest()[:Encrypter._MAC_LENGTH] if T_expected != T_actual: raise UnrecoverableDecryptionError('Failed to verify MAC.') iv2_bytes = '\x02' + self._ecb_enc_K1.decrypt(W1)[1:8] counter_val = fte.bit_ops.bytes_to_long(iv2_bytes) counter_length_in_bits = AES.block_size * 8 counter = Counter.new( counter_length_in_bits, initial_value=counter_val) ctr_enc = AES.new(key=self.K1, mode=AES.MODE_CTR, IV='\x00' * 8 + iv2_bytes, counter=counter) plaintext = ctr_enc.decrypt(W2) return plaintext def getCiphertextLen(self, ciphertext): """Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion. """ plaintext_length = self.getPlaintextLen(ciphertext) ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION return ciphertext_length def getPlaintextLen(self, ciphertext): """Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload. """ completeCiphertextHeader = (len(ciphertext) >= 16) if completeCiphertextHeader is False: raise RecoverableDecryptionError('Incomplete ciphertext header.') ciphertext_header = ciphertext[:16] L = self._ecb_enc_K1.decrypt(ciphertext_header) padding_expected = '\x00\x00\x00\x00' padding_actual = L[-8:-4] validPadding = (padding_actual == padding_expected) if validPadding is False: raise UnrecoverableDecryptionError( 'Invalid padding: ' + padding_actual) message_length = fte.bit_ops.bytes_to_long(L[-8:]) msgLenNonNegative = (message_length >= 0) if msgLenNonNegative is False: raise UnrecoverableDecryptionError('Negative message length.') return message_length def encryptOneBlock(self, plaintext): """Perform AES-128 ECB encryption on an 16-byte plaintext using ``K1``. """ assert len(plaintext) == 16 return self._ecb_enc_K1.encrypt(plaintext) def decryptOneBlock(self, ciphertext): """Perform AES-128 ECB decryption on a 16-byte ciphertext using ``K1``. """ assert len(ciphertext) == 16 return self._ecb_enc_K1.decrypt(ciphertext) libfte-0.1.0/fte/rank_unrank.cc000077500000000000000000000311041240634120100163460ustar00rootroot00000000000000#include #include #include #include #include /* * Please see rank_unrank.h for a detailed explantion of the * methods in this file and their purpose. */ // Helper fuction. Given a string and a token, performs a python .split() // Returns a list of string delimnated on the token array_type_string_t1 tokenize( std::string line, char delim ) { array_type_string_t1 retval; std::istringstream iss(line); std::string fragment; while(std::getline(iss, fragment, delim)) retval.push_back(fragment); return retval; } // Exceptions static class _invalid_rank_input: public std::exception { virtual const char* what() const throw() { return "Invalid rank input: ensure integer is within the correct range."; } } invalid_rank_input; static class _invalid_unrank_input: public std::exception { virtual const char* what() const throw() { return "Invalid unrank input: ensure string is exactly fixed length sizee."; } } invalid_unrank_input; static class _invalid_fst_format: public std::exception { virtual const char* what() const throw() { return "Invalid FST format."; } } invalid_fst_format; static class _invalid_fst_exception_state_name: public std::exception { virtual const char* what() const throw() { return "Invalid DFA format: DFA has N states, and a state that is not in the range 0,1,...,N-1."; } } invalid_fst_exception_state_name; static class _invalid_fst_exception_symbol_name: public std::exception { virtual const char* what() const throw() { return "Invalid DFA format: DFA has symbol that is not in the range 0,1,...,255."; } } invalid_fst_exception_symbol_name; static class _invalid_input_exception_not_in_final_states: public std::exception { virtual const char* what() const throw() { return "Please verify your input, the string does not result in an accepting path in the DFA."; } } invalid_input_exception_not_in_final_states; static class _symbol_not_in_sigma: public std::exception { virtual const char* what() const throw() { return "Please verify your input, it contains a symbol not in the sigma of the DFA."; } } symbol_not_in_sigma; /* * Parameters: * dfa_str: a minimized ATT FST formatted DFA, see: http://www2.research.att.com/~fsmtools/fsm/man4/fsm.5.html * max_len: the maxium length to compute DFA::buildTable */ DFA::DFA(const std::string dfa_str, const uint32_t max_len) : _fixed_slice(max_len), _start_state(0), _num_states(0), _num_symbols(0) { // construct the _start_state, _final_states and symbols/states of our DFA bool startStateIsntSet = true; std::string line; std::istringstream my_str_stream(dfa_str); while ( getline (my_str_stream,line) ) { if (line.empty()) break; array_type_string_t1 split_vec = tokenize( line, '\t' ); if (split_vec.size() == 4) { uint32_t current_state = strtol(split_vec.at(0).c_str(),NULL,10); uint32_t symbol = strtol(split_vec.at(2).c_str(),NULL,10); if (find(_states.begin(), _states.end(), current_state)==_states.end()) { _states.push_back( current_state ); } if (find(_symbols.begin(), _symbols.end(), symbol)==_symbols.end()) { _symbols.push_back( symbol ); } if ( startStateIsntSet ) { _start_state = current_state; startStateIsntSet = false; } } else if (split_vec.size()==1) { uint32_t final_state = strtol(split_vec.at(0).c_str(),NULL,10); if (find(_final_states.begin(), _final_states.end(), final_state)==_final_states.end()) { _final_states.push_back( final_state ); } if (find(_states.begin(), _states.end(), final_state)==_states.end()) { _states.push_back( final_state ); } } else if (split_vec.size()>0) { throw invalid_fst_format; } else { // blank line, ignore } } _states.push_back( _states.size() ); // extra for the "dead" state _num_symbols = _symbols.size(); _num_states = _states.size(); // build up our sigma/sigma_reverse tables which enable mappings between // bytes/integers uint32_t j, k; for (j=0; j<_num_symbols; j++) { _sigma.insert( std::pair( j, (char)(_symbols.at(j))) ); _sigma_reverse.insert( std::pair((char)(_symbols.at(j)), j) ); } // intialize all transitions in our DFA to our dead state _delta.resize(_num_states); for (j=0; j<_num_states; j++) { _delta.at(j).resize(_num_symbols); for (k=0; k < _num_symbols; k++) { _delta.at(j).at(k) = _num_states - 1; } } // fill our our transition function delta std::istringstream my_str_stream2(dfa_str); while ( getline (my_str_stream2,line) ) { array_type_string_t1 split_vec = tokenize( line, '\t' ); if (split_vec.size() == 4) { uint32_t current_state = strtol(split_vec.at(0).c_str(),NULL,10); uint32_t symbol = strtol(split_vec.at(2).c_str(),NULL,10); uint32_t new_state = strtol(split_vec.at(1).c_str(),NULL,10); symbol = _sigma_reverse.at(symbol); _delta.at(current_state).at(symbol) = new_state; } } _delta_dense.resize(_num_states); uint32_t q, a; for (q=0; q < _num_states; q++ ) { _delta_dense.at(q) = true; for (a=1; a < _num_symbols; a++) { if (_delta.at(q).at(a-1) != _delta.at(q).at(a)) { _delta_dense.at(q) = false; break; } } } DFA::_validate(); // perform our precalculation to speed up (un)ranking DFA::_buildTable(); } void DFA::_validate() { // ensure DFA has at least one state if (_states.size()==0) throw invalid_fst_format; // ensure DFA has at least one symbol if (_sigma.size()==0) throw invalid_fst_format; if (_sigma_reverse.size()==0) throw invalid_fst_format; // ensure we have N states, labeled 0,1,..N-1 array_type_uint32_t1::iterator state; for (state=_states.begin(); state!=_states.end(); state++) { if (*state >= _states.size()) { throw invalid_fst_exception_state_name; } } // ensure all symbols are in the range 0,1,...,255 for (uint32_t i = 0; i < _symbols.size(); i++) { if (_symbols.at(i) > 256 || _symbols.at(i) < 0) { throw invalid_fst_exception_symbol_name; } } } void DFA::_buildTable() { uint32_t i; uint32_t q; uint32_t a; // ensure our table _T is the correct size _T.resize(_num_states); for (q=0; q<_num_states; q++) { _T.at(q).resize(_fixed_slice+1); for (i=0; i<=_fixed_slice; i++) { _T.at(q).at(i) = 0; } } // set all _T.at(q).at(0) = 1 for all states in _final_states array_type_uint32_t1::iterator state; for (state=_final_states.begin(); state!=_final_states.end(); state++) { _T.at(*state).at(0) = 1; } // walk through our table _T // we want each entry _T.at(q).at(i) to contain the number of strings that start // from state q, terminate in a final state, and are of length i for (i=1; i<=_fixed_slice; i++) { for (q=0; q<_delta.size(); q++) { for (a=0; a<_delta.at(0).size(); a++) { uint32_t state = _delta.at(q).at(a); _T.at(q).at(i) += _T.at(state).at(i-1); } } } } std::string DFA::unrank( const mpz_class c_in ) { std::string retval; // throw exception if input integer is not in range of pre-computed value mpz_class words_in_slice = getNumWordsInLanguage( _fixed_slice, _fixed_slice ); if ( c_in > words_in_slice ) throw invalid_unrank_input; // walk the DFA subtracting values from c until we have our n symbols mpz_class c = c_in; uint32_t i = 0; uint32_t q = _start_state; uint32_t char_cursor = 0; uint32_t state = 0; mpz_class char_index = 0; for (i=1; i<=_fixed_slice; i++) { if (_delta_dense.at(q)) { // our optimized version, when _delta[q][i] is equal to n for all symbols i state = _delta.at(q).at(0); // We do the following two lines with a single call // to mpz_fdiv_qr, which is much faster. // char_index = (c / _T.at(state).at(_fixed_slice-i)); // c = c % _T.at(state).at(_fixed_slice-i); mpz_fdiv_qr( char_index.get_mpz_t(), c.get_mpz_t(), c.get_mpz_t(), _T.at(state).at(_fixed_slice-i).get_mpz_t() ); char_cursor = char_index.get_ui(); } else { // traditional goldberg-sipser ranking char_cursor = 0; state = _delta.at(q).at(char_cursor); // A call to mpz_cmp is faster than using >= directly. // while (c >= _T.at(state).at(n-i)) { while (mpz_cmp( c.get_mpz_t(), _T.at(state).at(_fixed_slice-i).get_mpz_t() )>=0) { // Much faster to call mpz_sub, than -=. // c -= _T.at(state).at(n-i); mpz_sub( c.get_mpz_t(), c.get_mpz_t(), _T.at(state).at(_fixed_slice-i).get_mpz_t() ); char_cursor += 1; state =_delta.at(q).at(char_cursor); } } retval += _sigma.at(char_cursor); q = state; } // bail if our last state q is not in _final_states if (find(_final_states.begin(), _final_states.end(), q)==_final_states.end()) { throw invalid_input_exception_not_in_final_states; } return retval; } mpz_class DFA::rank( const std::string X ) { mpz_class retval = 0; // verify len(X) is what we expect if (X.length()!=_fixed_slice) { throw invalid_rank_input; } // walk the DFA, adding values from _T to c uint32_t i = 0; uint32_t j = 0; uint32_t n = X.size(); uint32_t symbol_as_int = 0; uint32_t q = _start_state; uint32_t state = 0; mpz_class tmp = 0; for (i=1; i<=n; i++) { try { symbol_as_int = _sigma_reverse.at(X.at(i-1)); } catch (int e) { throw symbol_not_in_sigma; } if (_delta_dense.at(q)) { // our optimized version, when _delta[q][i] is equal to n for all symbols i state = _delta.at(q).at(0); // Orders of magnitude faster to use mpz_mul_ui, // compared to *. // tmp = _T.at(state).at(n-i) * symbol_as_int mpz_mul_ui( tmp.get_mpz_t(), _T.at(state).at(n-i).get_mpz_t(), symbol_as_int ); // mpz_add is faster than += //retval += tmp.get_mpz_t(); mpz_add( retval.get_mpz_t(), retval.get_mpz_t(), tmp.get_mpz_t() ); } else { // traditional goldberg-sipser ranking for (j=1; j<=symbol_as_int; j++) { state = _delta.at(q).at(j-1); // mpz_add is faster than += //retval += _T.at(state).at(n-i); mpz_add( retval.get_mpz_t(), retval.get_mpz_t(), _T.at(state).at(n-i).get_mpz_t() ); } } q = _delta.at(q).at(symbol_as_int); } // bail if our last state q is not in _final_states if (find(_final_states.begin(), _final_states.end(), q)==_final_states.end()) { throw invalid_input_exception_not_in_final_states; } return retval; } mpz_class DFA::getNumWordsInLanguage( const uint32_t min_word_length, const uint32_t max_word_length ) { // verify min_word_length <= max_word_length <= _fixed_slice assert(0<=min_word_length); assert(min_word_length<=max_word_length); assert(max_word_length<=_fixed_slice); // count the number of words in the language of length // at least min_word_length and no greater than max_word_length mpz_class num_words = 0; for (uint32_t word_length = min_word_length; word_length <= max_word_length; word_length++) { num_words += _T.at(_start_state).at(word_length); } return num_words; } libfte-0.1.0/fte/rank_unrank.h000077500000000000000000000057331240634120100162210ustar00rootroot00000000000000/* * Please see Appendix A of "Protocol Misidentification Made Easy with Format-Transforming Encryption" * url: http://dl.acm.org/citation.cfm?id=2516657 * * and * * "Compression and ranking" * url: http://dl.acm.org/citation.cfm?id=22194 * * for details about (un)ranking for regular languages. */ #ifndef _RANK_UNRANK_H #define _RANK_UNRANK_H #include #include #include #include typedef std::vector array_type_char_t1; typedef std::vector array_type_bool_t1; typedef std::vector array_type_uint32_t1; typedef std::vector< std::vector > array_type_uint32_t2; typedef std::vector< std::vector > array_type_mpz_t2; typedef std::vector< std::string > array_type_string_t1; class DFA { private: // the maximum value for which buildTable is computed uint32_t _fixed_slice; // our DFA start state uint32_t _start_state; // the number of states in our DFA uint32_t _num_states; // the number of symbols in our DFA alphabet uint32_t _num_symbols; // the symbols of our DFA alphabet array_type_uint32_t1 _symbols; // our mapping between integers and the symbols in our alphabet; ints -> chars std::map _sigma; // the reverse mapping of sigma, chars -> ints std::map _sigma_reverse; // the states in our DFA array_type_uint32_t1 _states; // our transitions table array_type_uint32_t2 _delta; // a lookup table used for additional performance gain // for each state we detect if all outgoing transitions are to the same state array_type_bool_t1 _delta_dense; // the set of final states in our DFA array_type_uint32_t1 _final_states; // buildTable builds a mapping from [q, i] -> n // q: a state in our DFA // i: an integer // n: the number of words in our language that have a path to a final // state that is exactly length i void _buildTable(); // Checks the properties of our DFA, to ensure that we meet all constraints. // Throws an exception upon failure. void _validate(); // _T is our cached table, the output of buildTable // For a state q and integer i, the value _T[q][i] is the number of unique // accepting paths of length exactly i from state q. array_type_mpz_t2 _T; public: // The constructor of our rank/urank DFA class DFA( const std::string, const uint32_t ); // our unrank function an int -> str mapping // given an integer i, return the ith lexicographically ordered string in // the language accepted by the DFA std::string unrank( const mpz_class ); // our rank function performs the inverse operation of unrank mpz_class rank( const std::string ); // given integers [n,m] returns the number of words accepted by the // DFA that are at least length n and no greater than length m mpz_class getNumWordsInLanguage( const uint32_t, const uint32_t ); }; #endif /* _RANK_UNRANK_H */ libfte-0.1.0/fte/tests/000077500000000000000000000000001240634120100146665ustar00rootroot00000000000000libfte-0.1.0/fte/tests/__init__.py000077500000000000000000000006171240634120100170060ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import test_bit_ops import test_encoder import test_encrypter def suite(): suite = unittest.TestSuite() suite.addTests(test_bit_ops.suite()) suite.addTests(test_encoder.suite()) suite.addTests(test_encrypter.suite()) return suite if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite()) libfte-0.1.0/fte/tests/dfas/000077500000000000000000000000001240634120100156035ustar00rootroot00000000000000libfte-0.1.0/fte/tests/dfas/__init__.py000077500000000000000000000000001240634120100177050ustar00rootroot00000000000000libfte-0.1.0/fte/tests/dfas/test1.dfa000077500000000000000000000000771240634120100173260ustar00rootroot000000000000000 1 97 97 1 2 98 98 2 3 99 99 3 4 49 49 3 4 5 50 50 5 6 51 51 6libfte-0.1.0/fte/tests/dfas/test1.regex000077500000000000000000000000201240634120100176720ustar00rootroot00000000000000^(abc)|(abc123)$libfte-0.1.0/fte/tests/dfas/test2.dfa000077500000000000000000000000511240634120100173170ustar00rootroot000000000000000 1 97 97 0 1 98 98 1 1 97 97 1 1 98 98 1libfte-0.1.0/fte/tests/dfas/test2.regex000077500000000000000000000000101240634120100176720ustar00rootroot00000000000000^(a|b)+$libfte-0.1.0/fte/tests/dfas/test3.dfa000077500000000000000000000001551240634120100173250ustar00rootroot000000000000000 1 115 115 1 2 116 116 2 3 97 97 3 4 116 116 4 5 105 105 5 6 99 99 6 7 97 97 6 7 98 98 7 7 97 97 7 7 98 98 7libfte-0.1.0/fte/tests/dfas/test3.regex000077500000000000000000000000161240634120100177010ustar00rootroot00000000000000^static(a|b)+$libfte-0.1.0/fte/tests/dfas/test4.dfa000077500000000000000000000131111240634120100173220ustar00rootroot000000000000000 1 0 0 0 1 1 1 0 1 2 2 0 1 3 3 0 1 4 4 0 1 5 5 0 1 6 6 0 1 7 7 0 1 8 8 0 1 9 9 0 1 10 10 0 1 11 11 0 1 12 12 0 1 13 13 0 1 14 14 0 1 15 15 0 1 16 16 0 1 17 17 0 1 18 18 0 1 19 19 0 1 20 20 0 1 21 21 0 1 22 22 0 1 23 23 0 1 24 24 0 1 25 25 0 1 26 26 0 1 27 27 0 1 28 28 0 1 29 29 0 1 30 30 0 1 31 31 0 1 32 32 0 1 33 33 0 1 34 34 0 1 35 35 0 1 36 36 0 1 37 37 0 1 38 38 0 1 39 39 0 1 40 40 0 1 41 41 0 1 42 42 0 1 43 43 0 1 44 44 0 1 45 45 0 1 46 46 0 1 47 47 0 1 48 48 0 1 49 49 0 1 50 50 0 1 51 51 0 1 52 52 0 1 53 53 0 1 54 54 0 1 55 55 0 1 56 56 0 1 57 57 0 1 58 58 0 1 59 59 0 1 60 60 0 1 61 61 0 1 62 62 0 1 63 63 0 1 64 64 0 1 65 65 0 1 66 66 0 1 67 67 0 1 68 68 0 1 69 69 0 1 70 70 0 1 71 71 0 1 72 72 0 1 73 73 0 1 74 74 0 1 75 75 0 1 76 76 0 1 77 77 0 1 78 78 0 1 79 79 0 1 80 80 0 1 81 81 0 1 82 82 0 1 83 83 0 1 84 84 0 1 85 85 0 1 86 86 0 1 87 87 0 1 88 88 0 1 89 89 0 1 90 90 0 1 91 91 0 1 92 92 0 1 93 93 0 1 94 94 0 1 95 95 0 1 96 96 0 1 97 97 0 1 98 98 0 1 99 99 0 1 100 100 0 1 101 101 0 1 102 102 0 1 103 103 0 1 104 104 0 1 105 105 0 1 106 106 0 1 107 107 0 1 108 108 0 1 109 109 0 1 110 110 0 1 111 111 0 1 112 112 0 1 113 113 0 1 114 114 0 1 115 115 0 1 116 116 0 1 117 117 0 1 118 118 0 1 119 119 0 1 120 120 0 1 121 121 0 1 122 122 0 1 123 123 0 1 124 124 0 1 125 125 0 1 126 126 0 1 127 127 0 1 128 128 0 1 129 129 0 1 130 130 0 1 131 131 0 1 132 132 0 1 133 133 0 1 134 134 0 1 135 135 0 1 136 136 0 1 137 137 0 1 138 138 0 1 139 139 0 1 140 140 0 1 141 141 0 1 142 142 0 1 143 143 0 1 144 144 0 1 145 145 0 1 146 146 0 1 147 147 0 1 148 148 0 1 149 149 0 1 150 150 0 1 151 151 0 1 152 152 0 1 153 153 0 1 154 154 0 1 155 155 0 1 156 156 0 1 157 157 0 1 158 158 0 1 159 159 0 1 160 160 0 1 161 161 0 1 162 162 0 1 163 163 0 1 164 164 0 1 165 165 0 1 166 166 0 1 167 167 0 1 168 168 0 1 169 169 0 1 170 170 0 1 171 171 0 1 172 172 0 1 173 173 0 1 174 174 0 1 175 175 0 1 176 176 0 1 177 177 0 1 178 178 0 1 179 179 0 1 180 180 0 1 181 181 0 1 182 182 0 1 183 183 0 1 184 184 0 1 185 185 0 1 186 186 0 1 187 187 0 1 188 188 0 1 189 189 0 1 190 190 0 1 191 191 0 1 192 192 0 1 193 193 0 1 194 194 0 1 195 195 0 1 196 196 0 1 197 197 0 1 198 198 0 1 199 199 0 1 200 200 0 1 201 201 0 1 202 202 0 1 203 203 0 1 204 204 0 1 205 205 0 1 206 206 0 1 207 207 0 1 208 208 0 1 209 209 0 1 210 210 0 1 211 211 0 1 212 212 0 1 213 213 0 1 214 214 0 1 215 215 0 1 216 216 0 1 217 217 0 1 218 218 0 1 219 219 0 1 220 220 0 1 221 221 0 1 222 222 0 1 223 223 0 1 224 224 0 1 225 225 0 1 226 226 0 1 227 227 0 1 228 228 0 1 229 229 0 1 230 230 0 1 231 231 0 1 232 232 0 1 233 233 0 1 234 234 0 1 235 235 0 1 236 236 0 1 237 237 0 1 238 238 0 1 239 239 0 1 240 240 0 1 241 241 0 1 242 242 0 1 243 243 0 1 244 244 0 1 245 245 0 1 246 246 0 1 247 247 0 1 248 248 0 1 249 249 0 1 250 250 0 1 251 251 0 1 252 252 0 1 253 253 0 1 254 254 0 1 255 255 1 1 0 0 1 1 1 1 1 1 2 2 1 1 3 3 1 1 4 4 1 1 5 5 1 1 6 6 1 1 7 7 1 1 8 8 1 1 9 9 1 1 10 10 1 1 11 11 1 1 12 12 1 1 13 13 1 1 14 14 1 1 15 15 1 1 16 16 1 1 17 17 1 1 18 18 1 1 19 19 1 1 20 20 1 1 21 21 1 1 22 22 1 1 23 23 1 1 24 24 1 1 25 25 1 1 26 26 1 1 27 27 1 1 28 28 1 1 29 29 1 1 30 30 1 1 31 31 1 1 32 32 1 1 33 33 1 1 34 34 1 1 35 35 1 1 36 36 1 1 37 37 1 1 38 38 1 1 39 39 1 1 40 40 1 1 41 41 1 1 42 42 1 1 43 43 1 1 44 44 1 1 45 45 1 1 46 46 1 1 47 47 1 1 48 48 1 1 49 49 1 1 50 50 1 1 51 51 1 1 52 52 1 1 53 53 1 1 54 54 1 1 55 55 1 1 56 56 1 1 57 57 1 1 58 58 1 1 59 59 1 1 60 60 1 1 61 61 1 1 62 62 1 1 63 63 1 1 64 64 1 1 65 65 1 1 66 66 1 1 67 67 1 1 68 68 1 1 69 69 1 1 70 70 1 1 71 71 1 1 72 72 1 1 73 73 1 1 74 74 1 1 75 75 1 1 76 76 1 1 77 77 1 1 78 78 1 1 79 79 1 1 80 80 1 1 81 81 1 1 82 82 1 1 83 83 1 1 84 84 1 1 85 85 1 1 86 86 1 1 87 87 1 1 88 88 1 1 89 89 1 1 90 90 1 1 91 91 1 1 92 92 1 1 93 93 1 1 94 94 1 1 95 95 1 1 96 96 1 1 97 97 1 1 98 98 1 1 99 99 1 1 100 100 1 1 101 101 1 1 102 102 1 1 103 103 1 1 104 104 1 1 105 105 1 1 106 106 1 1 107 107 1 1 108 108 1 1 109 109 1 1 110 110 1 1 111 111 1 1 112 112 1 1 113 113 1 1 114 114 1 1 115 115 1 1 116 116 1 1 117 117 1 1 118 118 1 1 119 119 1 1 120 120 1 1 121 121 1 1 122 122 1 1 123 123 1 1 124 124 1 1 125 125 1 1 126 126 1 1 127 127 1 1 128 128 1 1 129 129 1 1 130 130 1 1 131 131 1 1 132 132 1 1 133 133 1 1 134 134 1 1 135 135 1 1 136 136 1 1 137 137 1 1 138 138 1 1 139 139 1 1 140 140 1 1 141 141 1 1 142 142 1 1 143 143 1 1 144 144 1 1 145 145 1 1 146 146 1 1 147 147 1 1 148 148 1 1 149 149 1 1 150 150 1 1 151 151 1 1 152 152 1 1 153 153 1 1 154 154 1 1 155 155 1 1 156 156 1 1 157 157 1 1 158 158 1 1 159 159 1 1 160 160 1 1 161 161 1 1 162 162 1 1 163 163 1 1 164 164 1 1 165 165 1 1 166 166 1 1 167 167 1 1 168 168 1 1 169 169 1 1 170 170 1 1 171 171 1 1 172 172 1 1 173 173 1 1 174 174 1 1 175 175 1 1 176 176 1 1 177 177 1 1 178 178 1 1 179 179 1 1 180 180 1 1 181 181 1 1 182 182 1 1 183 183 1 1 184 184 1 1 185 185 1 1 186 186 1 1 187 187 1 1 188 188 1 1 189 189 1 1 190 190 1 1 191 191 1 1 192 192 1 1 193 193 1 1 194 194 1 1 195 195 1 1 196 196 1 1 197 197 1 1 198 198 1 1 199 199 1 1 200 200 1 1 201 201 1 1 202 202 1 1 203 203 1 1 204 204 1 1 205 205 1 1 206 206 1 1 207 207 1 1 208 208 1 1 209 209 1 1 210 210 1 1 211 211 1 1 212 212 1 1 213 213 1 1 214 214 1 1 215 215 1 1 216 216 1 1 217 217 1 1 218 218 1 1 219 219 1 1 220 220 1 1 221 221 1 1 222 222 1 1 223 223 1 1 224 224 1 1 225 225 1 1 226 226 1 1 227 227 1 1 228 228 1 1 229 229 1 1 230 230 1 1 231 231 1 1 232 232 1 1 233 233 1 1 234 234 1 1 235 235 1 1 236 236 1 1 237 237 1 1 238 238 1 1 239 239 1 1 240 240 1 1 241 241 1 1 242 242 1 1 243 243 1 1 244 244 1 1 245 245 1 1 246 246 1 1 247 247 1 1 248 248 1 1 249 249 1 1 250 250 1 1 251 251 1 1 252 252 1 1 253 253 1 1 254 254 1 1 255 255 1libfte-0.1.0/fte/tests/dfas/test4.regex000077500000000000000000000000051240634120100177000ustar00rootroot00000000000000^\C+$libfte-0.1.0/fte/tests/dfas/test5.dfa000077500000000000000000000131211240634120100173240ustar00rootroot000000000000000 1 0 0 1 2 0 0 1 2 1 1 1 2 2 2 1 2 3 3 1 2 4 4 1 2 5 5 1 2 6 6 1 2 7 7 1 2 8 8 1 2 9 9 1 2 10 10 1 2 11 11 1 2 12 12 1 2 13 13 1 2 14 14 1 2 15 15 1 2 16 16 1 2 17 17 1 2 18 18 1 2 19 19 1 2 20 20 1 2 21 21 1 2 22 22 1 2 23 23 1 2 24 24 1 2 25 25 1 2 26 26 1 2 27 27 1 2 28 28 1 2 29 29 1 2 30 30 1 2 31 31 1 2 32 32 1 2 33 33 1 2 34 34 1 2 35 35 1 2 36 36 1 2 37 37 1 2 38 38 1 2 39 39 1 2 40 40 1 2 41 41 1 2 42 42 1 2 43 43 1 2 44 44 1 2 45 45 1 2 46 46 1 2 47 47 1 2 48 48 1 2 49 49 1 2 50 50 1 2 51 51 1 2 52 52 1 2 53 53 1 2 54 54 1 2 55 55 1 2 56 56 1 2 57 57 1 2 58 58 1 2 59 59 1 2 60 60 1 2 61 61 1 2 62 62 1 2 63 63 1 2 64 64 1 2 65 65 1 2 66 66 1 2 67 67 1 2 68 68 1 2 69 69 1 2 70 70 1 2 71 71 1 2 72 72 1 2 73 73 1 2 74 74 1 2 75 75 1 2 76 76 1 2 77 77 1 2 78 78 1 2 79 79 1 2 80 80 1 2 81 81 1 2 82 82 1 2 83 83 1 2 84 84 1 2 85 85 1 2 86 86 1 2 87 87 1 2 88 88 1 2 89 89 1 2 90 90 1 2 91 91 1 2 92 92 1 2 93 93 1 2 94 94 1 2 95 95 1 2 96 96 1 2 97 97 1 2 98 98 1 2 99 99 1 2 100 100 1 2 101 101 1 2 102 102 1 2 103 103 1 2 104 104 1 2 105 105 1 2 106 106 1 2 107 107 1 2 108 108 1 2 109 109 1 2 110 110 1 2 111 111 1 2 112 112 1 2 113 113 1 2 114 114 1 2 115 115 1 2 116 116 1 2 117 117 1 2 118 118 1 2 119 119 1 2 120 120 1 2 121 121 1 2 122 122 1 2 123 123 1 2 124 124 1 2 125 125 1 2 126 126 1 2 127 127 1 2 128 128 1 2 129 129 1 2 130 130 1 2 131 131 1 2 132 132 1 2 133 133 1 2 134 134 1 2 135 135 1 2 136 136 1 2 137 137 1 2 138 138 1 2 139 139 1 2 140 140 1 2 141 141 1 2 142 142 1 2 143 143 1 2 144 144 1 2 145 145 1 2 146 146 1 2 147 147 1 2 148 148 1 2 149 149 1 2 150 150 1 2 151 151 1 2 152 152 1 2 153 153 1 2 154 154 1 2 155 155 1 2 156 156 1 2 157 157 1 2 158 158 1 2 159 159 1 2 160 160 1 2 161 161 1 2 162 162 1 2 163 163 1 2 164 164 1 2 165 165 1 2 166 166 1 2 167 167 1 2 168 168 1 2 169 169 1 2 170 170 1 2 171 171 1 2 172 172 1 2 173 173 1 2 174 174 1 2 175 175 1 2 176 176 1 2 177 177 1 2 178 178 1 2 179 179 1 2 180 180 1 2 181 181 1 2 182 182 1 2 183 183 1 2 184 184 1 2 185 185 1 2 186 186 1 2 187 187 1 2 188 188 1 2 189 189 1 2 190 190 1 2 191 191 1 2 192 192 1 2 193 193 1 2 194 194 1 2 195 195 1 2 196 196 1 2 197 197 1 2 198 198 1 2 199 199 1 2 200 200 1 2 201 201 1 2 202 202 1 2 203 203 1 2 204 204 1 2 205 205 1 2 206 206 1 2 207 207 1 2 208 208 1 2 209 209 1 2 210 210 1 2 211 211 1 2 212 212 1 2 213 213 1 2 214 214 1 2 215 215 1 2 216 216 1 2 217 217 1 2 218 218 1 2 219 219 1 2 220 220 1 2 221 221 1 2 222 222 1 2 223 223 1 2 224 224 1 2 225 225 1 2 226 226 1 2 227 227 1 2 228 228 1 2 229 229 1 2 230 230 1 2 231 231 1 2 232 232 1 2 233 233 1 2 234 234 1 2 235 235 1 2 236 236 1 2 237 237 1 2 238 238 1 2 239 239 1 2 240 240 1 2 241 241 1 2 242 242 1 2 243 243 1 2 244 244 1 2 245 245 1 2 246 246 1 2 247 247 1 2 248 248 1 2 249 249 1 2 250 250 1 2 251 251 1 2 252 252 1 2 253 253 1 2 254 254 1 2 255 255 2 2 0 0 2 2 1 1 2 2 2 2 2 2 3 3 2 2 4 4 2 2 5 5 2 2 6 6 2 2 7 7 2 2 8 8 2 2 9 9 2 2 10 10 2 2 11 11 2 2 12 12 2 2 13 13 2 2 14 14 2 2 15 15 2 2 16 16 2 2 17 17 2 2 18 18 2 2 19 19 2 2 20 20 2 2 21 21 2 2 22 22 2 2 23 23 2 2 24 24 2 2 25 25 2 2 26 26 2 2 27 27 2 2 28 28 2 2 29 29 2 2 30 30 2 2 31 31 2 2 32 32 2 2 33 33 2 2 34 34 2 2 35 35 2 2 36 36 2 2 37 37 2 2 38 38 2 2 39 39 2 2 40 40 2 2 41 41 2 2 42 42 2 2 43 43 2 2 44 44 2 2 45 45 2 2 46 46 2 2 47 47 2 2 48 48 2 2 49 49 2 2 50 50 2 2 51 51 2 2 52 52 2 2 53 53 2 2 54 54 2 2 55 55 2 2 56 56 2 2 57 57 2 2 58 58 2 2 59 59 2 2 60 60 2 2 61 61 2 2 62 62 2 2 63 63 2 2 64 64 2 2 65 65 2 2 66 66 2 2 67 67 2 2 68 68 2 2 69 69 2 2 70 70 2 2 71 71 2 2 72 72 2 2 73 73 2 2 74 74 2 2 75 75 2 2 76 76 2 2 77 77 2 2 78 78 2 2 79 79 2 2 80 80 2 2 81 81 2 2 82 82 2 2 83 83 2 2 84 84 2 2 85 85 2 2 86 86 2 2 87 87 2 2 88 88 2 2 89 89 2 2 90 90 2 2 91 91 2 2 92 92 2 2 93 93 2 2 94 94 2 2 95 95 2 2 96 96 2 2 97 97 2 2 98 98 2 2 99 99 2 2 100 100 2 2 101 101 2 2 102 102 2 2 103 103 2 2 104 104 2 2 105 105 2 2 106 106 2 2 107 107 2 2 108 108 2 2 109 109 2 2 110 110 2 2 111 111 2 2 112 112 2 2 113 113 2 2 114 114 2 2 115 115 2 2 116 116 2 2 117 117 2 2 118 118 2 2 119 119 2 2 120 120 2 2 121 121 2 2 122 122 2 2 123 123 2 2 124 124 2 2 125 125 2 2 126 126 2 2 127 127 2 2 128 128 2 2 129 129 2 2 130 130 2 2 131 131 2 2 132 132 2 2 133 133 2 2 134 134 2 2 135 135 2 2 136 136 2 2 137 137 2 2 138 138 2 2 139 139 2 2 140 140 2 2 141 141 2 2 142 142 2 2 143 143 2 2 144 144 2 2 145 145 2 2 146 146 2 2 147 147 2 2 148 148 2 2 149 149 2 2 150 150 2 2 151 151 2 2 152 152 2 2 153 153 2 2 154 154 2 2 155 155 2 2 156 156 2 2 157 157 2 2 158 158 2 2 159 159 2 2 160 160 2 2 161 161 2 2 162 162 2 2 163 163 2 2 164 164 2 2 165 165 2 2 166 166 2 2 167 167 2 2 168 168 2 2 169 169 2 2 170 170 2 2 171 171 2 2 172 172 2 2 173 173 2 2 174 174 2 2 175 175 2 2 176 176 2 2 177 177 2 2 178 178 2 2 179 179 2 2 180 180 2 2 181 181 2 2 182 182 2 2 183 183 2 2 184 184 2 2 185 185 2 2 186 186 2 2 187 187 2 2 188 188 2 2 189 189 2 2 190 190 2 2 191 191 2 2 192 192 2 2 193 193 2 2 194 194 2 2 195 195 2 2 196 196 2 2 197 197 2 2 198 198 2 2 199 199 2 2 200 200 2 2 201 201 2 2 202 202 2 2 203 203 2 2 204 204 2 2 205 205 2 2 206 206 2 2 207 207 2 2 208 208 2 2 209 209 2 2 210 210 2 2 211 211 2 2 212 212 2 2 213 213 2 2 214 214 2 2 215 215 2 2 216 216 2 2 217 217 2 2 218 218 2 2 219 219 2 2 220 220 2 2 221 221 2 2 222 222 2 2 223 223 2 2 224 224 2 2 225 225 2 2 226 226 2 2 227 227 2 2 228 228 2 2 229 229 2 2 230 230 2 2 231 231 2 2 232 232 2 2 233 233 2 2 234 234 2 2 235 235 2 2 236 236 2 2 237 237 2 2 238 238 2 2 239 239 2 2 240 240 2 2 241 241 2 2 242 242 2 2 243 243 2 2 244 244 2 2 245 245 2 2 246 246 2 2 247 247 2 2 248 248 2 2 249 249 2 2 250 250 2 2 251 251 2 2 252 252 2 2 253 253 2 2 254 254 2 2 255 255 2libfte-0.1.0/fte/tests/dfas/test5.regex000077500000000000000000000000111240634120100176760ustar00rootroot00000000000000^\x00\C+$libfte-0.1.0/fte/tests/dfas/test6.dfa000077500000000000000000000131211240634120100173250ustar00rootroot000000000000000 1 0 0 1 2 0 0 1 2 1 1 1 2 2 2 1 2 3 3 1 2 4 4 1 2 5 5 1 2 6 6 1 2 7 7 1 2 8 8 1 2 9 9 1 2 10 10 1 2 11 11 1 2 12 12 1 2 13 13 1 2 14 14 1 2 15 15 1 2 16 16 1 2 17 17 1 2 18 18 1 2 19 19 1 2 20 20 1 2 21 21 1 2 22 22 1 2 23 23 1 2 24 24 1 2 25 25 1 2 26 26 1 2 27 27 1 2 28 28 1 2 29 29 1 2 30 30 1 2 31 31 1 2 32 32 1 2 33 33 1 2 34 34 1 2 35 35 1 2 36 36 1 2 37 37 1 2 38 38 1 2 39 39 1 2 40 40 1 2 41 41 1 2 42 42 1 2 43 43 1 2 44 44 1 2 45 45 1 2 46 46 1 2 47 47 1 2 48 48 1 2 49 49 1 2 50 50 1 2 51 51 1 2 52 52 1 2 53 53 1 2 54 54 1 2 55 55 1 2 56 56 1 2 57 57 1 2 58 58 1 2 59 59 1 2 60 60 1 2 61 61 1 2 62 62 1 2 63 63 1 2 64 64 1 2 65 65 1 2 66 66 1 2 67 67 1 2 68 68 1 2 69 69 1 2 70 70 1 2 71 71 1 2 72 72 1 2 73 73 1 2 74 74 1 2 75 75 1 2 76 76 1 2 77 77 1 2 78 78 1 2 79 79 1 2 80 80 1 2 81 81 1 2 82 82 1 2 83 83 1 2 84 84 1 2 85 85 1 2 86 86 1 2 87 87 1 2 88 88 1 2 89 89 1 2 90 90 1 2 91 91 1 2 92 92 1 2 93 93 1 2 94 94 1 2 95 95 1 2 96 96 1 2 97 97 1 2 98 98 1 2 99 99 1 2 100 100 1 2 101 101 1 2 102 102 1 2 103 103 1 2 104 104 1 2 105 105 1 2 106 106 1 2 107 107 1 2 108 108 1 2 109 109 1 2 110 110 1 2 111 111 1 2 112 112 1 2 113 113 1 2 114 114 1 2 115 115 1 2 116 116 1 2 117 117 1 2 118 118 1 2 119 119 1 2 120 120 1 2 121 121 1 2 122 122 1 2 123 123 1 2 124 124 1 2 125 125 1 2 126 126 1 2 127 127 1 2 128 128 1 2 129 129 1 2 130 130 1 2 131 131 1 2 132 132 1 2 133 133 1 2 134 134 1 2 135 135 1 2 136 136 1 2 137 137 1 2 138 138 1 2 139 139 1 2 140 140 1 2 141 141 1 2 142 142 1 2 143 143 1 2 144 144 1 2 145 145 1 2 146 146 1 2 147 147 1 2 148 148 1 2 149 149 1 2 150 150 1 2 151 151 1 2 152 152 1 2 153 153 1 2 154 154 1 2 155 155 1 2 156 156 1 2 157 157 1 2 158 158 1 2 159 159 1 2 160 160 1 2 161 161 1 2 162 162 1 2 163 163 1 2 164 164 1 2 165 165 1 2 166 166 1 2 167 167 1 2 168 168 1 2 169 169 1 2 170 170 1 2 171 171 1 2 172 172 1 2 173 173 1 2 174 174 1 2 175 175 1 2 176 176 1 2 177 177 1 2 178 178 1 2 179 179 1 2 180 180 1 2 181 181 1 2 182 182 1 2 183 183 1 2 184 184 1 2 185 185 1 2 186 186 1 2 187 187 1 2 188 188 1 2 189 189 1 2 190 190 1 2 191 191 1 2 192 192 1 2 193 193 1 2 194 194 1 2 195 195 1 2 196 196 1 2 197 197 1 2 198 198 1 2 199 199 1 2 200 200 1 2 201 201 1 2 202 202 1 2 203 203 1 2 204 204 1 2 205 205 1 2 206 206 1 2 207 207 1 2 208 208 1 2 209 209 1 2 210 210 1 2 211 211 1 2 212 212 1 2 213 213 1 2 214 214 1 2 215 215 1 2 216 216 1 2 217 217 1 2 218 218 1 2 219 219 1 2 220 220 1 2 221 221 1 2 222 222 1 2 223 223 1 2 224 224 1 2 225 225 1 2 226 226 1 2 227 227 1 2 228 228 1 2 229 229 1 2 230 230 1 2 231 231 1 2 232 232 1 2 233 233 1 2 234 234 1 2 235 235 1 2 236 236 1 2 237 237 1 2 238 238 1 2 239 239 1 2 240 240 1 2 241 241 1 2 242 242 1 2 243 243 1 2 244 244 1 2 245 245 1 2 246 246 1 2 247 247 1 2 248 248 1 2 249 249 1 2 250 250 1 2 251 251 1 2 252 252 1 2 253 253 1 2 254 254 1 2 255 255 2 2 0 0 2 2 1 1 2 2 2 2 2 2 3 3 2 2 4 4 2 2 5 5 2 2 6 6 2 2 7 7 2 2 8 8 2 2 9 9 2 2 10 10 2 2 11 11 2 2 12 12 2 2 13 13 2 2 14 14 2 2 15 15 2 2 16 16 2 2 17 17 2 2 18 18 2 2 19 19 2 2 20 20 2 2 21 21 2 2 22 22 2 2 23 23 2 2 24 24 2 2 25 25 2 2 26 26 2 2 27 27 2 2 28 28 2 2 29 29 2 2 30 30 2 2 31 31 2 2 32 32 2 2 33 33 2 2 34 34 2 2 35 35 2 2 36 36 2 2 37 37 2 2 38 38 2 2 39 39 2 2 40 40 2 2 41 41 2 2 42 42 2 2 43 43 2 2 44 44 2 2 45 45 2 2 46 46 2 2 47 47 2 2 48 48 2 2 49 49 2 2 50 50 2 2 51 51 2 2 52 52 2 2 53 53 2 2 54 54 2 2 55 55 2 2 56 56 2 2 57 57 2 2 58 58 2 2 59 59 2 2 60 60 2 2 61 61 2 2 62 62 2 2 63 63 2 2 64 64 2 2 65 65 2 2 66 66 2 2 67 67 2 2 68 68 2 2 69 69 2 2 70 70 2 2 71 71 2 2 72 72 2 2 73 73 2 2 74 74 2 2 75 75 2 2 76 76 2 2 77 77 2 2 78 78 2 2 79 79 2 2 80 80 2 2 81 81 2 2 82 82 2 2 83 83 2 2 84 84 2 2 85 85 2 2 86 86 2 2 87 87 2 2 88 88 2 2 89 89 2 2 90 90 2 2 91 91 2 2 92 92 2 2 93 93 2 2 94 94 2 2 95 95 2 2 96 96 2 2 97 97 2 2 98 98 2 2 99 99 2 2 100 100 2 2 101 101 2 2 102 102 2 2 103 103 2 2 104 104 2 2 105 105 2 2 106 106 2 2 107 107 2 2 108 108 2 2 109 109 2 2 110 110 2 2 111 111 2 2 112 112 2 2 113 113 2 2 114 114 2 2 115 115 2 2 116 116 2 2 117 117 2 2 118 118 2 2 119 119 2 2 120 120 2 2 121 121 2 2 122 122 2 2 123 123 2 2 124 124 2 2 125 125 2 2 126 126 2 2 127 127 2 2 128 128 2 2 129 129 2 2 130 130 2 2 131 131 2 2 132 132 2 2 133 133 2 2 134 134 2 2 135 135 2 2 136 136 2 2 137 137 2 2 138 138 2 2 139 139 2 2 140 140 2 2 141 141 2 2 142 142 2 2 143 143 2 2 144 144 2 2 145 145 2 2 146 146 2 2 147 147 2 2 148 148 2 2 149 149 2 2 150 150 2 2 151 151 2 2 152 152 2 2 153 153 2 2 154 154 2 2 155 155 2 2 156 156 2 2 157 157 2 2 158 158 2 2 159 159 2 2 160 160 2 2 161 161 2 2 162 162 2 2 163 163 2 2 164 164 2 2 165 165 2 2 166 166 2 2 167 167 2 2 168 168 2 2 169 169 2 2 170 170 2 2 171 171 2 2 172 172 2 2 173 173 2 2 174 174 2 2 175 175 2 2 176 176 2 2 177 177 2 2 178 178 2 2 179 179 2 2 180 180 2 2 181 181 2 2 182 182 2 2 183 183 2 2 184 184 2 2 185 185 2 2 186 186 2 2 187 187 2 2 188 188 2 2 189 189 2 2 190 190 2 2 191 191 2 2 192 192 2 2 193 193 2 2 194 194 2 2 195 195 2 2 196 196 2 2 197 197 2 2 198 198 2 2 199 199 2 2 200 200 2 2 201 201 2 2 202 202 2 2 203 203 2 2 204 204 2 2 205 205 2 2 206 206 2 2 207 207 2 2 208 208 2 2 209 209 2 2 210 210 2 2 211 211 2 2 212 212 2 2 213 213 2 2 214 214 2 2 215 215 2 2 216 216 2 2 217 217 2 2 218 218 2 2 219 219 2 2 220 220 2 2 221 221 2 2 222 222 2 2 223 223 2 2 224 224 2 2 225 225 2 2 226 226 2 2 227 227 2 2 228 228 2 2 229 229 2 2 230 230 2 2 231 231 2 2 232 232 2 2 233 233 2 2 234 234 2 2 235 235 2 2 236 236 2 2 237 237 2 2 238 238 2 2 239 239 2 2 240 240 2 2 241 241 2 2 242 242 2 2 243 243 2 2 244 244 2 2 245 245 2 2 246 246 2 2 247 247 2 2 248 248 2 2 249 249 2 2 250 250 2 2 251 251 2 2 252 252 2 2 253 253 2 2 254 254 2 2 255 255 2libfte-0.1.0/fte/tests/dfas/test6.regex000077500000000000000000000000111240634120100176770ustar00rootroot00000000000000^\x00\C+$libfte-0.1.0/fte/tests/test_bit_ops.py000077500000000000000000000033041240634120100177410ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import random import fte.bit_ops class Tests(unittest.TestCase): def _testMSB(self): self.assertEquals(15, fte.bit_ops.msb(0xFF, 4)) self.assertEquals(0xFFFFFFFFFFFFFFFF, fte.bit_ops.msb(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 4 * 16)) self.assertEquals(15, fte.bit_ops.msb(0xFFFFFFFFFFFFFFFFF, 4)) self.assertEquals(15, fte.bit_ops.msb(0xF0000000000000000, 4)) def _testLSB(self): self.assertEquals(15, fte.bit_ops.lsb(0xFF, 4)) self.assertEquals(0xFFFFFFFFFFFFFFFF, fte.bit_ops.lsb(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 4 * 16)) self.assertEquals(15, fte.bit_ops.lsb(0xFFFFFFFFFFFFFFFFF, 4)) self.assertEquals(15, fte.bit_ops.lsb(15, 4)) def testLTB(self): self.assertEquals(fte.bit_ops.long_to_bytes(0xff), '\xFF') self.assertEquals(fte.bit_ops.bytes_to_long('\xFF'), 0xff) def testLTB2(self): for i in range(2 ** 10): N = random.randint(0, 1 << 1024) M = fte.bit_ops.long_to_bytes(N) M = fte.bit_ops.bytes_to_long(M) self.assertEquals(N, M) def testLTB3(self): for i in range(2 ** 10): N = random.randint(0, 1 << 1024) M = fte.bit_ops.long_to_bytes(N, 1024) self.assertEquals(1024, len(M)) M = fte.bit_ops.bytes_to_long(M) self.assertEquals(N, M) def suite(): loader = unittest.TestLoader() suite = unittest.TestSuite() suite.addTest(loader.loadTestsFromTestCase(Tests)) return suite libfte-0.1.0/fte/tests/test_encoder.py000077500000000000000000000143701240634120100177260ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import fte.bit_ops import fte.encoder DOT_STAR_DFA = "0 0 0 0\n" + \ "0 0 1 1\n" + \ "0 0 2 2\n" + \ "0 0 3 3\n" + \ "0 0 4 4\n" + \ "0 0 5 5\n" + \ "0 0 6 6\n" + \ "0 0 7 7\n" + \ "0 0 8 8\n" + \ "0 0 9 9\n" + \ "0 0 10 10\n" + \ "0 0 11 11\n" + \ "0 0 12 12\n" + \ "0 0 13 13\n" + \ "0 0 14 14\n" + \ "0 0 15 15\n" + \ "0 0 16 16\n" + \ "0 0 17 17\n" + \ "0 0 18 18\n" + \ "0 0 19 19\n" + \ "0 0 20 20\n" + \ "0 0 21 21\n" + \ "0 0 22 22\n" + \ "0 0 23 23\n" + \ "0 0 24 24\n" + \ "0 0 25 25\n" + \ "0 0 26 26\n" + \ "0 0 27 27\n" + \ "0 0 28 28\n" + \ "0 0 29 29\n" + \ "0 0 30 30\n" + \ "0 0 31 31\n" + \ "0 0 32 32\n" + \ "0 0 33 33\n" + \ "0 0 34 34\n" + \ "0 0 35 35\n" + \ "0 0 36 36\n" + \ "0 0 37 37\n" + \ "0 0 38 38\n" + \ "0 0 39 39\n" + \ "0 0 40 40\n" + \ "0 0 41 41\n" + \ "0 0 42 42\n" + \ "0 0 43 43\n" + \ "0 0 44 44\n" + \ "0 0 45 45\n" + \ "0 0 46 46\n" + \ "0 0 47 47\n" + \ "0 0 48 48\n" + \ "0 0 49 49\n" + \ "0 0 50 50\n" + \ "0 0 51 51\n" + \ "0 0 52 52\n" + \ "0 0 53 53\n" + \ "0 0 54 54\n" + \ "0 0 55 55\n" + \ "0 0 56 56\n" + \ "0 0 57 57\n" + \ "0 0 58 58\n" + \ "0 0 59 59\n" + \ "0 0 60 60\n" + \ "0 0 61 61\n" + \ "0 0 62 62\n" + \ "0 0 63 63\n" + \ "0 0 64 64\n" + \ "0 0 65 65\n" + \ "0 0 66 66\n" + \ "0 0 67 67\n" + \ "0 0 68 68\n" + \ "0 0 69 69\n" + \ "0 0 70 70\n" + \ "0 0 71 71\n" + \ "0 0 72 72\n" + \ "0 0 73 73\n" + \ "0 0 74 74\n" + \ "0 0 75 75\n" + \ "0 0 76 76\n" + \ "0 0 77 77\n" + \ "0 0 78 78\n" + \ "0 0 79 79\n" + \ "0 0 80 80\n" + \ "0 0 81 81\n" + \ "0 0 82 82\n" + \ "0 0 83 83\n" + \ "0 0 84 84\n" + \ "0 0 85 85\n" + \ "0 0 86 86\n" + \ "0 0 87 87\n" + \ "0 0 88 88\n" + \ "0 0 89 89\n" + \ "0 0 90 90\n" + \ "0 0 91 91\n" + \ "0 0 92 92\n" + \ "0 0 93 93\n" + \ "0 0 94 94\n" + \ "0 0 95 95\n" + \ "0 0 96 96\n" + \ "0 0 97 97\n" + \ "0 0 98 98\n" + \ "0 0 99 99\n" + \ "0 0 100 100\n" + \ "0 0 101 101\n" + \ "0 0 102 102\n" + \ "0 0 103 103\n" + \ "0 0 104 104\n" + \ "0 0 105 105\n" + \ "0 0 106 106\n" + \ "0 0 107 107\n" + \ "0 0 108 108\n" + \ "0 0 109 109\n" + \ "0 0 110 110\n" + \ "0 0 111 111\n" + \ "0 0 112 112\n" + \ "0 0 113 113\n" + \ "0 0 114 114\n" + \ "0 0 115 115\n" + \ "0 0 116 116\n" + \ "0 0 117 117\n" + \ "0 0 118 118\n" + \ "0 0 119 119\n" + \ "0 0 120 120\n" + \ "0 0 121 121\n" + \ "0 0 122 122\n" + \ "0 0 123 123\n" + \ "0 0 124 124\n" + \ "0 0 125 125\n" + \ "0 0 126 126\n" + \ "0 0 127 127\n" + \ "0 0 128 128\n" + \ "0 0 129 129\n" + \ "0 0 130 130\n" + \ "0 0 131 131\n" + \ "0 0 132 132\n" + \ "0 0 133 133\n" + \ "0 0 134 134\n" + \ "0 0 135 135\n" + \ "0 0 136 136\n" + \ "0 0 137 137\n" + \ "0 0 138 138\n" + \ "0 0 139 139\n" + \ "0 0 140 140\n" + \ "0 0 141 141\n" + \ "0 0 142 142\n" + \ "0 0 143 143\n" + \ "0 0 144 144\n" + \ "0 0 145 145\n" + \ "0 0 146 146\n" + \ "0 0 147 147\n" + \ "0 0 148 148\n" + \ "0 0 149 149\n" + \ "0 0 150 150\n" + \ "0 0 151 151\n" + \ "0 0 152 152\n" + \ "0 0 153 153\n" + \ "0 0 154 154\n" + \ "0 0 155 155\n" + \ "0 0 156 156\n" + \ "0 0 157 157\n" + \ "0 0 158 158\n" + \ "0 0 159 159\n" + \ "0 0 160 160\n" + \ "0 0 161 161\n" + \ "0 0 162 162\n" + \ "0 0 163 163\n" + \ "0 0 164 164\n" + \ "0 0 165 165\n" + \ "0 0 166 166\n" + \ "0 0 167 167\n" + \ "0 0 168 168\n" + \ "0 0 169 169\n" + \ "0 0 170 170\n" + \ "0 0 171 171\n" + \ "0 0 172 172\n" + \ "0 0 173 173\n" + \ "0 0 174 174\n" + \ "0 0 175 175\n" + \ "0 0 176 176\n" + \ "0 0 177 177\n" + \ "0 0 178 178\n" + \ "0 0 179 179\n" + \ "0 0 180 180\n" + \ "0 0 181 181\n" + \ "0 0 182 182\n" + \ "0 0 183 183\n" + \ "0 0 184 184\n" + \ "0 0 185 185\n" + \ "0 0 186 186\n" + \ "0 0 187 187\n" + \ "0 0 188 188\n" + \ "0 0 189 189\n" + \ "0 0 190 190\n" + \ "0 0 191 191\n" + \ "0 0 192 192\n" + \ "0 0 193 193\n" + \ "0 0 194 194\n" + \ "0 0 195 195\n" + \ "0 0 196 196\n" + \ "0 0 197 197\n" + \ "0 0 198 198\n" + \ "0 0 199 199\n" + \ "0 0 200 200\n" + \ "0 0 201 201\n" + \ "0 0 202 202\n" + \ "0 0 203 203\n" + \ "0 0 204 204\n" + \ "0 0 205 205\n" + \ "0 0 206 206\n" + \ "0 0 207 207\n" + \ "0 0 208 208\n" + \ "0 0 209 209\n" + \ "0 0 210 210\n" + \ "0 0 211 211\n" + \ "0 0 212 212\n" + \ "0 0 213 213\n" + \ "0 0 214 214\n" + \ "0 0 215 215\n" + \ "0 0 216 216\n" + \ "0 0 217 217\n" + \ "0 0 218 218\n" + \ "0 0 219 219\n" + \ "0 0 220 220\n" + \ "0 0 221 221\n" + \ "0 0 222 222\n" + \ "0 0 223 223\n" + \ "0 0 224 224\n" + \ "0 0 225 225\n" + \ "0 0 226 226\n" + \ "0 0 227 227\n" + \ "0 0 228 228\n" + \ "0 0 229 229\n" + \ "0 0 230 230\n" + \ "0 0 231 231\n" + \ "0 0 232 232\n" + \ "0 0 233 233\n" + \ "0 0 234 234\n" + \ "0 0 235 235\n" + \ "0 0 236 236\n" + \ "0 0 237 237\n" + \ "0 0 238 238\n" + \ "0 0 239 239\n" + \ "0 0 240 240\n" + \ "0 0 241 241\n" + \ "0 0 242 242\n" + \ "0 0 243 243\n" + \ "0 0 244 244\n" + \ "0 0 245 245\n" + \ "0 0 246 246\n" + \ "0 0 247 247\n" + \ "0 0 248 248\n" + \ "0 0 249 249\n" + \ "0 0 250 250\n" + \ "0 0 251 251\n" + \ "0 0 252 252\n" + \ "0 0 253 253\n" + \ "0 0 254 254\n" + \ "0 0 255 255\n" + \ "0" DFAS = [ DOT_STAR_DFA ] FIXED_SLICES = [ 512, 1024, 2048 ] MSG_LEN = 15 CONCATS = 8 class Tests(unittest.TestCase): def testSingle(self): for dfa in DFAS: for fixed_slice in FIXED_SLICES: fteObj = fte.encoder.DfaEncoder(dfa, fixed_slice) input_plaintext = fte.bit_ops.random_bytes(MSG_LEN) ciphertext = fteObj.encode(input_plaintext) output_plaintext, buffer = fteObj.decode(ciphertext) self.assertEquals( input_plaintext, output_plaintext ) def testConcat(self): for dfa in DFAS: for fixed_slice in FIXED_SLICES: fteObj = fte.encoder.DfaEncoder(dfa, fixed_slice) input_plaintext = fte.bit_ops.random_bytes(MSG_LEN) ciphertext = '' for i in range(CONCATS): ciphertext += fteObj.encode(input_plaintext) for i in range(CONCATS): output_plaintext, buffer = fteObj.decode(ciphertext) self.assertEquals( input_plaintext, output_plaintext ) ciphertext = buffer self.assertEquals( buffer, '' ) def suite(): loader = unittest.TestLoader() suite = unittest.TestSuite() suite.addTest(loader.loadTestsFromTestCase(Tests)) return suite libfte-0.1.0/fte/tests/test_encrypter.py000077500000000000000000000026661240634120100203270ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import random import fte.encrypter TRIALS = 2 ** 8 class Tests(unittest.TestCase): def setUp(self): self.encrypter = fte.encrypter.Encrypter() def testEncryptNoOp(self): for i in range(TRIALS): C = self.encrypter.encrypt('') for j in range(10): self.assertEquals(self.encrypter.decrypt(C), '') def testEncryptDecrypt_1(self): for i in range(TRIALS): P = 'X' * i C = self.encrypter.encrypt(P) self.assertNotEqual(C, P) for j in range(1): self.assertEquals(P, self.encrypter.decrypt(C)) def testEncryptDecrypt_2(self): for i in range(TRIALS): P = '\x01' * 2 ** 15 C = self.encrypter.encrypt(P) self.assertNotEqual(C, P) for j in range(1): self.assertEquals(P, self.encrypter.decrypt(C)) def testEncryptDecryptOneBlock(self): for i in range(TRIALS): M1 = random.randint(0, (1 << 128) - 1) M1 = fte.bit_ops.long_to_bytes(M1, 16) retval = self.encrypter.encryptOneBlock(M1) H_out = self.encrypter.decryptOneBlock(retval) self.assertEquals(M1, H_out) def suite(): loader = unittest.TestLoader() suite = unittest.TestSuite() suite.addTest(loader.loadTestsFromTestCase(Tests)) return suite libfte-0.1.0/requirements.txt000066400000000000000000000000111240634120100162220ustar00rootroot00000000000000pycrypto libfte-0.1.0/setup.cfg000066400000000000000000000000261240634120100145650ustar00rootroot00000000000000[build_ext] inplace=1 libfte-0.1.0/setup.py000066400000000000000000000023641240634120100144650ustar00rootroot00000000000000#!/usr/bin/env python from setuptools import setup from setuptools import Extension from setuptools.command.build_py import build_py as DistutilsBuild from setuptools.command.install import install as DistutilsInstall import glob import sys import os if os.name == 'nt': libraries = ['gmp.dll'] else: libraries = ['gmp'] fte_cDFA = Extension('fte.cDFA', include_dirs=['fte', ], extra_compile_args=['-O3', '-fPIC', ], libraries=libraries, sources=['fte/rank_unrank.cc', 'fte/cDFA.cc']) with open('fte/VERSION') as fh: LIBFTE_RELEASE = fh.read().strip() with open('README') as fh: long_description = fh.read() setup(name='fte', install_requires=['pycrypto'], package_data = {'fte': ['VERSION']}, test_suite = 'fte.tests.suite', version=LIBFTE_RELEASE, description='Format-Transforming Encryption', long_description=long_description, author='Kevin P. Dyer', author_email='kpdyer@gmail.com', url='https://github.com/kpdyer/libfte', ext_modules=[fte_cDFA], packages=['fte'], )