├── .gitignore ├── .pylintrc ├── .readthedocs.yaml ├── .testing.pylintrc ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── README.rst ├── doc ├── Makefile ├── conf.py ├── index.rst └── topics │ ├── aead.rst │ ├── dual.rst │ ├── kx.rst │ ├── public.rst │ ├── raw_generichash.rst │ ├── raw_hash.rst │ ├── raw_public.rst │ ├── raw_sealed.rst │ ├── raw_secret.rst │ ├── raw_sign.rst │ ├── releases │ ├── 1.0.0.rst │ ├── 1.1.0.rst │ ├── 1.2.0.rst │ ├── 1.3.0.rst │ ├── 1.3.1.rst │ ├── 1.3.2.rst │ ├── 1.3.3.rst │ ├── 1.3.4.rst │ ├── 1.4.0.rst │ ├── 1.4.1.rst │ ├── 1.4.2.rst │ ├── 1.4.3.rst │ ├── 1.4.4.rst │ ├── 1.4.5.rst │ ├── 1.5.0.rst │ ├── 1.5.1.rst │ ├── 1.5.2.rst │ ├── 1.6.0.rst │ ├── 1.6.1.rst │ ├── 1.7.1.rst │ ├── 1.7.rst │ ├── 1.9.0.rst │ ├── 2.0.0.rst │ ├── 2.1.0.rst │ └── index.rst │ ├── sealed.rst │ ├── secret.rst │ ├── sign.rst │ └── utils.rst ├── libnacl ├── __init__.py ├── aead.py ├── base.py ├── blake.py ├── dual.py ├── encode.py ├── kx.py ├── public.py ├── sealed.py ├── secret.py ├── secret_easy.py ├── sign.py └── utils.py ├── pkg ├── rpm │ └── python-libnacl.spec └── suse │ ├── python-libnacl.changes │ └── python-libnacl.spec ├── pyproject.toml └── tests ├── runtests.py └── unit ├── __init__.py ├── test_aead.py ├── test_auth_verify.py ├── test_blake.py ├── test_dual.py ├── test_kx.py ├── test_public.py ├── test_raw_auth_sym.py ├── test_raw_auth_sym_easy.py ├── test_raw_generichash.py ├── test_raw_hash.py ├── test_raw_public.py ├── test_raw_random.py ├── test_raw_secret.py ├── test_raw_secret_easy.py ├── test_raw_sign.py ├── test_save.py ├── test_seal.py ├── test_secret.py ├── test_secret_easy.py ├── test_sign.py ├── test_stream.py ├── test_verify.py └── test_version.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | bin/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | MANIFEST 25 | 26 | # Installer logs 27 | pip-log.txt 28 | pip-delete-this-directory.txt 29 | 30 | # Unit test / coverage reports 31 | htmlcov/ 32 | .tox/ 33 | .coverage 34 | .cache 35 | nosetests.xml 36 | coverage.xml 37 | 38 | # Translations 39 | *.mo 40 | 41 | # Mr Developer 42 | .mr.developer.cfg 43 | .project 44 | .pydevproject 45 | 46 | # Rope 47 | .ropeproject 48 | 49 | # Django stuff: 50 | *.log 51 | *.pot 52 | 53 | # Sphinx documentation 54 | doc/_build/ 55 | 56 | # Local VIM RC 57 | .lvimrc 58 | 59 | # pycharm 60 | .idea* -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # Specify a configuration file. 4 | #rcfile= 5 | 6 | # Python code to execute, usually for sys.path manipulation such as 7 | # pygtk.require(). 8 | init-hook=" 9 | exec 'aW1wb3J0IG9zLCBzeXMKCmlmICdWSVJUVUFMX0VOVicgaW4gb3MuZW52aXJvbjoKCiAgICB2ZV9k \ 10 | aXIgPSBvcy5lbnZpcm9uWydWSVJUVUFMX0VOViddCiAgICB2ZV9kaXIgaW4gc3lzLnBhdGggb3Ig \ 11 | c3lzLnBhdGguaW5zZXJ0KDAsIHZlX2RpcikKICAgIGFjdGl2YXRlX3RoaXMgPSBvcy5wYXRoLmpv \ 12 | aW4ob3MucGF0aC5qb2luKHZlX2RpciwgJ2JpbicpLCAnYWN0aXZhdGVfdGhpcy5weScpCgogICAg \ 13 | IyBGaXggZm9yIHdpbmRvd3MKICAgIGlmIG5vdCBvcy5wYXRoLmV4aXN0cyhhY3RpdmF0ZV90aGlz \ 14 | KToKICAgICAgICBhY3RpdmF0ZV90aGlzID0gb3MucGF0aC5qb2luKG9zLnBhdGguam9pbih2ZV9k \ 15 | aXIsICdTY3JpcHRzJyksICdhY3RpdmF0ZV90aGlzLnB5JykKCiAgICBleGVjZmlsZShhY3RpdmF0 \ 16 | ZV90aGlzLCBkaWN0KF9fZmlsZV9fPWFjdGl2YXRlX3RoaXMpKQo='.decode('base64')" 17 | 18 | 19 | # Profiled execution. 20 | profile=no 21 | 22 | # Add files or directories to the blacklist. They should be base names, not 23 | # paths. 24 | ignore=CVS 25 | 26 | # Pickle collected data for later comparisons. 27 | persistent=yes 28 | 29 | # List of plugins (as comma separated values of python modules names) to load, 30 | # usually to register additional checkers. 31 | load-plugins=salttesting.pylintplugins.pep8,salttesting.pylintplugins.pep263,salttesting.pylintplugins.strings 32 | 33 | 34 | [MESSAGES CONTROL] 35 | 36 | # Enable the message, report, category or checker with the given id(s). You can 37 | # either give multiple identifier separated by comma (,) or put this option 38 | # multiple time. See also the "--disable" option for examples. 39 | #enable= 40 | 41 | # Disable the message, report, category or checker with the given id(s). You 42 | # can either give multiple identifiers separated by comma (,) or put this 43 | # option multiple times (only on the command line, not in the configuration 44 | # file where it should appear only once).You can also use "--disable=all" to 45 | # disable everything first and then reenable specific checks. For example, if 46 | # you want to run only the similarities checker, you can use "--disable=all 47 | # --enable=similarities". If you want to run only the classes checker, but have 48 | # no Warning level messages displayed, use"--disable=all --enable=classes 49 | # --disable=W" 50 | disable=C0330 51 | 52 | # Disabled Checks 53 | # C0330 (bad-continuation) 54 | 55 | 56 | [REPORTS] 57 | 58 | # Set the output format. Available formats are text, parseable, colorized, msvs 59 | # (visual studio) and html. You can also give a reporter class, eg 60 | # mypackage.mymodule.MyReporterClass. 61 | output-format=text 62 | 63 | # Put messages in a separate file for each module / package specified on the 64 | # command line instead of printing them on stdout. Reports (if any) will be 65 | # written in a file name "pylint_global.[txt|html]". 66 | files-output=no 67 | 68 | # Tells whether to display a full report or only the messages 69 | reports=yes 70 | 71 | # Python expression which should return a note less than 10 (10 is the highest 72 | # note). You have access to the variables errors warning, statement which 73 | # respectively contain the number of errors / warnings messages and the total 74 | # number of statements analyzed. This is used by the global evaluation report 75 | # (RP0004). 76 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 77 | 78 | # Add a comment according to your evaluation note. This is used by the global 79 | # evaluation report (RP0004). 80 | comment=no 81 | 82 | # Template used to display messages. This is a python new-style format string 83 | # used to format the message information. See doc for all details 84 | msg-template='{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}' 85 | 86 | 87 | [VARIABLES] 88 | 89 | # Tells whether we should check for unused import in __init__ files. 90 | init-import=no 91 | 92 | # A regular expression matching the name of dummy variables (i.e. expectedly 93 | # not used). 94 | dummy-variables-rgx=_|dummy 95 | 96 | # List of additional names supposed to be defined in builtins. Remember that 97 | # you should avoid to define new builtins when possible. 98 | #additional-builtins= 99 | 100 | 101 | [FORMAT] 102 | 103 | # Maximum number of characters on a single line. 104 | max-line-length=80 105 | 106 | # Regexp for a line that is allowed to be longer than the limit. 107 | ignore-long-lines=^\s*(# )??$ 108 | 109 | # Allow the body of an if to be on the same line as the test if there is no 110 | # else. 111 | single-line-if-stmt=no 112 | 113 | # List of optional constructs for which whitespace checking is disabled 114 | #no-space-check=trailing-comma,dict-separator 115 | 116 | # Maximum number of lines in a module 117 | max-module-lines=3000 118 | 119 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 120 | # tab). 121 | indent-string=' ' 122 | 123 | # Number of spaces of indent required inside a hanging or continued line. 124 | indent-after-paren=4 125 | 126 | 127 | [LOGGING] 128 | 129 | # Logging modules to check that the string format arguments are in logging 130 | # function parameter format 131 | logging-modules=logging 132 | 133 | 134 | [TYPECHECK] 135 | 136 | # Tells whether missing members accessed in mixin class should be ignored. A 137 | # mixin class is detected if its name ends with "mixin" (case insensitive). 138 | ignore-mixin-members=yes 139 | 140 | # List of module names for which member attributes should not be checked 141 | # (useful for modules/projects where namespaces are manipulated during runtime 142 | # and thus extisting member attributes cannot be deduced by static analysis 143 | ignored-modules= 144 | 145 | # List of classes names for which member attributes should not be checked 146 | # (useful for classes with attributes dynamically set). 147 | ignored-classes=SQLObject 148 | 149 | # When zope mode is activated, add a predefined set of Zope acquired attributes 150 | # to generated-members. 151 | zope=no 152 | 153 | # List of members which are set dynamically and missed by pylint inference 154 | # system, and so shouldn't trigger E0201 when accessed. Python regular 155 | # expressions are accepted. 156 | generated-members=REQUEST,acl_users,aq_parent 157 | 158 | 159 | [MISCELLANEOUS] 160 | 161 | # List of note tags to take in consideration, separated by a comma. 162 | notes=FIXME,FIX,XXX,TODO 163 | 164 | 165 | [SIMILARITIES] 166 | 167 | # Minimum lines number of a similarity. 168 | min-similarity-lines=4 169 | 170 | # Ignore comments when computing similarities. 171 | ignore-comments=yes 172 | 173 | # Ignore docstrings when computing similarities. 174 | ignore-docstrings=yes 175 | 176 | # Ignore imports when computing similarities. 177 | ignore-imports=no 178 | 179 | 180 | [BASIC] 181 | 182 | # Required attributes for module, separated by a comma 183 | required-attributes= 184 | 185 | # List of builtins function names that should not be used, separated by a comma 186 | bad-functions=map,filter,apply,input 187 | 188 | # Good variable names which should always be accepted, separated by a comma 189 | #good-names=i,j,k,ex,Run,_,log 190 | good-names=pk,vk,sk,_,log,nacl 191 | 192 | # Bad variable names which should always be refused, separated by a comma 193 | bad-names=foo,bar,baz,toto,tutu,tata 194 | 195 | # Colon-delimited sets of names that determine each other's naming style when 196 | # the name regexes allow several styles. 197 | name-group= 198 | 199 | # Include a hint for the correct naming format with invalid-name 200 | include-naming-hint=no 201 | 202 | # Regular expression matching correct function names 203 | function-rgx=[a-z_][a-z0-9_]{2,30}$ 204 | 205 | # Naming hint for function names 206 | function-name-hint=[a-z_][a-z0-9_]{2,30}$ 207 | 208 | # Regular expression matching correct variable names 209 | variable-rgx=[a-z_][a-z0-9_]{2,30}$ 210 | 211 | # Naming hint for variable names 212 | variable-name-hint=[a-z_][a-z0-9_]{2,30}$ 213 | 214 | # Regular expression matching correct constant names 215 | const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 216 | 217 | # Naming hint for constant names 218 | const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 219 | 220 | # Regular expression matching correct attribute names 221 | attr-rgx=[a-z_][a-z0-9_]{2,30}$ 222 | 223 | # Naming hint for attribute names 224 | attr-name-hint=[a-z_][a-z0-9_]{2,30}$ 225 | 226 | # Regular expression matching correct argument names 227 | argument-rgx=[a-z_][a-z0-9_]{2,30}$ 228 | 229 | # Naming hint for argument names 230 | argument-name-hint=[a-z_][a-z0-9_]{2,30}$ 231 | 232 | # Regular expression matching correct class attribute names 233 | class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ 234 | 235 | # Naming hint for class attribute names 236 | class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ 237 | 238 | # Regular expression matching correct inline iteration names 239 | inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ 240 | 241 | # Naming hint for inline iteration names 242 | inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ 243 | 244 | # Regular expression matching correct class names 245 | class-rgx=[A-Z_][a-zA-Z0-9]+$ 246 | 247 | # Naming hint for class names 248 | class-name-hint=[A-Z_][a-zA-Z0-9]+$ 249 | 250 | # Regular expression matching correct module names 251 | module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 252 | 253 | # Naming hint for module names 254 | module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 255 | 256 | # Regular expression matching correct method names 257 | method-rgx=[a-z_][a-z0-9_]{2,30}$ 258 | 259 | # Naming hint for method names 260 | method-name-hint=[a-z_][a-z0-9_]{2,30}$ 261 | 262 | # Regular expression which should only match function or class names that do 263 | # not require a docstring. 264 | no-docstring-rgx=__.*__ 265 | 266 | # Minimum line length for functions/classes that require docstrings, shorter 267 | # ones are exempt. 268 | docstring-min-length=-1 269 | 270 | 271 | [CLASSES] 272 | 273 | # List of interface methods to ignore, separated by a comma. This is used for 274 | # instance to not check methods defines in Zope's Interface base class. 275 | ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by 276 | 277 | # List of method names used to declare (i.e. assign) instance attributes. 278 | defining-attr-methods=__init__,__new__,setUp 279 | 280 | # List of valid names for the first argument in a class method. 281 | valid-classmethod-first-arg=cls 282 | 283 | # List of valid names for the first argument in a metaclass class method. 284 | valid-metaclass-classmethod-first-arg=mcs 285 | 286 | 287 | [IMPORTS] 288 | 289 | # Deprecated modules which should not be used, separated by a comma 290 | deprecated-modules=regsub,string,TERMIOS,Bastion,rexec 291 | 292 | # Create a graph of every (i.e. internal and external) dependencies in the 293 | # given file (report RP0402 must not be disabled) 294 | import-graph= 295 | 296 | # Create a graph of external dependencies in the given file (report RP0402 must 297 | # not be disabled) 298 | ext-import-graph= 299 | 300 | # Create a graph of internal dependencies in the given file (report RP0402 must 301 | # not be disabled) 302 | int-import-graph= 303 | 304 | 305 | [DESIGN] 306 | 307 | # Maximum number of arguments for function / method 308 | max-args=35 309 | 310 | # Argument names that match this expression will be ignored. Default to name 311 | # with leading underscore 312 | ignored-argument-names=_.* 313 | 314 | # Maximum number of locals for function / method body 315 | max-locals=40 316 | 317 | # Maximum number of return / yield for function / method body 318 | max-returns=6 319 | 320 | # Maximum number of branch for function / method body 321 | max-branches=12 322 | 323 | # Maximum number of statements in function / method body 324 | max-statements=100 325 | 326 | # Maximum number of parents for a class (see R0901). 327 | max-parents=7 328 | 329 | # Maximum number of attributes for a class (see R0902). 330 | max-attributes=7 331 | 332 | # Minimum number of public methods for a class (see R0903). 333 | min-public-methods=2 334 | 335 | # Maximum number of public methods for a class (see R0904). 336 | max-public-methods=20 337 | 338 | 339 | [EXCEPTIONS] 340 | 341 | # Exceptions that will emit a warning when being caught. Defaults to 342 | # "Exception" 343 | overgeneral-exceptions=Exception 344 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yaml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Set the version of Python and other tools you might need 9 | build: 10 | os: ubuntu-22.04 11 | tools: 12 | python: "3.11" 13 | 14 | # Build documentation in the docs/ directory with Sphinx 15 | sphinx: 16 | configuration: doc/conf.py 17 | 18 | # We recommend specifying your dependencies to enable reproducible builds: 19 | # https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html 20 | # python: 21 | # install: 22 | # - requirements: docs/requirements.txt 23 | 24 | -------------------------------------------------------------------------------- /.testing.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # Specify a configuration file. 4 | rcfile=.pylintrc 5 | 6 | [MESSAGES CONTROL] 7 | 8 | # Disable the message, report, category or checker with the given id(s). You 9 | # can either give multiple identifiers separated by comma (,) or put this 10 | # option multiple times (only on the command line, not in the configuration 11 | # file where it should appear only once).You can also use "--disable=all" to 12 | # disable everything first and then reenable specific checks. For example, if 13 | # you want to run only the similarities checker, you can use "--disable=all 14 | # --enable=similarities". If you want to run only the classes checker, but have 15 | # no Warning level messages displayed, use"--disable=all --enable=classes 16 | # --disable=W" 17 | disable=R, 18 | I0011, 19 | I0013, 20 | E1101, 21 | E1103, 22 | C0102, 23 | C0103, 24 | C0111, 25 | C0203, 26 | C0204, 27 | C0301, 28 | C0302, 29 | C0330, 30 | W0110, 31 | W0122, 32 | W0142, 33 | W0201, 34 | W0212, 35 | W0404, 36 | W0511, 37 | W0603, 38 | W0612, 39 | W0613, 40 | W0621, 41 | W0622, 42 | W0631, 43 | W0704, 44 | F0220, 45 | F0401, 46 | E8501, 47 | E8121, 48 | E8122, 49 | E8123, 50 | E8124, 51 | E8125, 52 | E8126, 53 | E8127, 54 | E8128 55 | 56 | [REPORTS] 57 | 58 | # Include message's id in output 59 | include-ids=yes 60 | 61 | # Include symbolic ids of messages in output 62 | symbols=no 63 | 64 | # Tells whether to display a full report or only the messages 65 | reports=no 66 | 67 | # Set the output format. Available formats are text, parseable, colorized, msvs 68 | # (visual studio) and html 69 | # output-format=parseable 70 | msg-template='{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}' 71 | 72 | # Put messages in a separate file for each module / package specified on the 73 | # command line instead of printing them on stdout. Reports (if any) will be 74 | # written in a file name "pylint_global.[txt|html]". 75 | files-output=no 76 | 77 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | dist: bionic 3 | language: python 4 | python: 5 | - "2.7" 6 | - "3.5" 7 | - "3.6" 8 | - "3.7" 9 | - "pypy2" 10 | - "pypy3" 11 | 12 | install: 13 | - sudo apt-get update -qq 14 | - sudo apt-get install -y libsodium23 15 | - "python -m pip install -U pip setuptools" 16 | 17 | script: 18 | - "python -m unittest discover --start-directory tests -v" 19 | 20 | # until the libsodium source is approved by Travis 21 | # addons: 22 | # apt: 23 | # sources: 24 | # - chris-lea/libsodium 25 | # packages: 26 | # - libsodium13 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {2023} Thomas S Hatch 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | recursive-include tests *.py 4 | recursive-include doc * 5 | recursive-include pkg * 6 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============== 2 | Python libnacl 3 | ============== 4 | 5 | This library is used to gain direct access to the functions exposed by 6 | Daniel J. Bernstein's nacl library via libsodium. It has 7 | been constructed to maintain extensive documentation on how to use nacl 8 | as well as being completely portable. The file in libnacl/__init__.py 9 | can be pulled out and placed directly in any project to give a single file 10 | binding to all of nacl. 11 | 12 | Higher Level Classes 13 | ==================== 14 | 15 | The libnacl code also ships with many high level classes which make nacl 16 | cryptography easy and safe, for documentation please see: 17 | http://libnacl.readthedocs.org/ 18 | 19 | Why libnacl 20 | =========== 21 | 22 | There are a number of libraries out there binding to libsodium, so why make 23 | libnacl? 24 | 25 | 1. libnacl does not have any non-python hard deps outside of libsodium 26 | 2. libnacl does not need to be compiled 27 | 3. libnacl is easy to package and very portable 28 | 4. Inclusion of high level pythonic encryption classes 29 | 5. Ability to have a single embeddable and transferable bindings file 30 | that can be added directly to python applications without needing 31 | to dep libnacl 32 | 33 | This makes libnacl very portable, very easy to use and easy to distribute. 34 | 35 | Install 36 | ======= 37 | 38 | The libnacl code is easiy installed via a setup.py from the source or via pip. 39 | 40 | From Source: 41 | 42 | .. code-block:: bash 43 | 44 | tar xvf libnacl-1.5.2.tar.gz 45 | cd libnacl-1.5.2 46 | python setup.py install 47 | 48 | Via Pip: 49 | 50 | .. code-block:: bash 51 | 52 | pip install libnacl 53 | 54 | Remember that libnacl can be installed for python 2 and 3. 55 | 56 | Linux distributions 57 | ------------------- 58 | 59 | Libnacl is shiped with many linux distributions, check your distribution 60 | package manager for the package ``python-libnacl``, ``python2-libnacl`` 61 | and/or ``python3-libnacl``. 62 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Python-NaCl.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Python-NaCl.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Python-NaCl" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Python-NaCl" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # libnacl documentation build configuration file, created by 4 | # sphinx-quickstart on Thu May 29 10:29:25 2014. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | sys.path.insert(0, os.path.abspath('..')) 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | #sys.path.insert(0, os.path.abspath('.')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | #needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [ 33 | 'sphinx.ext.autodoc', 34 | ] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'libnacl' 50 | copyright = u'2023, Thomas S Hatch' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | # The full version, including alpha/beta/rc tags. 58 | release = "2.1.0" 59 | version = release 60 | # The language for content autogenerated by Sphinx. Refer to documentation 61 | # for a list of supported languages. 62 | #language = None 63 | 64 | # There are two options for replacing |today|: either, you set today to some 65 | # non-false value, then it is used: 66 | #today = '' 67 | # Else, today_fmt is used as the format for a strftime call. 68 | #today_fmt = '%B %d, %Y' 69 | 70 | # List of patterns, relative to source directory, that match files and 71 | # directories to ignore when looking for source files. 72 | exclude_patterns = ['_build'] 73 | 74 | # The reST default role (used for this markup: `text`) to use for all 75 | # documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output ---------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | #html_theme = 'default' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | #html_static_path = ['_static'] 133 | 134 | # Add any extra paths that contain custom files (such as robots.txt or 135 | # .htaccess) here, relative to this directory. These files are copied 136 | # directly to the root of the documentation. 137 | #html_extra_path = [] 138 | 139 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 140 | # using the given strftime format. 141 | #html_last_updated_fmt = '%b %d, %Y' 142 | 143 | # If true, SmartyPants will be used to convert quotes and dashes to 144 | # typographically correct entities. 145 | #html_use_smartypants = True 146 | 147 | # Custom sidebar templates, maps document names to template names. 148 | #html_sidebars = {} 149 | 150 | # Additional templates that should be rendered to pages, maps page names to 151 | # template names. 152 | #html_additional_pages = {} 153 | 154 | # If false, no module index is generated. 155 | #html_domain_indices = True 156 | 157 | # If false, no index is generated. 158 | #html_use_index = True 159 | 160 | # If true, the index is split into individual pages for each letter. 161 | #html_split_index = False 162 | 163 | # If true, links to the reST sources are added to the pages. 164 | #html_show_sourcelink = True 165 | 166 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 167 | #html_show_sphinx = True 168 | 169 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 170 | #html_show_copyright = True 171 | 172 | # If true, an OpenSearch description file will be output, and all pages will 173 | # contain a tag referring to it. The value of this option must be the 174 | # base URL from which the finished HTML is served. 175 | #html_use_opensearch = '' 176 | 177 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 178 | #html_file_suffix = None 179 | 180 | # Output file base name for HTML help builder. 181 | #htmlhelp_basename = 'libnacl' 182 | 183 | 184 | # -- Options for LaTeX output --------------------------------------------- 185 | 186 | latex_elements = { 187 | # The paper size ('letterpaper' or 'a4paper'). 188 | #'papersize': 'letterpaper', 189 | 190 | # The font size ('10pt', '11pt' or '12pt'). 191 | #'pointsize': '10pt', 192 | 193 | # Additional stuff for the LaTeX preamble. 194 | #'preamble': '', 195 | } 196 | 197 | # Grouping the document tree into LaTeX files. List of tuples 198 | # (source start file, target name, title, 199 | # author, documentclass [howto, manual, or own class]). 200 | latex_documents = [ 201 | ('index', 'libnacl.tex', u'libnacl Documentation', 202 | u'Thomas S Hatch', 'manual'), 203 | ] 204 | 205 | # The name of an image file (relative to this directory) to place at the top of 206 | # the title page. 207 | #latex_logo = None 208 | 209 | # For "manual" documents, if this is true, then toplevel headings are parts, 210 | # not chapters. 211 | #latex_use_parts = False 212 | 213 | # If true, show page references after internal links. 214 | #latex_show_pagerefs = False 215 | 216 | # If true, show URL addresses after external links. 217 | #latex_show_urls = False 218 | 219 | # Documents to append as an appendix to all manuals. 220 | #latex_appendices = [] 221 | 222 | # If false, no module index is generated. 223 | #latex_domain_indices = True 224 | 225 | 226 | # -- Options for manual page output --------------------------------------- 227 | 228 | # One entry per manual page. List of tuples 229 | # (source start file, name, description, authors, manual section). 230 | man_pages = [ 231 | ('index', 'libnacl', u'libnacl Documentation', 232 | [u'Thomas S Hatch'], 1) 233 | ] 234 | 235 | # If true, show URL addresses after external links. 236 | #man_show_urls = False 237 | 238 | 239 | # -- Options for Texinfo output ------------------------------------------- 240 | 241 | # Grouping the document tree into Texinfo files. List of tuples 242 | # (source start file, target name, title, author, 243 | # dir menu entry, description, category) 244 | texinfo_documents = [ 245 | ('index', 'libnacl', u'libnacl Documentation', 246 | u'Thomas S Hatch', 'libnacl', 'One line description of project.', 247 | 'Miscellaneous'), 248 | ] 249 | 250 | # Documents to append as an appendix to all manuals. 251 | #texinfo_appendices = [] 252 | 253 | # If false, no module index is generated. 254 | #texinfo_domain_indices = True 255 | 256 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 257 | #texinfo_show_urls = 'footnote' 258 | 259 | # If true, do not generate a @detailmenu in the "Top" node's menu. 260 | #texinfo_no_detailmenu = False 261 | 262 | 263 | # -- Options for Epub output ---------------------------------------------- 264 | 265 | # Bibliographic Dublin Core info. 266 | epub_title = u'libnacl' 267 | epub_author = u'Thomas S Hatch' 268 | epub_publisher = u'Thomas S Hatch' 269 | epub_copyright = u'2023, Thomas S Hatch' 270 | 271 | # The basename for the epub file. It defaults to the project name. 272 | #epub_basename = u'libnacl' 273 | 274 | # The HTML theme for the epub output. Since the default themes are not optimized 275 | # for small screen space, using the same theme for HTML and epub output is 276 | # usually not wise. This defaults to 'epub', a theme designed to save visual 277 | # space. 278 | #epub_theme = 'epub' 279 | 280 | # The language of the text. It defaults to the language option 281 | # or en if the language is not set. 282 | #epub_language = '' 283 | 284 | # The scheme of the identifier. Typical schemes are ISBN or URL. 285 | #epub_scheme = '' 286 | 287 | # The unique identifier of the text. This can be a ISBN number 288 | # or the project homepage. 289 | #epub_identifier = '' 290 | 291 | # A unique identification for the text. 292 | #epub_uid = '' 293 | 294 | # A tuple containing the cover image and cover page html template filenames. 295 | #epub_cover = () 296 | 297 | # A sequence of (type, uri, title) tuples for the guide element of content.opf. 298 | #epub_guide = () 299 | 300 | # HTML files that should be inserted before the pages created by sphinx. 301 | # The format is a list of tuples containing the path and title. 302 | #epub_pre_files = [] 303 | 304 | # HTML files shat should be inserted after the pages created by sphinx. 305 | # The format is a list of tuples containing the path and title. 306 | #epub_post_files = [] 307 | 308 | # A list of files that should not be packed into the epub file. 309 | #epub_exclude_files = [] 310 | 311 | # The depth of the table of contents in toc.ncx. 312 | #epub_tocdepth = 3 313 | 314 | # Allow duplicate toc entries. 315 | #epub_tocdup = True 316 | 317 | # Choose between 'default' and 'includehidden'. 318 | #epub_tocscope = 'default' 319 | 320 | # Fix unsupported image types using the PIL. 321 | #epub_fix_images = False 322 | 323 | # Scale large images. 324 | #epub_max_image_width = 0 325 | 326 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 327 | #epub_show_urls = 'inline' 328 | 329 | # If false, no index is generated. 330 | #epub_use_index = True 331 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | libnacl: Python bindings to NaCl 2 | ================================ 3 | 4 | Contents: 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | topics/public 10 | topics/sealed 11 | topics/secret 12 | topics/sign 13 | topics/dual 14 | topics/aead 15 | topics/utils 16 | topics/raw_public 17 | topics/raw_sealed 18 | topics/raw_secret 19 | topics/raw_sign 20 | topics/raw_hash 21 | topics/raw_generichash 22 | topics/releases/index 23 | 24 | 25 | Indices and tables 26 | ================== 27 | 28 | * :ref:`genindex` 29 | * :ref:`modindex` 30 | * :ref:`search` 31 | -------------------------------------------------------------------------------- /doc/topics/aead.rst: -------------------------------------------------------------------------------- 1 | ============================================= 2 | Authenticated Encryption with Associated Data 3 | ============================================= 4 | 5 | One of the most powerful symmetric encryption models available i s known as AEAD. 6 | The libsodium library enables four models of AEAD encryption. As of libnacl 2.0 7 | we expose 3 of them. 8 | 9 | Using AEAD with libnacl is very easy and can be executed following the same models 10 | as the rest of libnacl. 11 | 12 | The recommended algorithm to use is `XChaCha20-Poly1305-IETF`. Some organizations 13 | require the use of AES, in these cases please use AESGCM. 14 | 15 | For more information on AEAD please see the libsodium documentation 16 | 17 | Using the AEAD system is very easy. 18 | 19 | .. code-block:: python 20 | 21 | import libnacl.aead 22 | 23 | msg = b"Our King? Well i didn't vote for you!!" 24 | aad = b'\x00\x11\x22\x33' 25 | box = libnacl.aead.AEAD_XCHACHA() 26 | ctxt = box.encrypt(msg, aad) 27 | 28 | box2 = libnacl.aead.AEAD_XCHACHA(box.sk) 29 | clear1 = box.decrypt(ctxt, len(aad)) 30 | 31 | ctxt2 = box2.encrypt(msg, aad) 32 | clear3 = box.decrypt(ctxt2, len(aad)) 33 | 34 | -------------------------------------------------------------------------------- /doc/topics/dual.rst: -------------------------------------------------------------------------------- 1 | =================== 2 | Dual Key Management 3 | =================== 4 | 5 | The libnacl library abstracts a "Dual Key" model. The Dual Key creates a single 6 | key management object that can be used for both signing and encrypting, it 7 | generates and maintains a Curve25519 encryption key pair and an ED25519 signing 8 | keypair. All methods for encryption and signing work with and from Dual Keys. 9 | 10 | To encrypt messages using Dual Keys: 11 | 12 | .. code-block:: python 13 | 14 | import libnacl.dual 15 | 16 | # Define a message to send 17 | msg = b"You've got two empty halves of coconut and you're bangin' 'em together." 18 | 19 | # Generate the key pairs for Alice and bob, if secret keys already exist 20 | # they can be passed in, otherwise new keys will be automatically generated 21 | bob = libnacl.dual.DualSecret() 22 | alice = libnacl.dual.DualSecret() 23 | 24 | # Create the boxes, this is an object which represents the combination of the 25 | # sender's secret key and the receiver's public key 26 | bob_box = libnacl.public.Box(bob.sk, alice.pk) 27 | alice_box = libnacl.public.Box(alice.sk, bob.pk) 28 | 29 | # Bob's box encrypts messages for Alice 30 | bob_ctxt = bob_box.encrypt(msg) 31 | # Alice's box decrypts messages from Bob 32 | bclear = alice_box.decrypt(bob_ctxt) 33 | # Alice can send encrypted messages which only Bob can decrypt 34 | alice_ctxt = alice_box.encrypt(msg) 35 | aclear = alice_box.decrypt(alice_ctxt) 36 | 37 | .. note:: 38 | 39 | Every encryption routine requires a nonce. The nonce is a 24 char string 40 | that must never be used twice with the same keypair. If no nonce is passed 41 | in then a nonce is generated based on random data. 42 | If it is desired to generate a nonce manually this can be done by passing 43 | it into the encrypt method. 44 | 45 | DualKey Object 46 | ============== 47 | 48 | The DualKey object is used to manage both public and secret keys, this object 49 | contains a number of methods for both convenience and utility. The key data is 50 | also available. 51 | 52 | Keys 53 | ---- 54 | 55 | The raw public key is available as DualKey.pk, to generate a hex encoded 56 | version of the key the pk_hex method is available: 57 | 58 | .. code-block:: python 59 | 60 | import libnacl.dual 61 | 62 | fred = libnacl.dual.DualSecret() 63 | 64 | raw_sk = fred.sk 65 | hex_sk = fred.hex_sk() 66 | 67 | raw_pk = fred.pk 68 | hex_pk = fred.hex_pk() 69 | 70 | By saving only the binary keys in memory libnacl ensures that the minimal 71 | memory footprint is needed. 72 | 73 | Saving Keys to Disk 74 | =================== 75 | 76 | All libnacl key objects can be safely saved to disk via the save method. This 77 | method changes the umask before saving the key file to ensure that the saved 78 | file can only be read by the user creating it and cannot be written to. 79 | When using dual keys the encrypting and signing keys will be saved togather in 80 | a single file. 81 | 82 | .. code-block:: python 83 | 84 | import libnacl.dual 85 | 86 | fred = libnacl.dual.DualSecret() 87 | fred.save('/etc/nacl/fred.key') 88 | -------------------------------------------------------------------------------- /doc/topics/kx.rst: -------------------------------------------------------------------------------- 1 | ======================= 2 | Key Exchange Encryption 3 | ======================= 4 | 5 | The X25519 key exchange algorithm in libsodium allows for key exchange encryption 6 | to be safely executed. The ExchangeKey class makes it easy to use key exchange wrapping 7 | AEAD encryption. This class works similarly to sealed boxes, but offers more functionality 8 | and better security. 9 | 10 | When using the ExchangeKey encryption class you can select which AEAD encryption 11 | subsystem to use, but it is recommended to stick with the default XChaCha algorithm. 12 | The options are: `aesgcm` for the AES256-GCM construct, `xchacha` for the XChaCha20-Poly1305-IETF 13 | construct, and `chacha` for the ChaCha20-Poly1305-IETF construct. 14 | 15 | To use the ExchangeKey system, simply create an ExchangeKey class for `bob` and `alice` 16 | and then encrypt a message and additional unencrypted data and send them back and forth. 17 | 18 | In this example, bob acts as the client, and alice acts as the server. The underlying 19 | nature of the connections are irrelevant, just that once end needs to call the server 20 | functions and the other needs to call the client functions. 21 | 22 | .. code-block:: python 23 | 24 | # Import libnacl libs 25 | import libnacl.kx 26 | 27 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 28 | aad = b'A Duck!' 29 | # Make Bob and Alice Exchange Keys 30 | bob = libnacl.kx.ExchangeKey() 31 | alice = libnacl.kx.ExchangeKey() 32 | # Encrypt with bob as client and alice as server 33 | bob_ctxt = bob.encrypt_client(alice.kx_pk, msg, aad) 34 | bclear, clear_aad = alice.decrypt_server(bob.kx_pk, bob_ctxt, len(aad)) 35 | # Similarly you can have alice encrypt as server and bob decrypt as client 36 | alice_ctxt = alice.encrypt_server(bob.kx_pk, msg, aad) 37 | aclear, clear_aad = bob.decrypt_client(alice.kx_pk, alice_ctxt, len(aad)) 38 | 39 | -------------------------------------------------------------------------------- /doc/topics/public.rst: -------------------------------------------------------------------------------- 1 | ===================== 2 | Public Key Encryption 3 | ===================== 4 | 5 | Unlike traditional means for public key asymmetric encryption, the nacl 6 | encryption systems are very high speed. The CurveCP network protocol for 7 | instance only uses public key encryption for all transport. 8 | 9 | Public key encryption is very simple, as is evidenced with this communication 10 | between Alice and Bob: 11 | 12 | .. code-block:: python 13 | 14 | import libnacl.public 15 | 16 | # Define a message to send 17 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 18 | 19 | # Generate the key pairs for Alice and bob, if secret keys already exist 20 | # they can be passed in, otherwise new keys will be automatically generated 21 | bob = libnacl.public.SecretKey() 22 | alice = libnacl.public.SecretKey() 23 | 24 | # Create the boxes, this is an object which represents the combination of the 25 | # sender's secret key and the receiver's public key 26 | bob_box = libnacl.public.Box(bob.sk, alice.pk) 27 | alice_box = libnacl.public.Box(alice.sk, bob.pk) 28 | 29 | # Bob's box encrypts messages for Alice 30 | bob_ctxt = bob_box.encrypt(msg) 31 | # Alice's box decrypts messages from Bob 32 | bclear = alice_box.decrypt(bob_ctxt) 33 | # Alice can send encrypted messages which only Bob can decrypt 34 | alice_ctxt = alice_box.encrypt(msg) 35 | aclear = bob_box.decrypt(alice_ctxt) 36 | 37 | .. note:: 38 | 39 | Every encryption routine requires a nonce. The nonce is a 24 char string 40 | that must never be used twice with the same keypair. If no nonce is passed 41 | in then a nonce is generated based on random data. 42 | If it is desired to generate a nonce manually this can be done by passing 43 | it into the encrypt method. 44 | 45 | .. _secretkey-object: 46 | 47 | SecretKey Object 48 | ================ 49 | 50 | The SecretKey object is used to manage both public and secret keys, this object 51 | contains a number of methods for both convenience and utility. The key data is 52 | also available. 53 | 54 | Keys 55 | ---- 56 | 57 | The raw public key is available as SecretKey.sk, to generate a hex encoded 58 | version of the key the sk_hex method is available. The same items are 59 | available for the public keys: 60 | 61 | .. code-block:: python 62 | 63 | import libnacl.public 64 | 65 | fred = libnacl.public.SecretKey() 66 | 67 | raw_sk = fred.sk 68 | hex_sk = fred.hex_sk() 69 | 70 | raw_pk = fred.pk 71 | hex_pk = fred.hex_pk() 72 | 73 | By saving only the binary keys in memory libnacl ensures that the minimal 74 | memory footprint is needed. 75 | 76 | .. _publickey-object: 77 | 78 | PublicKey Object 79 | ================ 80 | 81 | To manage only the public key end, a public key object exists: 82 | 83 | .. code-block:: python 84 | 85 | import libnacl.public 86 | 87 | tom_secret = libnacl.public.SecretKey() 88 | 89 | tom = libnacl.public.PublicKey(tom_secret.pk) 90 | 91 | raw_pk = tom.pk 92 | hex_pk = tom.hex_pk() 93 | 94 | Saving Keys to Disk 95 | =================== 96 | 97 | All libnacl key objects can be safely saved to disk via the save method. This 98 | method changes the umask before saving the key file to ensure that the saved 99 | file can only be read by the user creating it and cannot be written to. 100 | 101 | .. code-block:: python 102 | 103 | import libnacl.public 104 | 105 | fred = libnacl.public.SecretKey() 106 | fred.save('/etc/nacl/fred.key') 107 | -------------------------------------------------------------------------------- /doc/topics/raw_generichash.rst: -------------------------------------------------------------------------------- 1 | ==================================== 2 | Raw Generic Hash (Blake2b) Functions 3 | ==================================== 4 | 5 | The nacl library comes with blake hashing libraries. 6 | 7 | More information on Blake can be found here: 8 | https://blake2.net 9 | 10 | The blake2b hashing algorithm is a keyed hashing algorithm, which allows 11 | for a key to be associated with a hash. Blake can be executed with or without 12 | a key. 13 | 14 | With a key (they key can should be between 16 and 64 bytes): 15 | 16 | .. code-block:: python 17 | 18 | import libnacl 19 | 20 | msg = 'Is there someone else up there we could talk to?' 21 | key = libnacl.randombytes(32) 22 | h_msg = libnacl.crypto_generichash(msg, key) 23 | 24 | Without a key: 25 | 26 | .. code-block:: python 27 | 28 | import libnacl 29 | 30 | msg = 'Is there someone else up there we could talk to?' 31 | h_msg = libnacl.crypto_generichash(msg) 32 | -------------------------------------------------------------------------------- /doc/topics/raw_hash.rst: -------------------------------------------------------------------------------- 1 | ================== 2 | Raw Hash Functions 3 | ================== 4 | 5 | The nacl library comes with sha256 and sha512 hashing libraries. They do not 6 | seem to offer any benefit over python's hashlib, but for completeness they are 7 | included. Creating a hash of a message is very simple: 8 | 9 | .. code-block:: python 10 | 11 | import libnacl 12 | 13 | msg = 'Is there someone else up there we could talk to?' 14 | h_msg = libnacl.crypto_hash(msg) 15 | 16 | crypto_hash defaults to sha256, sha512 is also available: 17 | 18 | .. code-block:: python 19 | 20 | import libnacl 21 | 22 | msg = 'Is there someone else up there we could talk to?' 23 | h_msg = libnacl.crypto_hash_sha512(msg) 24 | -------------------------------------------------------------------------------- /doc/topics/raw_public.rst: -------------------------------------------------------------------------------- 1 | ========================= 2 | Raw Public Key Encryption 3 | ========================= 4 | 5 | .. note:: 6 | 7 | While these routines are perfectly safe, higher level convenience 8 | wrappers are under development to make these routines easier. 9 | 10 | Public key encryption inside the nacl library has been constructed to ensure 11 | that all cryptographic routines are executed correctly and safely. 12 | 13 | The public key encryption is executed via the functions which begin with 14 | `crypto_box` and can be easily executed. 15 | 16 | First generate a public key and secret key keypair for the two communicating 17 | parties, who for tradition's sake, will be referred to as Alice and Bob: 18 | 19 | .. code-block:: python 20 | 21 | import libnacl 22 | 23 | alice_pk, alice_sk = libnacl.crypto_box_keypair() 24 | bob_pk, bob_sk = libnacl.crypto_box_keypair() 25 | 26 | Once the keys have been generated a cryptographic box needs to be created. The 27 | cryptographic box takes the party's secret key and the receiving party's public 28 | key. These are used to create a message which is both signed and encrypted. 29 | 30 | Before creating the box a nonce is required. The nonce is a 24 character 31 | string which should only be used for this message, the nonce should never be 32 | reused. This means that the nonce needs to be generated in such a way that 33 | the probability of reusing the nonce string with the same keypair is very 34 | low. The libnacl wrapper ships with a convenience function which generates a 35 | nonce from random bytes: 36 | 37 | .. code-block:: python 38 | 39 | import libnacl.utils 40 | nonce = libnacl.utils.rand_nonce() 41 | 42 | Now, with a nonce a cryptographic box can be created, Alice will send a 43 | message: 44 | 45 | .. code-block:: python 46 | 47 | msg = 'Quiet, quiet. Quiet! There are ways of telling whether she is a witch.' 48 | box = libnacl.crypto_box(msg, nonce, bob_pk, alice_sk) 49 | 50 | Now with a box in hand it can be decrypted by Bob: 51 | 52 | .. code-block:: python 53 | 54 | clear_msg = libnacl.crypto_box_open(box, nonce, alice_pk, bob_sk) 55 | 56 | The trick here is that the box AND the nonce need to be sent to Bob, so he can 57 | decrypt the message. The nonce can be safely sent to Bob in the clear. 58 | 59 | To bring it all together: 60 | 61 | .. code-block:: python 62 | 63 | import libnacl 64 | import libnacl.utils 65 | 66 | alice_pk, alice_sk = libnacl.crypto_box_keypair() 67 | bob_pk, bob_sk = libnacl.crypto_box_keypair() 68 | 69 | nonce = libnacl.utils.rand_nonce() 70 | 71 | msg = 'Quiet, quiet. Quiet! There are ways of telling whether she is a witch.' 72 | box = libnacl.crypto_box(msg, nonce, bob_pk, alice_sk) 73 | 74 | clear_msg = libnacl.crypto_box_open(box, nonce, alice_pk, bob_sk) 75 | -------------------------------------------------------------------------------- /doc/topics/raw_sealed.rst: -------------------------------------------------------------------------------- 1 | ========================= 2 | Raw Sealed Box Encryption 3 | ========================= 4 | 5 | Sealed box is a variant of :doc:`public key encryption scheme ` 6 | where the sender is not authenticated. This is done by generating an 7 | ephemeral key pair, which the public key is prefixed to the cipher text. 8 | 9 | First, generate a keypair for the receiver. The sender doesn't need a keypair. 10 | 11 | .. code-block:: python 12 | 13 | import libnacl 14 | 15 | pk, sk = libnacl.crypto_box_keypair() 16 | 17 | Then a sealed box is created by the sender, using the receiver's public key 18 | 19 | .. code-block:: python 20 | 21 | msg = 'Quiet, quiet. Quiet! There are ways of telling whether she is a witch.' 22 | box = libnacl.crypto_box_seal(msg, pk) 23 | 24 | The receiver then can decrypt the box using their keypair. 25 | 26 | .. code-block:: python 27 | 28 | clear_msg = libnacl.crypto_box_seal_open(box, pk, sk) 29 | 30 | To bring it all together: 31 | 32 | .. code-block:: python 33 | 34 | import libnacl 35 | 36 | pk, sk = libnacl.crypto_box_keypair() 37 | 38 | msg = 'Quiet, quiet. Quiet! There are ways of telling whether she is a witch.' 39 | box = libnacl.crypto_box_seal(msg, pk) 40 | 41 | clear_msg = libnacl.crypto_box_seal_open(box, pk, sk) 42 | -------------------------------------------------------------------------------- /doc/topics/raw_secret.rst: -------------------------------------------------------------------------------- 1 | ========================= 2 | Raw Secret Key Encryption 3 | ========================= 4 | 5 | .. note:: 6 | 7 | While these routines are perfectly safe, higher level convenience 8 | wrappers are under development to make these routines easier. 9 | 10 | Secret key encryption is high speed encryption based on a shared secret key. 11 | 12 | .. note:: 13 | 14 | The nacl library uses the salsa20 stream encryption cipher for secret key 15 | encryption, more information about the salsa20 cipher can be found here: 16 | http://cr.yp.to/salsa20.html 17 | 18 | The means of encryption assumes that the two sides of the conversation both 19 | have access to the same shared secret key. First generate a secret key, libnacl 20 | provides a convenience function for the generation of this key called 21 | libnacl.utils.salsa_key, then generate a nonce, a new nonce should be used 22 | every time a new message is encrypted. A convenience function to create a unique 23 | nonce based on random bytes: 24 | 25 | .. code-block:: python 26 | 27 | import libnacl 28 | import libnacl.utils 29 | 30 | key = libnacl.utils.salsa_key() 31 | nonce = libnacl.utils.rand_nonce() 32 | 33 | With the key and nonce in hand, the cryptographic secret box can now be 34 | generated: 35 | 36 | .. code-block:: python 37 | 38 | msg = 'Who are you who are so wise in the ways of science?' 39 | box = libnacl.crypto_secretbox(msg, nonce, key) 40 | 41 | Now the message can be decrypted on the other end. The nonce and the key are 42 | both required to decrypt: 43 | 44 | .. code-block:: python 45 | 46 | clear_msg = libnacl.crypto_secretbox_open(box, nonce, key) 47 | 48 | When placed all together the sequence looks like this: 49 | 50 | .. code-block:: python 51 | 52 | import libnacl 53 | import libnacl.utils 54 | 55 | key = libnacl.utils.salsa_key() 56 | nonce = libnacl.utils.rand_nonce() 57 | 58 | msg = 'Who are you who are so wise in the ways of science?' 59 | box = libnacl.crypto_secretbox(msg, nonce, key) 60 | 61 | clear_msg = libnacl.crypto_secretbox_open(box, nonce, key) 62 | -------------------------------------------------------------------------------- /doc/topics/raw_sign.rst: -------------------------------------------------------------------------------- 1 | ====================== 2 | Raw Message Signatures 3 | ====================== 4 | 5 | .. note:: 6 | 7 | While these routines are perfectly safe, higher level convenience 8 | wrappers are under development to make these routines easier. 9 | 10 | Signing messages ensures that the message itself has not been tampered with. 11 | The application of a signature to a message is something that is is 12 | automatically applied when using the public key encryption and is not a 13 | required step when sending encrypted messages. This document however is 14 | intended to illustrate how to sign plain text messages. 15 | 16 | The nacl libs use a separate keypair for signing then is used for 17 | public key encryption, it is a high performance key signing algorithm 18 | called ed25519, more information on ed25519 can be found here: 19 | http://ed25519.cr.yp.to/ 20 | 21 | The sign messages first generate a signing keypair, this constitutes the 22 | signing key which needs to be kept secret, and the verify key which is 23 | made available to message recipients. 24 | 25 | .. code-block:: python 26 | 27 | import libnacl 28 | 29 | vk, sk = libnacl.crypto_sign_keypair() 30 | 31 | With the signing keypair in hand a message can be signed: 32 | 33 | .. code-block:: python 34 | 35 | msg = 'And that, my liege, is how we know the Earth to be banana-shaped.' 36 | signed = libnacl.crypto_sign(msg, sk) 37 | 38 | The signed message is really just the plain text of the message prepended with 39 | the signature. The crypto_sign_open function will read the signed message 40 | and return the original message without the signature: 41 | 42 | .. code-block:: python 43 | 44 | orig = libnacl.crypto_sign_open(signed, vk) 45 | 46 | Put all together: 47 | 48 | .. code-block:: python 49 | 50 | import libnacl 51 | 52 | vk, sk = libnacl.crypto_sign_keypair() 53 | 54 | msg = 'And that, my liege, is how we know the Earth to be banana-shaped.' 55 | signed = libnacl.crypto_sign(msg, sk) 56 | 57 | orig = libnacl.crypto_sign_open(signed, vk) 58 | -------------------------------------------------------------------------------- /doc/topics/releases/1.0.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.0.0 Release Notes 3 | =========================== 4 | 5 | This is the first stable release of libnacl, the python bindings for Daniel J. 6 | Bernstein's nacl library via libsodium. 7 | 8 | NaCl Base Functions 9 | =================== 10 | 11 | This release features direct access to the underlying functions from nacl 12 | exposed via importing libnacl. These functions are fully documented and can 13 | be safely used directly. 14 | -------------------------------------------------------------------------------- /doc/topics/releases/1.1.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.1.0 Release Notes 3 | =========================== 4 | 5 | This release introduces the addition of high level classes that make using 6 | NaCl even easier. 7 | 8 | High level NaCl 9 | =============== 10 | 11 | The addition of the high level classes give a more pythonic abstraction to 12 | using the underlying NaCl cryptography. 13 | 14 | These classes can be found in libnacl.public, libnacl.sign and libnacl.secret. 15 | 16 | Easy Nonce Generation 17 | ===================== 18 | 19 | The new classes will automatically generate a nonce value per encrypted 20 | message. The default nonce which is generated can be found in 21 | `libnacl.utils.time_nonce`. 22 | -------------------------------------------------------------------------------- /doc/topics/releases/1.2.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.2.0 Release Notes 3 | =========================== 4 | 5 | This release introduces the DualKey class, secure key saving and loading, as 6 | well as enhancements to the time_nonce function. 7 | 8 | Dual Key Class 9 | ============== 10 | 11 | Dual Keys are classes which can encrypt and sign data. These classes generate 12 | and maintain both Curve25519 and Ed25519 keys, as well as all methods for both 13 | encryption and signing. 14 | 15 | Time Nonce Improvements 16 | ======================= 17 | 18 | The original time nonce routine used the first 20 chars of the 24 char nonce 19 | for the microsecond timestamp (based on salt's jid), leaving 4 chars for random 20 | data. This new nonce uses far fewer chars for the timestamp by hex encoding the 21 | float of microseconds into just 13 chars, leaving 11 chars of random data. This 22 | makes the default nonce safer and more secure. 23 | -------------------------------------------------------------------------------- /doc/topics/releases/1.3.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.3.0 Release Notes 3 | =========================== 4 | 5 | This release removes the time_nonce function and replaces it with the 6 | rand_nonce function. 7 | -------------------------------------------------------------------------------- /doc/topics/releases/1.3.1.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.3.1 Release Notes 3 | =========================== 4 | 5 | Bring back a safe time_nonce function. 6 | -------------------------------------------------------------------------------- /doc/topics/releases/1.3.2.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.3.2 Release Notes 3 | =========================== 4 | 5 | Add detection of the libsodium.so.10 lib created by libsodium 0.6 6 | -------------------------------------------------------------------------------- /doc/topics/releases/1.3.3.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.3.3 Release Notes 3 | =========================== 4 | 5 | Fix issue and add tests for bug where saving and loading a signing key caused 6 | a stack trace, se issue #18 7 | -------------------------------------------------------------------------------- /doc/topics/releases/1.3.4.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.3.4 Release Notes 3 | =========================== 4 | 5 | * Change the default ctype values to be more accurate and efficient 6 | * Update soname detection on Linux for libsodium 0.7.0 7 | * Make soname detection a little more future proof 8 | -------------------------------------------------------------------------------- /doc/topics/releases/1.4.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.4.0 Release Notes 3 | =========================== 4 | 5 | Blake Hash Support 6 | ================== 7 | 8 | Initial support has been added for the blake2b hash algorithm 9 | 10 | Misc Fixes 11 | ========== 12 | 13 | * Fix issue with keyfile saves on windows 14 | * Fix libsodium detection for Ubuntu manual installs and Windows dll detection 15 | -------------------------------------------------------------------------------- /doc/topics/releases/1.4.1.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.4.1 Release Notes 3 | =========================== 4 | 5 | Misc Fixes 6 | ========== 7 | 8 | * Fix for crypto_auth_verify and crypto_auth_onetimeverify 9 | * Lint fixes and updates 10 | -------------------------------------------------------------------------------- /doc/topics/releases/1.4.2.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.4.2 Release Notes 3 | =========================== 4 | 5 | SecretBox key save and load 6 | =========================== 7 | 8 | * Add support to save and load SecretBox keys 9 | -------------------------------------------------------------------------------- /doc/topics/releases/1.4.3.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.4.3 Release Notes 3 | =========================== 4 | 5 | crypto_onetimeauth_verify fixes 6 | =============================== 7 | 8 | * Fix a call to the crypto_onetimeauth_verify routine into the right libsodium system 9 | * Add tests for crypto_onetimeauth_verify 10 | 11 | Improved support for MacOSX 12 | =========================== 13 | 14 | * Improved the lookup procedure for finding libsodium on MacOSX 15 | 16 | Add support for reading file streams for key loading 17 | ==================================================== 18 | -------------------------------------------------------------------------------- /doc/topics/releases/1.4.4.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.4.4 Release Notes 3 | =========================== 4 | 5 | Add pack_nonce options to secretbox 6 | =================================== 7 | 8 | * libnacl secretbox has been packing the nonce in each message, the new pack_nonce 9 | option allows for the nonce to be omitted which allows for more flexible options 10 | 11 | Add soversion 17 detection 12 | ========================== 13 | 14 | * Added explicit soversion support for libsodium 17 15 | 16 | Fix crypto_onetimeauth tests 17 | ============================ 18 | 19 | * The crypto onetimeauth test issues have been resolved 20 | 21 | Remove tweetnacl Support 22 | ======================== 23 | 24 | * The tweetnacl support was never really tested, and since the tweetnacl api 25 | is not complete we have removed support for it 26 | 27 | Add sodium_init calls 28 | ===================== 29 | 30 | * Added calls to sodium_init when the lib is loaded 31 | -------------------------------------------------------------------------------- /doc/topics/releases/1.4.5.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.4.5 Release Notes 3 | =========================== 4 | 5 | Set low end libsodium version to 0.5 6 | ==================================== 7 | 8 | * libnacl will only function with libsodium 0.5 and above 9 | 10 | Add soversion 18 detection 11 | ========================== 12 | 13 | * Added explicit soversion support for libsodium 18 14 | 15 | -------------------------------------------------------------------------------- /doc/topics/releases/1.5.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.5.0 Release Notes 3 | =========================== 4 | 5 | Add Built In libsodium.so Support 6 | ================================= 7 | 8 | Added the ability to place a `libsodium.so` file in the libnacl 9 | python directory as a last resort fallback. To use this feature 10 | just copy your `libsodium.so` file to the same directory as the libnacl 11 | `__init__.py` file. 12 | 13 | This was added to make total portability of the library easier. 14 | 15 | Add `bytes_eq` 16 | ============== 17 | 18 | Added the `bytes_eq` function to allow better byte comparison 19 | 20 | -------------------------------------------------------------------------------- /doc/topics/releases/1.5.1.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.5.1 Release Notes 3 | =========================== 4 | 5 | Add Sealed Box Support 6 | ====================== 7 | 8 | A big thanks to Manatsawin Hanmongkolchai for adding in support for libsodium 9 | `Sealed Boxes`! 10 | 11 | Change Exception on Encrypt/Decrypt Failure 12 | =========================================== 13 | 14 | If encryption or decryption fails, `CryptError` is raised instead of 15 | `ValueError`. This might be a breaking change for your application. See 16 | `#91 `__ and 17 | `#74 `__. 18 | -------------------------------------------------------------------------------- /doc/topics/releases/1.5.2.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.5.2 Release Notes 3 | =========================== 4 | 5 | Add Support for AEAD AES and chacha20poly1305 6 | ============================================= 7 | 8 | Big thanks to Nicholas O'Brien for adding support for libsodium's AEAD 9 | encryption systems. The raw functions are all available to access 10 | libsodium directly along with the high level AEAD class that cleanly 11 | follows libnacl's key management model. 12 | -------------------------------------------------------------------------------- /doc/topics/releases/1.6.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.6.0 Release Notes 3 | =========================== 4 | 5 | Add Bindings for More Libsodium Function 6 | ======================================== 7 | 8 | Add bindings for crypto_box_seed_keypair() and crypto_scalarmult_base() 9 | Add bindings for crypto_box_easy() and crypto_box_open_easy() 10 | Add bindings for crypto_box_easy_afternm() and crypto_box_open_easy_afternm() 11 | Add bindings for crypto_sign_ed25519_keypair(), crypto_sign_ed25519_sk_to_pk() and crypto_sign_ed25519_sk_to_seed() 12 | Add bindings for crypto_sign_detached() and crypto_sign_verify_detached() 13 | Add bindings for crypto_sign_ed25519_pk_to_curve25519() and crypto_sign_ed25519_sk_to_curve25519() 14 | 15 | Please Note The Exception Change From the 1.5.1 Release 16 | ======================================================= 17 | 18 | If encryption or decryption fails, `CryptError` is raised instead of 19 | `ValueError`. This might be a breaking change for your application. See 20 | `#91 `__ and 21 | `#74 `__. 22 | -------------------------------------------------------------------------------- /doc/topics/releases/1.6.1.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.6.1 Release Notes 3 | =========================== 4 | 5 | Add support for libsodium 1.0.15 6 | ================================ 7 | 8 | Make sure that libnacl runs correctly on the 1.0.15 release of libsodium 9 | -------------------------------------------------------------------------------- /doc/topics/releases/1.7.1.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.7.1 Release Notes 3 | =========================== 4 | 5 | This release fixes a few minor bugs, primarily in tests, and restores 6 | functionality with older versions of libsodium. 7 | 8 | Compatibility With Older libsodium 9 | ================================== 10 | 11 | PR #118 fixes compatibility with Debian 8. 12 | 13 | Test Fixes 14 | ========== 15 | 16 | Some unreliability in tests were found by the Debian team. These 17 | issues were fixed in PRs #115 and #116. 18 | 19 | Travis no longer supports the same pypy tests on all platforms, 20 | these were removed in PR #119. 21 | 22 | -------------------------------------------------------------------------------- /doc/topics/releases/1.7.rst: -------------------------------------------------------------------------------- 1 | ========================= 2 | libnacl 1.7 Release Notes 3 | ========================= 4 | 5 | Bindings for kdf in libsodium 6 | ============================= 7 | 8 | Thanks to Michael Mendoza, PR #109 9 | 10 | Added extra key validation 11 | ========================== 12 | 13 | Thanks to Kent Ross, PR #106 14 | 15 | Add Crypto_box_easy 16 | =================== 17 | 18 | Thanks to jheling PR #114 19 | -------------------------------------------------------------------------------- /doc/topics/releases/1.9.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 1.9.0 Release Notes 3 | =========================== 4 | 5 | This release is a little overdue, it fixes a number of documentation issues 6 | and adds a few convenience features. It also migrates the build system to poetry 7 | and fixes the documentation build on readthedocs 8 | -------------------------------------------------------------------------------- /doc/topics/releases/2.0.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 2.0.0 Release Notes 3 | =========================== 4 | 5 | Add Support for AEAD and AEAD Classes 6 | ===================================== 7 | 8 | Added classes to the libnacl.aead module allowing for the use of 9 | XChaCha20-Poly1305-IETF, ChaCha20-Poly1305-IETF, and AES256-GCM. 10 | -------------------------------------------------------------------------------- /doc/topics/releases/2.1.0.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | libnacl 2.1.0 Release Notes 3 | =========================== 4 | 5 | Add Support for the Key Exchange System 6 | ======================================= 7 | 8 | Added the libnacl.kx module. This module contains the ExchangeKey class. 9 | 10 | The ExchangeKey class makes it easy to use AEAD encryption with an 11 | exchange key setup. The class works much like a sealed box but allows 12 | for the creation of the exchange keys. 13 | 14 | This makes it very easy to set up a system using AEAD and exchange keys. 15 | 16 | Fix issues with pyproject.toml 17 | ============================== 18 | 19 | The 2.0.0 release introduced the use of poetry into libnacl, unfortunately I 20 | made a mistake in the pyproject.toml file. Thanks for @mgorny for catching the 21 | issue and getting a PR in. 22 | -------------------------------------------------------------------------------- /doc/topics/releases/index.rst: -------------------------------------------------------------------------------- 1 | ============= 2 | Release notes 3 | ============= 4 | 5 | .. toctree:: 6 | :maxdepth: 1 7 | :glob: 8 | 9 | [0-9]* 10 | -------------------------------------------------------------------------------- /doc/topics/sealed.rst: -------------------------------------------------------------------------------- 1 | ===================== 2 | Sealed Box 3 | ===================== 4 | 5 | Sealed box is a variant of :doc:`public key encryption scheme ` 6 | which only the receiver's public key is required. As such, the sender of the 7 | message cannot be cryptographically authenticated. 8 | 9 | .. code-block:: python 10 | 11 | import libnacl.sealed 12 | import libnacl.public 13 | 14 | # Define a message to send 15 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 16 | 17 | # Generate the key pair 18 | keypair = libnacl.public.SecretKey() 19 | 20 | # Create the box 21 | box = libnacl.sealed.SealedBox(keypair) 22 | 23 | # Encrypt messages 24 | ctxt = box.encrypt(msg) 25 | # Decrypt messages 26 | bclear = box.decrypt(ctxt) 27 | 28 | Creating Box 29 | ====================== 30 | SealedBox instances can be created by supplying a public and private key. The 31 | private key is only required when decrypting. 32 | 33 | The public key can be supplied as: 34 | 35 | * Instance of :ref:`SecretKey `, which supply both the public 36 | and private key. 37 | * Instance of :ref:`PublicKey ` 38 | * Raw binary representation 39 | -------------------------------------------------------------------------------- /doc/topics/secret.rst: -------------------------------------------------------------------------------- 1 | ===================== 2 | Secret Key Encryption 3 | ===================== 4 | 5 | Secret key encryption is the method of using a single key for both encryption 6 | and decryption of messages. One of the classic examples from history of secret 7 | key, or symmetric, encryption is the Enigma machine. 8 | 9 | The SecretBoxEasy class in libnacl.secret_easy makes this type of encryption very easy 10 | to execute: 11 | 12 | .. code-block:: python 13 | 14 | import libnacl.secret_easy 15 | 16 | msg = b'But then of course African swallows are not migratory.' 17 | # Create a SecretBox object, if not passed in the secret key is 18 | # Generated purely from random data 19 | box = libnacl.secret_easy.SecretBoxEasy() 20 | # Messages can now be safely encrypted 21 | ctxt = box.encrypt(msg) 22 | # An additional box can be created from the original box secret key 23 | box2 = libnacl.secret_easy.SecretBoxEasy(box.sk) 24 | # Messages can now be easily encrypted and decrypted 25 | clear1 = box.decrypt(ctxt) 26 | clear2 = box2.decrypt(ctxt) 27 | ctxt2 = box2.encrypt(msg) 28 | clear3 = box.decrypt(ctxt2) 29 | 30 | .. note:: 31 | 32 | Every encryption routine requires a nonce. The nonce is a 24 char string 33 | that must never be used twice with the same keypair. If no nonce is passed 34 | in then a nonce is generated based on random data. 35 | If it is desired to generate a nonce manually this can be done by passing 36 | it into the encrypt method. 37 | -------------------------------------------------------------------------------- /doc/topics/sign.rst: -------------------------------------------------------------------------------- 1 | ============================== 2 | Signing and Verifying Messages 3 | ============================== 4 | 5 | The nacl libs have the capability to sign and verify messages. 6 | 7 | To sign and verify messages use the Signer and Verifier classes: 8 | 9 | .. code-block:: python 10 | 11 | import libnacl.sign 12 | 13 | msg = (b'Well, that\'s no ordinary rabbit. That\'s the most foul, ' 14 | b'cruel, and bad-tempered rodent you ever set eyes on.') 15 | # Create a Signer Object, if the key seed value is not passed in the 16 | # signing keys will be automatically generated 17 | signer = libnacl.sign.Signer() 18 | # Sign the message, the signed string is the message itself plus the 19 | # signature 20 | signed = signer.sign(msg) 21 | # If only the signature is desired without the message: 22 | signature = signer.signature(msg) 23 | # To create a verifier pass in the verify key: 24 | veri = libnacl.sign.Verifier(signer.hex_vk()) 25 | # Verify the message! 26 | verified = veri.verify(signed) 27 | verified2 = veri.verify(signature + msg) 28 | 29 | Saving Keys to Disk 30 | =================== 31 | 32 | All libnacl key objects can be safely saved to disk via the save method. This 33 | method changes the umask before saving the key file to ensure that the saved 34 | file can only be read by the user creating it and cannot be written to. 35 | 36 | .. code-block:: python 37 | 38 | import libnacl.sign 39 | 40 | signer = libnacl.sign.Signer() 41 | signer.save('/etc/nacl/signer.key') 42 | -------------------------------------------------------------------------------- /doc/topics/utils.rst: -------------------------------------------------------------------------------- 1 | ================= 2 | Utility Functions 3 | ================= 4 | 5 | The libnacl system comes with a number of utility functions, these functions 6 | are made available to make some of the aspects of encryption and key management 7 | easier. These range from nonce generation to loading saved keys. 8 | 9 | Loading Saved Keys 10 | ================== 11 | 12 | After keys are saved using the key save method reloading the keys is easy. The 13 | `libnacl.utils.load_key` function will detect what type of key object saved 14 | said key and then create the object from the key and return it. 15 | 16 | .. code-block:: python 17 | 18 | import libnacl.utils 19 | 20 | key_obj = libnacl.utils.load_key('/etc/keys/bob.key') 21 | 22 | The load_key and save routines also support inline key serialization. The 23 | default is json but msgpack is also supported. 24 | 25 | Salsa Key 26 | ========= 27 | 28 | A simple function that will return a random byte string suitable for use in 29 | SecretKey encryption. 30 | 31 | .. code-block:: python 32 | 33 | import libnacl.utils 34 | 35 | key = libnacl.utils.salsa_key() 36 | 37 | This routine is only required with the raw encryption functions, as the 38 | `libnacl.secret.SecretBox` will generate the key automatically. 39 | 40 | Nonce Routines 41 | ============== 42 | 43 | A few functions are available to help with creating nonce values, these 44 | routines are available because there is some debate about what the best approach 45 | is. 46 | 47 | We recommend a pure random string for the nonce which is returned from 48 | `rand_nonce`, but some have expressed a desire to create nonces which are 49 | designed to avoid re-use by more than simply random data and therefore 50 | the `time_nonce` function is also available. 51 | -------------------------------------------------------------------------------- /libnacl/aead.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | Utilities to make secret box encryption simple 4 | ''' 5 | # Import libnacl 6 | import libnacl 7 | import libnacl.utils 8 | import libnacl.base 9 | 10 | 11 | class AEAD(libnacl.base.BaseKey): 12 | ''' 13 | Manage AEAD encryption using the IETF ChaCha20-Poly1305(default) or AES-GCM algorithm 14 | ''' 15 | 16 | def __init__(self, key=None): 17 | if key is None: 18 | key = libnacl.utils.aead_key() 19 | if len(key) != libnacl.crypto_aead_chacha20poly1305_ietf_KEYBYTES: # same size for both 20 | raise ValueError('Invalid key') 21 | self.sk = key 22 | self.usingAES = False 23 | self.usingXCHACHA = False 24 | super().__init__() 25 | 26 | def useAESGCM(self): 27 | self.usingAES = True 28 | return self 29 | 30 | def useXCHACHA(self): 31 | self.usingXCHACHA = True 32 | return self 33 | 34 | def encrypt(self, msg, aad, nonce=None, pack_nonce_aad=True): 35 | ''' 36 | Encrypt the given message. If a nonce is not given it will be 37 | generated via the rand_nonce function 38 | ''' 39 | if nonce is None: 40 | if self.usingXCHACHA: 41 | nonce = libnacl.utils.rand_aead_xchacha_nonce() 42 | else: 43 | nonce = libnacl.utils.rand_aead_nonce() 44 | if self.usingXCHACHA: 45 | if len(nonce) != libnacl.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES: 46 | raise ValueError('Invalid nonce') 47 | else: 48 | if len(nonce) != libnacl.crypto_aead_aes256gcm_NPUBBYTES: 49 | raise ValueError('Invalid nonce') 50 | if self.usingXCHACHA: 51 | ctxt = libnacl.crypto_aead_xchacha20poly1305_ietf_encrypt(msg, aad, nonce, self.sk) 52 | elif self.usingAES: 53 | ctxt = libnacl.crypto_aead_aes256gcm_encrypt(msg, aad, nonce, self.sk) 54 | else: 55 | ctxt = libnacl.crypto_aead_chacha20poly1305_ietf_encrypt(msg, aad, nonce, self.sk) 56 | 57 | if pack_nonce_aad: 58 | return aad + nonce + ctxt 59 | else: 60 | return aad, nonce, ctxt 61 | 62 | def decrypt(self, ctxt, aadLen): 63 | ''' 64 | Decrypt the given message, if no nonce or aad are given they will be 65 | extracted from the message 66 | ''' 67 | aad = ctxt[:aadLen] 68 | if self.usingXCHACHA: 69 | nonce = ctxt[aadLen:aadLen+libnacl.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES] 70 | ctxt = ctxt[aadLen+libnacl.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES:] 71 | if len(nonce) != libnacl.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES: 72 | raise ValueError('Invalid nonce') 73 | else: 74 | nonce = ctxt[aadLen:aadLen+libnacl.crypto_aead_aes256gcm_NPUBBYTES] 75 | ctxt = ctxt[aadLen+libnacl.crypto_aead_aes256gcm_NPUBBYTES:] 76 | if len(nonce) != libnacl.crypto_aead_aes256gcm_NPUBBYTES: 77 | raise ValueError('Invalid nonce') 78 | if self.usingXCHACHA: 79 | return libnacl.crypto_aead_xchacha20poly1305_ietf_decrypt(ctxt, aad, nonce, self.sk) 80 | if self.usingAES: 81 | return libnacl.crypto_aead_aes256gcm_decrypt(ctxt, aad, nonce, self.sk) 82 | return libnacl.crypto_aead_chacha20poly1305_ietf_decrypt(ctxt, aad, nonce, self.sk) 83 | 84 | def decrypt_unpacked(self, aad, nonce, ctxt): 85 | ''' 86 | Decrypt the given message, if no nonce or aad are given they will be 87 | extracted from the message 88 | ''' 89 | if len(nonce) != libnacl.crypto_aead_aes256gcm_NPUBBYTES: 90 | raise ValueError('Invalid nonce') 91 | if self.usingAES: 92 | return libnacl.crypto_aead_aes256gcm_decrypt(ctxt, aad, nonce, self.sk) 93 | return libnacl.crypto_aead_chacha20poly1305_ietf_decrypt(ctxt, aad, nonce, self.sk) 94 | 95 | 96 | class AEAD_AESGCM(AEAD): 97 | def __init__(self, key=None): 98 | super().__init__(key) 99 | self.useAESGCM() 100 | 101 | 102 | class AEAD_XCHACHA(AEAD): 103 | def __init__(self, key=None): 104 | super().__init__(key) 105 | self.useXCHACHA() 106 | 107 | 108 | class AEAD_CHACHA(AEAD): 109 | def __init__(self, key=None): 110 | super().__init__(key) 111 | -------------------------------------------------------------------------------- /libnacl/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | Implement the base key object for other keys to inherit convenience functions 4 | ''' 5 | # Import libnacl libs 6 | import libnacl.encode 7 | 8 | # Import python libs 9 | import os 10 | import stat 11 | 12 | class BaseKey(object): 13 | ''' 14 | Include methods for key management convenience 15 | ''' 16 | def __init__(self): 17 | self.sk_hex = self.hex_sk() 18 | self.pk_hex = self.hex_pk() 19 | self.kx_sk_hex = self.hex_kx_sk() 20 | self.kx_pk_hex = self.hex_kx_pk() 21 | self.vk_hex = self.hex_vk() 22 | 23 | def hex_sk(self): 24 | if hasattr(self, 'sk'): 25 | return libnacl.encode.hex_encode(self.sk) 26 | 27 | def hex_pk(self): 28 | if hasattr(self, 'pk'): 29 | return libnacl.encode.hex_encode(self.pk) 30 | 31 | def hex_kx_pk(self): 32 | if hasattr(self, 'kx_pk'): 33 | return libnacl.encode.hex_encode(self.kx_pk) 34 | 35 | def hex_kx_sk(self): 36 | if hasattr(self, 'kx_sk'): 37 | return libnacl.encode.hex_encode(self.kx_sk) 38 | 39 | def hex_vk(self): 40 | if hasattr(self, 'vk'): 41 | return libnacl.encode.hex_encode(self.vk) 42 | 43 | def hex_seed(self): 44 | if hasattr(self, 'seed'): 45 | return libnacl.encode.hex_encode(self.seed) 46 | 47 | def for_json(self): 48 | ''' 49 | Return a dictionary of the secret values we need to store. 50 | ''' 51 | pre = {} 52 | sk = self.hex_sk() 53 | pk = self.hex_pk() 54 | kx_sk = self.hex_kx_sk() 55 | kx_pk = self.hex_kx_pk() 56 | vk = self.hex_vk() 57 | seed = self.hex_seed() 58 | if sk: 59 | pre['priv'] = sk.decode('utf-8') 60 | if pk: 61 | pre['pub'] = pk.decode('utf-8') 62 | if kx_sk: 63 | pre['kx_priv'] = kx_sk.decode('utf-8') 64 | if kx_pk: 65 | pre['kx_pub'] = kx_pk.decode('utf-8') 66 | if vk: 67 | pre['verify'] = vk.decode('utf-8') 68 | if seed: 69 | pre['sign'] = seed.decode('utf-8') 70 | 71 | return pre 72 | 73 | def save(self, path, serial='json'): 74 | ''' 75 | Safely save keys with perms of 0400 76 | ''' 77 | pre = self.for_json() 78 | 79 | if serial == 'msgpack': 80 | import msgpack 81 | packaged = msgpack.dumps(pre) 82 | elif serial == 'json': 83 | import json 84 | packaged = json.dumps(pre) 85 | 86 | perm_other = stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH 87 | perm_group = stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP 88 | 89 | cumask = os.umask(perm_other | perm_group) 90 | with open(path, 'w+') as fp_: 91 | fp_.write(packaged) 92 | os.umask(cumask) 93 | -------------------------------------------------------------------------------- /libnacl/blake.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Mimic very closely the python hashlib classes for blake2b 3 | 4 | NOTE: 5 | This class does not yet implement streaming the msg into the 6 | hash function via the update method 7 | ''' 8 | 9 | # Import python libs 10 | import binascii 11 | 12 | # Import libnacl libs 13 | import libnacl 14 | 15 | 16 | class Blake2b(object): 17 | ''' 18 | Manage a Blake2b hash 19 | ''' 20 | def __init__(self, msg, key=None): 21 | self.msg = msg 22 | self.key = key 23 | self.raw_digest = libnacl.crypto_generichash(msg, key) 24 | self.digest_size = len(self.raw_digest) 25 | 26 | def digest(self): 27 | ''' 28 | Return the digest of the string 29 | ''' 30 | return self.raw_digest 31 | 32 | def hexdigest(self): 33 | ''' 34 | Return the hex digest of the string 35 | ''' 36 | return binascii.hexlify(self.raw_digest) 37 | 38 | 39 | def blake2b(msg, key=None): 40 | ''' 41 | Create and return a Blake2b object to mimic the behavior of the python 42 | hashlib functions 43 | ''' 44 | return Blake2b(msg, key) 45 | -------------------------------------------------------------------------------- /libnacl/dual.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The dual key system allows for the creation of keypairs that contain both 3 | cryptographic and signing keys 4 | ''' 5 | # import libnacl libs 6 | import libnacl 7 | import libnacl.base 8 | import libnacl.public 9 | import libnacl.sign 10 | 11 | 12 | class DualSecret(libnacl.base.BaseKey): 13 | ''' 14 | Manage crypt and sign keys in one object 15 | ''' 16 | def __init__(self, crypt=None, sign=None): 17 | self.crypt = libnacl.public.SecretKey(crypt) 18 | self.signer = libnacl.sign.Signer(sign) 19 | self.sk = self.crypt.sk 20 | self.seed = self.signer.seed 21 | self.pk = self.crypt.pk 22 | self.vk = self.signer.vk 23 | super().__init__() 24 | 25 | def sign(self, msg): 26 | ''' 27 | Sign the given message 28 | ''' 29 | return self.signer.sign(msg) 30 | 31 | def signature(self, msg): 32 | ''' 33 | Return just the signature for the message 34 | ''' 35 | return self.signer.signature(msg) 36 | -------------------------------------------------------------------------------- /libnacl/encode.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | Build in routines and classes to simplify encoding routines 4 | ''' 5 | # Import python libs 6 | import base64 7 | import binascii 8 | 9 | 10 | def hex_encode(data): 11 | ''' 12 | Hex encode data 13 | ''' 14 | return binascii.hexlify(data) 15 | 16 | 17 | def hex_decode(data): 18 | ''' 19 | Hex decode data 20 | ''' 21 | return binascii.unhexlify(data) 22 | 23 | 24 | def base16_encode(data): 25 | ''' 26 | Base32 encode data 27 | ''' 28 | return base64.b16encode(data) 29 | 30 | 31 | def base16_decode(data): 32 | ''' 33 | Base16 decode data 34 | ''' 35 | return base64.b16decode(data) 36 | 37 | 38 | def base32_encode(data): 39 | ''' 40 | Base16 encode data 41 | ''' 42 | return base64.b32encode(data) 43 | 44 | 45 | def base32_decode(data): 46 | ''' 47 | Base32 decode data 48 | ''' 49 | return base64.b32decode(data) 50 | 51 | 52 | def base64_encode(data): 53 | ''' 54 | Base16 encode data 55 | ''' 56 | return base64.b64encode(data) 57 | 58 | 59 | def base64_decode(data): 60 | ''' 61 | Base32 decode data 62 | ''' 63 | return base64.b64decode(data) 64 | -------------------------------------------------------------------------------- /libnacl/kx.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implementation of the X25519 Key Exchange function. These classes make executing a key 3 | exchange simple. 4 | """ 5 | import libnacl 6 | import libnacl.base 7 | import libnacl.utils 8 | 9 | 10 | class ExchangeKey(libnacl.base.BaseKey): 11 | """ 12 | The class used to manage key exchange keys 13 | """ 14 | def __init__(self, kx_sk=None, enc=None): 15 | if kx_sk is None: 16 | self.kx_pk, self.kx_sk = libnacl.crypto_kx_keypair() 17 | elif len(kx_sk) == libnacl.libnacl.crypto_kx_SECRETKEYBYTES: 18 | self.kx_sk = kx_sk 19 | self.kx_pk = libnacl.crypto_scalarmult_base(kx_sk) 20 | if enc is None: 21 | self.enc = "xchacha" 22 | elif enc in ("xchacha", "aesgcm", "chacha"): 23 | self.enc = enc 24 | else: 25 | raise ValueError(f"Invalid encryption type passed: {enc}") 26 | 27 | def get_crypt(self, key): 28 | return getattr(self, f"get_{self.enc}")(key) 29 | 30 | def get_xchacha(self, key): 31 | return libnacl.aead.AEAD_XCHACHA(key) 32 | 33 | def get_chacha(self, key): 34 | return libnacl.aead.AEAD_CHACHA(key) 35 | 36 | def get_aesgcm(self, key): 37 | return libnacl.aead.AEAD_AESGCM(key) 38 | 39 | def client_session_keys(self, remote_pk): 40 | """ 41 | Takes a remote public key and derives the rx and tx session keys 42 | """ 43 | return libnacl.crypto_kx_client_session_keys(self.kx_pk, self.kx_sk, remote_pk) 44 | 45 | def server_session_keys(self, remote_pk): 46 | """ 47 | Takes a remote public key and derives the rx and tx session keys 48 | """ 49 | return libnacl.crypto_kx_server_session_keys(self.kx_pk, self.kx_sk, remote_pk) 50 | 51 | def encrypt_client(self, remote_pk, msg, ad): 52 | """ 53 | Encrypt the given message using the remote_sk 54 | """ 55 | rx, tx, status = self.client_session_keys(remote_pk) 56 | 57 | crypter = self.get_crypt(tx) 58 | return crypter.encrypt(msg, ad) 59 | 60 | def encrypt_server(self, remote_pk, msg, ad): 61 | """ 62 | Encrypt the given message using the remote_sk 63 | """ 64 | rx, tx, status = self.server_session_keys(remote_pk) 65 | 66 | crypter = self.get_crypt(tx) 67 | return crypter.encrypt(msg, ad) 68 | 69 | def decrypt_client(self, remote_pk, ctxt, len_ad): 70 | rx, tx, status = self.client_session_keys(remote_pk) 71 | 72 | crypter = self.get_crypt(rx) 73 | clear = crypter.decrypt(ctxt, len_ad) 74 | #ad = ctxt[:len_ad] 75 | return clear 76 | 77 | def decrypt_server(self, remote_pk, ctxt, len_ad): 78 | rx, tx, status = self.server_session_keys(remote_pk) 79 | 80 | crypter = self.get_crypt(rx) 81 | clear = crypter.decrypt(ctxt, len_ad) 82 | #ad = ctxt[:len_ad] 83 | return clear 84 | -------------------------------------------------------------------------------- /libnacl/public.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | High level classes and routines around public key encryption and decryption 4 | ''' 5 | # import libnacl libs 6 | import libnacl 7 | import libnacl.utils 8 | import libnacl.encode 9 | import libnacl.dual 10 | import libnacl.base 11 | 12 | 13 | class PublicKey(libnacl.base.BaseKey): 14 | ''' 15 | This class is used to manage public keys 16 | ''' 17 | def __init__(self, pk): 18 | if len(pk) == libnacl.crypto_box_PUBLICKEYBYTES: 19 | self.pk = pk 20 | else: 21 | raise ValueError('Passed in invalid public key') 22 | super().__init__() 23 | 24 | def __eq__(self, other): 25 | if isinstance(other, self.__class__): 26 | return self.pk == other.pk 27 | else: 28 | return False 29 | 30 | def __ne__(self, other): 31 | return not self.__eq__(other) 32 | 33 | def __hash__(self): 34 | return hash(self.pk) 35 | 36 | 37 | class SecretKey(libnacl.base.BaseKey): 38 | ''' 39 | This class is used to manage keypairs 40 | ''' 41 | def __init__(self, sk=None): 42 | ''' 43 | If a secret key is not passed in then it will be generated 44 | ''' 45 | if sk is None: 46 | self.pk, self.sk = libnacl.crypto_box_keypair() 47 | elif len(sk) == libnacl.crypto_box_SECRETKEYBYTES: 48 | self.sk = sk 49 | self.pk = libnacl.crypto_scalarmult_base(sk) 50 | else: 51 | raise ValueError('Passed in invalid secret key') 52 | super().__init__() 53 | 54 | def __eq__(self, other): 55 | if isinstance(other, self.__class__): 56 | return self.sk == other.sk and self.pk == other.pk 57 | else: 58 | return False 59 | 60 | def __ne__(self, other): 61 | return not self.__eq__(other) 62 | 63 | def __hash__(self): 64 | return hash((self.sk, self.pk)) 65 | 66 | 67 | class Box(object): 68 | ''' 69 | TheBox class is used to create cryptographic boxes and unpack 70 | cryptographic boxes 71 | ''' 72 | def __init__(self, sk, pk): 73 | if isinstance(sk, (SecretKey, libnacl.dual.DualSecret)): 74 | sk = sk.sk 75 | if isinstance(pk, (SecretKey, libnacl.dual.DualSecret)): 76 | raise ValueError('Passed in secret key as public key') 77 | if isinstance(pk, PublicKey): 78 | pk = pk.pk 79 | if pk and sk: 80 | self._k = libnacl.crypto_box_beforenm(pk, sk) 81 | 82 | def encrypt(self, msg, nonce=None, pack_nonce=True): 83 | ''' 84 | Encrypt the given message with the given nonce, if the nonce is not 85 | provided it will be generated from the libnacl.utils.rand_nonce 86 | function 87 | ''' 88 | if nonce is None: 89 | nonce = libnacl.utils.rand_nonce() 90 | elif len(nonce) != libnacl.crypto_box_NONCEBYTES: 91 | raise ValueError('Invalid nonce size') 92 | ctxt = libnacl.crypto_box_afternm(msg, nonce, self._k) 93 | if pack_nonce: 94 | return nonce + ctxt 95 | else: 96 | return nonce, ctxt 97 | 98 | def decrypt(self, ctxt, nonce=None): 99 | ''' 100 | Decrypt the given message, if a nonce is passed in attempt to decrypt 101 | it with the given nonce, otherwise assum that the nonce is attached 102 | to the message 103 | ''' 104 | if nonce is None: 105 | nonce = ctxt[:libnacl.crypto_box_NONCEBYTES] 106 | ctxt = ctxt[libnacl.crypto_box_NONCEBYTES:] 107 | elif len(nonce) != libnacl.crypto_box_NONCEBYTES: 108 | raise ValueError('Invalid nonce') 109 | msg = libnacl.crypto_box_open_afternm(ctxt, nonce, self._k) 110 | return msg 111 | -------------------------------------------------------------------------------- /libnacl/sealed.py: -------------------------------------------------------------------------------- 1 | import libnacl 2 | import libnacl.public 3 | import libnacl.dual 4 | 5 | class SealedBox(object): 6 | ''' 7 | Sealed box is a variant of Box that does not authenticate sender. 8 | ''' 9 | 10 | def __init__(self, pk, sk=None): 11 | self.pk = pk 12 | self.sk = sk 13 | 14 | if isinstance(pk, (libnacl.public.SecretKey, libnacl.dual.DualSecret)): 15 | self.pk = pk.pk 16 | self.sk = pk.sk 17 | 18 | if isinstance(pk, libnacl.public.PublicKey): 19 | self.pk = pk.pk 20 | 21 | def encrypt(self, msg): 22 | ''' 23 | Encrypt the given message using the receiver's public key 24 | ''' 25 | return libnacl.crypto_box_seal(msg, self.pk) 26 | 27 | def decrypt(self, msg): 28 | ''' 29 | Decrypt the given message using the receiver's public and private key 30 | ''' 31 | if not self.sk: 32 | raise ValueError('Secret key is not set') 33 | return libnacl.crypto_box_seal_open(msg, self.pk, self.sk) 34 | -------------------------------------------------------------------------------- /libnacl/secret.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | Utilities to make secret box encryption simple 4 | ''' 5 | # Import libnacl 6 | import libnacl 7 | import libnacl.utils 8 | import libnacl.base 9 | 10 | 11 | class SecretBox(libnacl.base.BaseKey): 12 | ''' 13 | Manage symetric encryption using the salsa20 algorithm 14 | ''' 15 | def __init__(self, key=None): 16 | if key is None: 17 | key = libnacl.utils.salsa_key() 18 | if len(key) != libnacl.crypto_secretbox_KEYBYTES: 19 | raise ValueError('Invalid key') 20 | self.sk = key 21 | 22 | def encrypt(self, msg, nonce=None, pack_nonce=True): 23 | ''' 24 | Encrypt the given message. If a nonce is not given it will be 25 | generated via the rand_nonce function 26 | ''' 27 | if nonce is None: 28 | nonce = libnacl.utils.rand_nonce() 29 | if len(nonce) != libnacl.crypto_secretbox_NONCEBYTES: 30 | raise ValueError('Invalid nonce size') 31 | ctxt = libnacl.crypto_secretbox(msg, nonce, self.sk) 32 | if pack_nonce: 33 | return nonce + ctxt 34 | else: 35 | return nonce, ctxt 36 | 37 | def decrypt(self, ctxt, nonce=None): 38 | ''' 39 | Decrypt the given message, if no nonce is given the nonce will be 40 | extracted from the message 41 | ''' 42 | if nonce is None: 43 | nonce = ctxt[:libnacl.crypto_secretbox_NONCEBYTES] 44 | ctxt = ctxt[libnacl.crypto_secretbox_NONCEBYTES:] 45 | if len(nonce) != libnacl.crypto_secretbox_NONCEBYTES: 46 | raise ValueError('Invalid nonce') 47 | return libnacl.crypto_secretbox_open(ctxt, nonce, self.sk) 48 | -------------------------------------------------------------------------------- /libnacl/secret_easy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | Utilities to make secret box easy encryption simple 4 | ''' 5 | # Import libnacl 6 | import libnacl 7 | import libnacl.utils 8 | import libnacl.base 9 | 10 | 11 | class SecretBoxEasy(libnacl.base.BaseKey): 12 | ''' 13 | Manage symetric encryption using the salsa20 algorithm 14 | ''' 15 | def __init__(self, key=None): 16 | if key is None: 17 | key = libnacl.utils.salsa_key() 18 | if len(key) != libnacl.crypto_secretbox_KEYBYTES: 19 | raise ValueError('Invalid key') 20 | self.sk = key 21 | super().__init__() 22 | 23 | def encrypt(self, msg, nonce=None, pack_nonce=True): 24 | ''' 25 | Encrypt the given message. If a nonce is not given it will be 26 | generated via the rand_nonce function 27 | ''' 28 | if nonce is None: 29 | nonce = libnacl.utils.rand_nonce() 30 | if len(nonce) != libnacl.crypto_secretbox_NONCEBYTES: 31 | raise ValueError('Invalid nonce size') 32 | ctxt = libnacl.crypto_secretbox_easy(msg, nonce, self.sk) 33 | if pack_nonce: 34 | return nonce + ctxt 35 | else: 36 | return nonce, ctxt 37 | 38 | def decrypt(self, ctxt, nonce=None): 39 | ''' 40 | Decrypt the given message, if no nonce is given the nonce will be 41 | extracted from the message 42 | ''' 43 | if nonce is None: 44 | nonce = ctxt[:libnacl.crypto_secretbox_NONCEBYTES] 45 | ctxt = ctxt[libnacl.crypto_secretbox_NONCEBYTES:] 46 | if len(nonce) != libnacl.crypto_secretbox_NONCEBYTES: 47 | raise ValueError('Invalid nonce') 48 | return libnacl.crypto_secretbox_open_easy(ctxt, nonce, self.sk) 49 | -------------------------------------------------------------------------------- /libnacl/sign.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | High level routines to maintain signing keys and to sign and verify messages 4 | ''' 5 | # Import libancl libs 6 | import libnacl 7 | import libnacl.base 8 | import libnacl.encode 9 | 10 | 11 | class Signer(libnacl.base.BaseKey): 12 | ''' 13 | The tools needed to sign messages 14 | ''' 15 | def __init__(self, seed=None): 16 | ''' 17 | Create a signing key, if not seed it supplied a keypair is generated 18 | ''' 19 | if seed: 20 | if len(seed) != libnacl.crypto_sign_SEEDBYTES: 21 | raise ValueError('Invalid seed bytes') 22 | self.vk, self.sk = libnacl.crypto_sign_seed_keypair(seed) 23 | else: 24 | seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES) 25 | self.vk, self.sk = libnacl.crypto_sign_seed_keypair(seed) 26 | self.seed = seed 27 | super().__init__() 28 | 29 | def sign(self, msg): 30 | ''' 31 | Sign the given message with this key 32 | ''' 33 | return libnacl.crypto_sign(msg, self.sk) 34 | 35 | def signature(self, msg): 36 | ''' 37 | Return just the signature for the message 38 | ''' 39 | return libnacl.crypto_sign(msg, self.sk)[:libnacl.crypto_sign_BYTES] 40 | 41 | 42 | class Verifier(libnacl.base.BaseKey): 43 | ''' 44 | Verify signed messages 45 | ''' 46 | def __init__(self, vk_hex): 47 | ''' 48 | Create a verification key from a hex encoded vkey 49 | ''' 50 | self.vk = libnacl.encode.hex_decode(vk_hex) 51 | super().__init__() 52 | 53 | def verify(self, msg): 54 | ''' 55 | Verify the message with tis key 56 | ''' 57 | return libnacl.crypto_sign_open(msg, self.vk) 58 | -------------------------------------------------------------------------------- /libnacl/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import struct 4 | import sys 5 | import time 6 | 7 | # Import nacl libs 8 | import libnacl 9 | import libnacl.encode 10 | import libnacl.secret 11 | import libnacl.public 12 | import libnacl.sign 13 | import libnacl.dual 14 | 15 | 16 | def load_key(path_or_file, serial='json'): 17 | ''' 18 | Read in a key from a file and return the applicable key object based on 19 | the contents of the file 20 | ''' 21 | if hasattr(path_or_file, 'read'): 22 | stream = path_or_file 23 | else: 24 | if serial == 'json': 25 | stream = open(path_or_file, 'r') 26 | else: 27 | stream = open(path_or_file, 'rb') 28 | 29 | try: 30 | if serial == 'msgpack': 31 | import msgpack 32 | key_data = msgpack.load(stream) 33 | elif serial == 'json': 34 | import json 35 | if sys.version_info[0] >= 3: 36 | key_data = json.loads(stream.read()) 37 | else: 38 | key_data = json.loads(stream.read(), encoding='UTF-8') 39 | finally: 40 | if stream != path_or_file: 41 | stream.close() 42 | 43 | if 'priv' in key_data and 'sign' in key_data and 'pub' in key_data: 44 | return libnacl.dual.DualSecret( 45 | libnacl.encode.hex_decode(key_data['priv']), 46 | libnacl.encode.hex_decode(key_data['sign'])) 47 | elif 'priv' in key_data and 'pub' in key_data: 48 | return libnacl.public.SecretKey( 49 | libnacl.encode.hex_decode(key_data['priv'])) 50 | elif 'kx_priv' in key_data and 'kx_pub' in key_data: 51 | return libnacl.kx.ExchangeKey( 52 | libnacl.encode.hex_decode(key_data['kx_priv'])) 53 | elif 'sign' in key_data: 54 | return libnacl.sign.Signer( 55 | libnacl.encode.hex_decode(key_data['sign'])) 56 | elif 'pub' in key_data: 57 | return libnacl.public.PublicKey( 58 | libnacl.encode.hex_decode(key_data['pub'])) 59 | elif 'verify' in key_data: 60 | return libnacl.sign.Verifier(key_data['verify']) 61 | elif 'priv' in key_data: 62 | return libnacl.secret.SecretBox( 63 | libnacl.encode.hex_decode(key_data['priv'])) 64 | raise ValueError('Found no key data') 65 | 66 | 67 | def salsa_key(): 68 | ''' 69 | Generates a salsa2020 key 70 | ''' 71 | return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES) 72 | 73 | 74 | def aead_key(): 75 | ''' 76 | Generates an AEAD key (both implementations use the same size) 77 | ''' 78 | return libnacl.randombytes(libnacl.crypto_aead_aes256gcm_KEYBYTES) 79 | 80 | 81 | def rand_aead_nonce(): 82 | ''' 83 | Generates and returns a random bytestring of the size defined in libsodium 84 | as crypto_aead_aes256gcm_NPUBBYTES and crypto_aead_chacha20poly1305_ietf_NPUBBYTES 85 | ''' 86 | return libnacl.randombytes(libnacl.crypto_aead_aes256gcm_NPUBBYTES) 87 | 88 | 89 | def rand_aead_xchacha_nonce(): 90 | ''' 91 | Generates and returns a random bytestring of the size defined in libsodium 92 | as crypto_aead_aes256gcm_NPUBBYTES and crypto_aead_chacha20poly1305_ietf_NPUBBYTES 93 | ''' 94 | return libnacl.randombytes(libnacl.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES) 95 | 96 | 97 | def rand_nonce(): 98 | ''' 99 | Generates and returns a random bytestring of the size defined in libsodium 100 | as crypto_box_NONCEBYTES 101 | ''' 102 | return libnacl.randombytes(libnacl.crypto_box_NONCEBYTES) 103 | 104 | 105 | def time_nonce(): 106 | ''' 107 | Generates and returns a nonce as in rand_nonce() but using a timestamp for the first 8 bytes. 108 | 109 | This function now exists mostly for backwards compatibility, as rand_nonce() is usually preferred. 110 | ''' 111 | nonce = rand_nonce() 112 | return (struct.pack('=d', time.time()) + nonce)[:len(nonce)] 113 | -------------------------------------------------------------------------------- /pkg/rpm/python-libnacl.spec: -------------------------------------------------------------------------------- 1 | %if 0%{?fedora} > 12 || 0%{?rhel} > 6 2 | %global with_python3 1 3 | %endif 4 | 5 | %if 0%{?rhel} == 5 6 | %global pybasever 2.6 7 | %endif 8 | 9 | %{!?__python2: %global __python2 /usr/bin/python%{?pybasever}} 10 | %{!?python2_sitearch: %global python2_sitearch %(%{__python2} -c "from distutils.sysconfig import get_python_lib; print get_python_lib(1)")} 11 | %{!?python2_sitelib: %global python2_sitelib %(%{__python2} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")} 12 | 13 | %global srcname libnacl 14 | 15 | Name: python-%{srcname} 16 | Version: 1.4.3 17 | Release: 1%{?dist} 18 | Summary: Python bindings for libsodium based on ctypes 19 | 20 | Group: Development/Libraries 21 | License: ASL 2.0 22 | URL: https://github.com/saltstack/libnacl 23 | Source0: https://pypi.python.org/packages/source/l/%{srcname}/%{srcname}-%{version}.tar.gz 24 | 25 | BuildRoot: %{_tmppath}/%{srcname}-%{version}-%{release}-root-%(%{__id_u} -n) 26 | BuildArch: noarch 27 | 28 | BuildRequires: libsodium 29 | Requires: libsodium >= 0.5.0 30 | 31 | %if ! (0%{?rhel} == 5) 32 | BuildRequires: python 33 | BuildRequires: python-devel 34 | BuildRequires: python-setuptools 35 | %endif 36 | 37 | %if 0%{?with_python3} 38 | BuildRequires: python3-devel 39 | BuildRequires: python3-setuptools 40 | %endif 41 | 42 | %description 43 | This library is used to gain direct access to the functions exposed by Daniel 44 | J. Bernstein's nacl library via libsodium. It has been constructed 45 | to maintain extensive documentation on how to use nacl as well as being 46 | completely portable. The file in libnacl/__init__.py can be pulled out and 47 | placed directly in any project to give a single file binding to all of nacl. 48 | 49 | This is the Python 2 build of the module. 50 | 51 | %if 0%{?with_python3} 52 | %package -n python3-%{srcname} 53 | Summary: Python bindings for libsodium based on ctypes 54 | Group: Development/Libraries 55 | Requires: libsodium 56 | 57 | %description -n python3-%{srcname} 58 | This library is used to gain direct access to the functions exposed by Daniel 59 | J. Bernstein's nacl library via libsodium. It has been constructed 60 | to maintain extensive documentation on how to use nacl as well as being 61 | completely portable. The file in libnacl/__init__.py can be pulled out and 62 | placed directly in any project to give a single file binding to all of nacl. 63 | 64 | This is the Python 3 build of the module. 65 | %endif 66 | 67 | %if 0%{?rhel} == 5 68 | %package -n python26-%{srcname} 69 | Summary: Python bindings for libsodium based on ctypes 70 | Group: Development/Libraries 71 | BuildRequires: python26 72 | BuildRequires: libsodium 73 | BuildRequires: python26-devel 74 | Requires: python26 75 | Requires: libsodium 76 | 77 | %description -n python26-%{srcname} 78 | This library is used to gain direct access to the functions exposed by Daniel 79 | J. Bernstein's nacl library via libsodium. It has been constructed 80 | to maintain extensive documentation on how to use nacl as well as being 81 | completely portable. The file in libnacl/__init__.py can be pulled out and 82 | placed directly in any project to give a single file binding to all of nacl. 83 | 84 | This is the Python 2 build of the module. 85 | %endif 86 | 87 | %prep 88 | %setup -q -n %{srcname}-%{version} 89 | 90 | %if 0%{?with_python3} 91 | rm -rf %{py3dir} 92 | cp -a . %{py3dir} 93 | %endif 94 | 95 | %build 96 | %{__python2} setup.py build 97 | 98 | %if 0%{?with_python3} 99 | pushd %{py3dir} 100 | %{__python3} setup.py build 101 | popd 102 | %endif 103 | 104 | %install 105 | rm -rf %{buildroot} 106 | %{__python2} setup.py install --skip-build --root %{buildroot} 107 | 108 | %if 0%{?with_python3} 109 | pushd %{py3dir} 110 | %{__python3} setup.py install --skip-build --root %{buildroot} 111 | popd 112 | %endif 113 | 114 | %clean 115 | rm -rf %{buildroot} 116 | 117 | %if 0%{?rhel} == 5 118 | %files -n python26-%{srcname} 119 | %defattr(-,root,root,-) 120 | %{python2_sitelib}/* 121 | %else 122 | %files 123 | %defattr(-,root,root,-) 124 | %{python2_sitelib}/* 125 | %endif 126 | 127 | %if 0%{?with_python3} 128 | %files -n python3-%{srcname} 129 | %defattr(-,root,root,-) 130 | %{python3_sitelib}/* 131 | %endif 132 | 133 | %changelog 134 | * Thu Sep 4 2014 Erik Johnson - 1.3.5-1 135 | - Updated to 1.3.5 136 | 137 | * Fri Aug 22 2014 Erik Johnson - 1.3.3-1 138 | - Updated to 1.3.3 139 | 140 | * Fri Aug 8 2014 Erik Johnson - 1.3.2-1 141 | - Updated to 1.3.2 142 | 143 | * Fri Aug 8 2014 Erik Johnson - 1.3.1-1 144 | - Updated to 1.3.1 145 | 146 | * Thu Aug 7 2014 Erik Johnson - 1.3.0-1 147 | - Updated to 1.3.0 148 | 149 | * Fri Jun 20 2014 Erik Johnson - 1.1.0-1 150 | - Updated to 1.1.0 151 | 152 | * Fri Jun 20 2014 Erik Johnson - 1.0.0-1 153 | - Initial build 154 | -------------------------------------------------------------------------------- /pkg/suse/python-libnacl.changes: -------------------------------------------------------------------------------- 1 | ------------------------------------------------------------------- 2 | Wed Jul 2 18:28:08 UTC 2014 - aboe76@gmail.com 3 | 4 | - Updated to 1.1.0 5 | 6 | ------------------------------------------------------------------- 7 | Fri Jun 20 15:10:52 UTC 2014 - aboe76@gmail.com 8 | 9 | - Simplified BuildRequirements to libsodium-devel 10 | 11 | ------------------------------------------------------------------- 12 | Mon Jun 9 10:53:12 UTC 2014 - aboe76@gmail.com 13 | 14 | - initial package 15 | 16 | -------------------------------------------------------------------------------- /pkg/suse/python-libnacl.spec: -------------------------------------------------------------------------------- 1 | # 2 | # spec file for package python-libnacl 3 | # 4 | # Copyright (c) 2014 SUSE LINUX Products GmbH, Nuernberg, Germany. 5 | # 6 | # All modifications and additions to the file contributed by third parties 7 | # remain the property of their copyright owners, unless otherwise agreed 8 | # upon. The license for this file, and modifications and additions to the 9 | # file, is the same license as for the pristine package itself (unless the 10 | # license for the pristine package is not an Open Source License, in which 11 | # case the license is the MIT License). An "Open Source License" is a 12 | # license that conforms to the Open Source Definition (Version 1.9) 13 | # published by the Open Source Initiative. 14 | 15 | # Please submit bugfixes or comments via http://bugs.opensuse.org/ 16 | # 17 | 18 | Name: python-libnacl 19 | Version: 1.4.3 20 | Release: 0 21 | License: Apache-2.0 22 | Summary: Python bindings for libsodium based on ctypes 23 | Url: https://github.com/saltstack/libnacl 24 | Group: Development/Languages/Python 25 | Source0: https://pypi.python.org/packages/source/l/libnacl/libnacl-%{version}.tar.gz 26 | BuildRoot: %{_tmppath}/libnacl-%{version}-build 27 | 28 | BuildRequires: python-setuptools 29 | BuildRequires: python-devel 30 | BuildRequires: libsodium-devel 31 | BuildRequires: fdupes 32 | 33 | BuildRoot: %{_tmppath}/%{name}-%{version}-build 34 | %if 0%{?suse_version} && 0%{?suse_version} <= 1110 35 | %{!?python_sitelib: %global python_sitelib %(python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()")} 36 | %else 37 | BuildArch: noarch 38 | %endif 39 | 40 | %description 41 | This library is used to gain direct access to the functions exposed by Daniel J. Bernstein's nacl library via libsodium. 42 | It has been constructed to maintain extensive documentation on how to use nacl as well as being completely portable. The file 43 | in libnacl/__init__.py can be pulled out and placed directly in any project to give a single file binding to all of nacl. 44 | 45 | %prep 46 | %setup -q -n libnacl-%{version} 47 | 48 | %build 49 | python setup.py build 50 | 51 | %install 52 | python setup.py install --prefix=%{_prefix} --root=%{buildroot} --optimize=1 53 | %fdupes %{buildroot}%{_prefix} 54 | 55 | %files 56 | %defattr(-,root,root) 57 | %{python_sitelib}/* 58 | 59 | %changelog -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "libnacl" 3 | version = "2.1.0" 4 | description = "Python bindings for libsodium based on ctypes" 5 | authors = ["Thomas S Hatch "] 6 | license = "Apache-2.0" 7 | homepage="https://libnacl.readthedocs.org" 8 | repository="https://github.com/saltstack/libnacl" 9 | documentation="https://libnacl.readthedocs.org" 10 | readme = "README.rst" 11 | classifiers = [ 12 | "Operating System :: OS Independent", 13 | "License :: OSI Approved :: Apache Software License", 14 | "Programming Language :: Python", 15 | "Programming Language :: Python :: 2.6", 16 | "Programming Language :: Python :: 2.7", 17 | "Programming Language :: Python :: 3.4", 18 | "Programming Language :: Python :: 3.5", 19 | "Programming Language :: Python :: 3.6", 20 | "Programming Language :: Python :: 3.7", 21 | "Programming Language :: Python :: 3.8", 22 | "Programming Language :: Python :: 3.9", 23 | "Programming Language :: Python :: 3.10", 24 | "Programming Language :: Python :: 3.11", 25 | "Development Status :: 5 - Production/Stable", 26 | "Intended Audience :: Developers", 27 | "Topic :: Security :: Cryptography", 28 | ] 29 | include = [ 30 | { path = "doc", format = "sdist" }, 31 | { path = "tests", format = "sdist" }, 32 | ] 33 | 34 | [tool.poetry.dependencies] 35 | python = "^3.4" 36 | 37 | 38 | [build-system] 39 | requires = ["poetry-core"] 40 | build-backend = "poetry.core.masonry.api" 41 | -------------------------------------------------------------------------------- /tests/runtests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Import python libs 5 | import os 6 | import sys 7 | import unittest 8 | 9 | NACL_ROOT = os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) 10 | UNIT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), 'unit')) 11 | 12 | sys.path.insert(0, NACL_ROOT) 13 | 14 | 15 | def run_suite(path=UNIT_ROOT): 16 | ''' 17 | Execute the unttest suite 18 | ''' 19 | loader = unittest.TestLoader() 20 | tests = loader.discover(path) 21 | unittest.TextTestRunner(verbosity=2).run(tests) 22 | 23 | 24 | 25 | if __name__ == '__main__': 26 | run_suite() 27 | -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /tests/unit/test_aead.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl.aead 3 | # Import python libs 4 | import unittest 5 | 6 | class TestAEAD(unittest.TestCase): 7 | ''' 8 | ''' 9 | @unittest.skipUnless(libnacl.HAS_AEAD_AES256GCM, 'AES256-GCM AEAD not available') 10 | def test_gcm_aead(self): 11 | msg = b"You've got two empty halves of coconuts and your bangin' 'em together." 12 | aad = b'\x00\x11\x22\x33' 13 | box = libnacl.aead.AEAD().useAESGCM() 14 | ctxt = box.encrypt(msg, aad) 15 | self.assertNotEqual(msg, ctxt) 16 | 17 | box2 = libnacl.aead.AEAD(box.sk).useAESGCM() 18 | clear1 = box.decrypt(ctxt, len(aad)) 19 | self.assertEqual(msg, clear1) 20 | clear2 = box2.decrypt(ctxt, len(aad)) 21 | self.assertEqual(clear1, clear2) 22 | ctxt2 = box2.encrypt(msg, aad) 23 | clear3 = box.decrypt(ctxt2, len(aad)) 24 | self.assertEqual(clear3, msg) 25 | 26 | @unittest.skipUnless(libnacl.HAS_AEAD_AES256GCM, 'AES256-GCM AEAD not available') 27 | def test_gcm_aead_class(self): 28 | msg = b"You've got two empty halves of coconuts and your bangin' 'em together." 29 | aad = b'\x00\x11\x22\x33' 30 | box = libnacl.aead.AEAD_AESGCM() 31 | ctxt = box.encrypt(msg, aad) 32 | self.assertNotEqual(msg, ctxt) 33 | 34 | box2 = libnacl.aead.AEAD_AESGCM(box.sk) 35 | clear1 = box.decrypt(ctxt, len(aad)) 36 | self.assertEqual(msg, clear1) 37 | clear2 = box2.decrypt(ctxt, len(aad)) 38 | self.assertEqual(clear1, clear2) 39 | ctxt2 = box2.encrypt(msg, aad) 40 | clear3 = box.decrypt(ctxt2, len(aad)) 41 | self.assertEqual(clear3, msg) 42 | 43 | @unittest.skipUnless(libnacl.HAS_AEAD_CHACHA20POLY1305_IETF, 'IETF variant of ChaCha20Poly1305 AEAD not available') 44 | def test_ietf_aead(self): 45 | msg = b"Our King? Well i didn't vote for you!!" 46 | aad = b'\x00\x11\x22\x33' 47 | box = libnacl.aead.AEAD() 48 | ctxt = box.encrypt(msg, aad) 49 | self.assertNotEqual(msg, ctxt) 50 | 51 | box2 = libnacl.aead.AEAD(box.sk) 52 | clear1 = box.decrypt(ctxt, len(aad)) 53 | self.assertEqual(msg, clear1) 54 | clear2 = box2.decrypt(ctxt, len(aad)) 55 | self.assertEqual(clear1, clear2) 56 | ctxt2 = box2.encrypt(msg, aad) 57 | clear3 = box.decrypt(ctxt2, len(aad)) 58 | 59 | @unittest.skipUnless(libnacl.HAS_AEAD_CHACHA20POLY1305_IETF, 'IETF variant of ChaCha20Poly1305 AEAD not available') 60 | def test_ietf_aead_class(self): 61 | msg = b"Our King? Well i didn't vote for you!!" 62 | aad = b'\x00\x11\x22\x33' 63 | box = libnacl.aead.AEAD_CHACHA() 64 | ctxt = box.encrypt(msg, aad) 65 | self.assertNotEqual(msg, ctxt) 66 | 67 | box2 = libnacl.aead.AEAD_CHACHA(box.sk) 68 | clear1 = box.decrypt(ctxt, len(aad)) 69 | self.assertEqual(msg, clear1) 70 | clear2 = box2.decrypt(ctxt, len(aad)) 71 | self.assertEqual(clear1, clear2) 72 | ctxt2 = box2.encrypt(msg, aad) 73 | clear3 = box.decrypt(ctxt2, len(aad)) 74 | 75 | @unittest.skipUnless(libnacl.HAS_AEAD_XCHACHA20POLY1305_IETF, 'IETF variant of xChaCha20Poly1305 AEAD not available') 76 | def test_ietf_aead_xchacha(self): 77 | msg = b"Our King? Well i didn't vote for you!!" 78 | aad = b'\x00\x11\x22\x33' 79 | box = libnacl.aead.AEAD().useXCHACHA() 80 | ctxt = box.encrypt(msg, aad) 81 | self.assertNotEqual(msg, ctxt) 82 | 83 | box2 = libnacl.aead.AEAD(box.sk).useXCHACHA() 84 | clear1 = box.decrypt(ctxt, len(aad)) 85 | self.assertEqual(msg, clear1) 86 | clear2 = box2.decrypt(ctxt, len(aad)) 87 | self.assertEqual(clear1, clear2) 88 | ctxt2 = box2.encrypt(msg, aad) 89 | clear3 = box.decrypt(ctxt2, len(aad)) 90 | self.assertEqual(clear3, msg) 91 | self.assertEqual(clear3, msg) 92 | 93 | 94 | @unittest.skipUnless(libnacl.HAS_AEAD_XCHACHA20POLY1305_IETF, 'IETF variant of xChaCha20Poly1305 AEAD not available') 95 | def test_ietf_aead_xchacha_class(self): 96 | msg = b"Our King? Well i didn't vote for you!!" 97 | aad = b'\x00\x11\x22\x33' 98 | box = libnacl.aead.AEAD_XCHACHA() 99 | ctxt = box.encrypt(msg, aad) 100 | self.assertNotEqual(msg, ctxt) 101 | 102 | box2 = libnacl.aead.AEAD_XCHACHA(box.sk) 103 | clear1 = box.decrypt(ctxt, len(aad)) 104 | self.assertEqual(msg, clear1) 105 | clear2 = box2.decrypt(ctxt, len(aad)) 106 | self.assertEqual(clear1, clear2) 107 | ctxt2 = box2.encrypt(msg, aad) 108 | clear3 = box.decrypt(ctxt2, len(aad)) 109 | self.assertEqual(clear3, msg) 110 | self.assertEqual(clear3, msg) 111 | 112 | -------------------------------------------------------------------------------- /tests/unit/test_auth_verify.py: -------------------------------------------------------------------------------- 1 | # Import nacl libs 2 | import libnacl 3 | import libnacl.utils 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | 9 | class TestAuthVerify(unittest.TestCase): 10 | ''' 11 | Test onetimeauth functions 12 | ''' 13 | def test_auth_verify(self): 14 | msg = b'Anybody can invent a cryptosystem he cannot break himself. Except Bruce Schneier.' 15 | key1 = libnacl.utils.salsa_key() 16 | key2 = libnacl.utils.salsa_key() 17 | 18 | sig1 = libnacl.crypto_auth(msg, key1) 19 | sig2 = libnacl.crypto_auth(msg, key2) 20 | 21 | self.assertTrue(libnacl.crypto_auth_verify(sig1, msg, key1)) 22 | self.assertTrue(libnacl.crypto_auth_verify(sig2, msg, key2)) 23 | with self.assertRaises(ValueError) as context: 24 | libnacl.crypto_auth_verify(sig1, msg, key2) 25 | self.assertTrue('Failed to auth msg' in context.exception.args) 26 | 27 | with self.assertRaises(ValueError) as context: 28 | libnacl.crypto_auth_verify(sig2, msg, key1) 29 | self.assertTrue('Failed to auth msg' in context.exception.args) 30 | 31 | def test_onetimeauth_verify(self): 32 | self.assertEqual("poly1305", libnacl.crypto_onetimeauth_primitive()) 33 | 34 | msg = b'Anybody can invent a cryptosystem he cannot break himself. Except Bruce Schneier.' 35 | key1 = libnacl.randombytes(libnacl.crypto_onetimeauth_KEYBYTES) 36 | key2 = libnacl.randombytes(libnacl.crypto_onetimeauth_KEYBYTES) 37 | 38 | sig1 = libnacl.crypto_onetimeauth(msg, key1) 39 | sig2 = libnacl.crypto_onetimeauth(msg, key2) 40 | 41 | with self.assertRaises(ValueError): 42 | libnacl.crypto_onetimeauth(msg, b'too_short') 43 | 44 | with self.assertRaises(ValueError): 45 | libnacl.crypto_onetimeauth_verify(sig1, msg, b'too_short') 46 | 47 | with self.assertRaises(ValueError): 48 | libnacl.crypto_onetimeauth_verify(b'too_short', msg, key1) 49 | 50 | self.assertTrue(libnacl.crypto_onetimeauth_verify(sig1, msg, key1)) 51 | self.assertTrue(libnacl.crypto_onetimeauth_verify(sig2, msg, key2)) 52 | with self.assertRaises(ValueError) as context: 53 | libnacl.crypto_onetimeauth_verify(sig1, msg, key2) 54 | self.assertTrue('Failed to auth message' in context.exception.args) 55 | 56 | with self.assertRaises(ValueError) as context: 57 | libnacl.crypto_onetimeauth_verify(sig2, msg, key1) 58 | self.assertTrue('Failed to auth message' in context.exception.args) 59 | 60 | def test_auth_rejects_wrong_lengths(self): 61 | msg = b'Time is an illusion. Lunchtime doubly so.' 62 | for bad_key in (b'too short', b'too long' * 100): 63 | with self.assertRaises(ValueError) as context: 64 | libnacl.crypto_auth(msg, bad_key) 65 | self.assertEqual(context.exception.args, ('Invalid secret key',)) 66 | 67 | def test_auth_verify_rejects_wrong_key_lengths(self): 68 | msg = b"I'd take the awe of understanding over the awe of ignorance any day." 69 | good_key = b'This valid key is 32 bytes long.' 70 | good_token = b'This token is likewise also 32B.' 71 | 72 | for bad_key in (b'too short', b'too long' * 100): 73 | with self.assertRaises(ValueError) as context: 74 | libnacl.crypto_auth_verify(good_token, msg, bad_key) 75 | self.assertEqual(context.exception.args, ('Invalid secret key',)) 76 | 77 | for bad_token in (b'too short', b'too long' * 100): 78 | with self.assertRaises(ValueError) as context: 79 | libnacl.crypto_auth_verify(bad_token, msg, good_key) 80 | self.assertEqual(context.exception.args, ('Invalid authenticator',)) 81 | 82 | def test_onetimeauth_rejects_wrong_lengths(self): 83 | msg = b"Are the most dangerous creatures the ones that use doors or the ones that don't?" 84 | for bad_key in (b'too short', b'too long' * 100): 85 | with self.assertRaises(ValueError) as context: 86 | libnacl.crypto_onetimeauth(msg, bad_key) 87 | self.assertEqual(context.exception.args, ('Invalid secret key',)) 88 | 89 | def test_onetimeauth_verify_rejects_wrong_key_lengths(self): 90 | msg = b"Of all the dogs I've known in my life, I've never seen a better driver." 91 | good_key = b'This valid key is 32 bytes long.' 92 | good_token = b'1time tokens=16B' 93 | 94 | for bad_key in (b'too short', b'too long' * 100): 95 | with self.assertRaises(ValueError) as context: 96 | libnacl.crypto_onetimeauth_verify(good_token, msg, bad_key) 97 | self.assertEqual(context.exception.args, ('Invalid secret key',)) 98 | 99 | for bad_token in (b'too short', b'too long' * 100): 100 | with self.assertRaises(ValueError) as context: 101 | libnacl.crypto_onetimeauth_verify(bad_token, msg, good_key) 102 | self.assertEqual(context.exception.args, ('Invalid authenticator',)) 103 | -------------------------------------------------------------------------------- /tests/unit/test_blake.py: -------------------------------------------------------------------------------- 1 | # Import nacl libs 2 | import libnacl.blake 3 | 4 | # Import python libs 5 | import unittest 6 | 7 | 8 | class TestBlake(unittest.TestCase): 9 | ''' 10 | Test sign functions 11 | ''' 12 | def test_keyless_blake(self): 13 | msg1 = b'Are you suggesting coconuts migrate?' 14 | msg2 = b'Not at all, they could be carried.' 15 | chash1 = libnacl.crypto_generichash(msg1) 16 | chash2 = libnacl.crypto_generichash(msg2) 17 | self.assertNotEqual(msg1, chash1) 18 | self.assertNotEqual(msg2, chash2) 19 | self.assertNotEqual(chash2, chash1) 20 | 21 | def test_key_blake(self): 22 | msg1 = b'Are you suggesting coconuts migrate?' 23 | msg2 = b'Not at all, they could be carried.' 24 | key1 = libnacl.utils.rand_nonce() 25 | key2 = libnacl.utils.rand_nonce() 26 | khash1_1 = libnacl.blake.Blake2b(msg1, key1).digest() 27 | khash1_1_2 = libnacl.blake.Blake2b(msg1, key1).digest() 28 | khash1_2 = libnacl.blake.Blake2b(msg1, key2).digest() 29 | khash2_1 = libnacl.blake.blake2b(msg2, key1).digest() 30 | khash2_2 = libnacl.blake.blake2b(msg2, key2).digest() 31 | self.assertNotEqual(msg1, khash1_1) 32 | self.assertNotEqual(msg1, khash1_2) 33 | self.assertNotEqual(msg2, khash2_1) 34 | self.assertNotEqual(msg2, khash2_2) 35 | self.assertNotEqual(khash1_1, khash1_2) 36 | self.assertNotEqual(khash2_1, khash2_2) 37 | self.assertNotEqual(khash1_1, khash2_1) 38 | self.assertNotEqual(khash1_2, khash2_2) 39 | self.assertEqual(khash1_1, khash1_1_2) 40 | -------------------------------------------------------------------------------- /tests/unit/test_dual.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl.public 3 | import libnacl.dual 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | class TestDual(unittest.TestCase): 9 | ''' 10 | ''' 11 | def test_secretkey(self): 12 | ''' 13 | ''' 14 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 15 | bob = libnacl.dual.DualSecret() 16 | alice = libnacl.dual.DualSecret() 17 | bob_box = libnacl.public.Box(bob.sk, alice.pk) 18 | alice_box = libnacl.public.Box(alice.sk, bob.pk) 19 | bob_ctxt = bob_box.encrypt(msg) 20 | self.assertNotEqual(msg, bob_ctxt) 21 | bclear = alice_box.decrypt(bob_ctxt) 22 | self.assertEqual(msg, bclear) 23 | alice_ctxt = alice_box.encrypt(msg) 24 | self.assertNotEqual(msg, alice_ctxt) 25 | aclear = alice_box.decrypt(alice_ctxt) 26 | self.assertEqual(msg, aclear) 27 | self.assertNotEqual(bob_ctxt, alice_ctxt) 28 | self.assertEqual(bob.pk_hex, bob.hex_pk()) 29 | self.assertEqual(bob.sk_hex, bob.hex_sk()) 30 | self.assertEqual(bob.vk_hex, bob.hex_vk()) 31 | 32 | def test_publickey(self): 33 | ''' 34 | ''' 35 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 36 | bob = libnacl.dual.DualSecret() 37 | alice = libnacl.dual.DualSecret() 38 | alice_pk = libnacl.public.PublicKey(alice.pk) 39 | bob_box = libnacl.public.Box(bob.sk, alice_pk) 40 | alice_box = libnacl.public.Box(alice.sk, bob.pk) 41 | bob_ctxt = bob_box.encrypt(msg) 42 | self.assertNotEqual(msg, bob_ctxt) 43 | bclear = alice_box.decrypt(bob_ctxt) 44 | self.assertEqual(msg, bclear) 45 | self.assertEqual(bob.pk_hex, bob.hex_pk()) 46 | self.assertEqual(bob.sk_hex, bob.hex_sk()) 47 | self.assertEqual(bob.vk_hex, bob.hex_vk()) 48 | 49 | def test_sign(self): 50 | msg = (b'Well, that\'s no ordinary rabbit. That\'s the most foul, ' 51 | b'cruel, and bad-tempered rodent you ever set eyes on.') 52 | signer = libnacl.dual.DualSecret() 53 | signed = signer.sign(msg) 54 | signature = signer.signature(msg) 55 | self.assertNotEqual(msg, signed) 56 | veri = libnacl.sign.Verifier(signer.hex_vk()) 57 | verified = veri.verify(signed) 58 | verified2 = veri.verify(signature + msg) 59 | self.assertEqual(verified, msg) 60 | self.assertEqual(verified2, msg) 61 | -------------------------------------------------------------------------------- /tests/unit/test_kx.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl.kx 3 | 4 | # Import python libs 5 | import unittest 6 | 7 | class TestKX(unittest.TestCase): 8 | ''' 9 | ''' 10 | def test_exchange_key(self): 11 | ''' 12 | ''' 13 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 14 | ad = b'A Duck!' 15 | # Make Bob and Alice Exchange Keys 16 | bob = libnacl.kx.ExchangeKey() 17 | alice = libnacl.kx.ExchangeKey() 18 | # Encrypt with bob as clientm alic as server 19 | bob_ctxt = bob.encrypt_client(alice.kx_pk, msg, ad) 20 | self.assertNotEqual(msg, bob_ctxt) 21 | bclear = alice.decrypt_server(bob.kx_pk, bob_ctxt, len(ad)) 22 | self.assertEqual(ad, bob_ctxt[:len(ad)]) 23 | self.assertEqual(msg, bclear) 24 | alice_ctxt = alice.encrypt_server(bob.kx_pk, msg, ad) 25 | aclear = bob.decrypt_client(alice.kx_pk, alice_ctxt, len(ad)) 26 | self.assertEqual(ad, alice_ctxt[:len(ad)]) 27 | self.assertEqual(msg, aclear) 28 | self.assertNotEqual(msg, alice_ctxt) 29 | # Encrypt with Alice as client bob as server 30 | alice_ctxt = alice.encrypt_client(bob.kx_pk, msg, ad) 31 | self.assertNotEqual(msg, alice_ctxt) 32 | bclear = bob.decrypt_server(alice.kx_pk, alice_ctxt, len(ad)) 33 | self.assertEqual(ad, alice_ctxt[:len(ad)]) 34 | self.assertEqual(msg, bclear) 35 | 36 | -------------------------------------------------------------------------------- /tests/unit/test_public.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl.public 3 | 4 | # Import python libs 5 | import unittest 6 | 7 | class TestPublic(unittest.TestCase): 8 | ''' 9 | ''' 10 | def test_secretkey(self): 11 | ''' 12 | ''' 13 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 14 | bob = libnacl.public.SecretKey() 15 | alice = libnacl.public.SecretKey() 16 | bob_box = libnacl.public.Box(bob.sk, alice.pk) 17 | alice_box = libnacl.public.Box(alice.sk, bob.pk) 18 | bob_ctxt = bob_box.encrypt(msg) 19 | self.assertNotEqual(msg, bob_ctxt) 20 | bclear = alice_box.decrypt(bob_ctxt) 21 | self.assertEqual(msg, bclear) 22 | alice_ctxt = alice_box.encrypt(msg) 23 | self.assertNotEqual(msg, alice_ctxt) 24 | aclear = alice_box.decrypt(alice_ctxt) 25 | self.assertEqual(msg, aclear) 26 | self.assertNotEqual(bob_ctxt, alice_ctxt) 27 | self.assertEqual(bob.pk_hex, bob.hex_pk()) 28 | self.assertEqual(bob.sk_hex, bob.hex_sk()) 29 | 30 | def test_publickey(self): 31 | ''' 32 | ''' 33 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 34 | bob = libnacl.public.SecretKey() 35 | alice = libnacl.public.SecretKey() 36 | alice_pk = libnacl.public.PublicKey(alice.pk) 37 | bob_box = libnacl.public.Box(bob.sk, alice_pk) 38 | alice_box = libnacl.public.Box(alice.sk, bob.pk) 39 | bob_ctxt = bob_box.encrypt(msg) 40 | self.assertNotEqual(msg, bob_ctxt) 41 | bclear = alice_box.decrypt(bob_ctxt) 42 | self.assertEqual(msg, bclear) 43 | self.assertEqual(bob.sk_hex, bob.hex_sk()) 44 | 45 | -------------------------------------------------------------------------------- /tests/unit/test_raw_auth_sym.py: -------------------------------------------------------------------------------- 1 | # Import nacl libs 2 | import libnacl 3 | import libnacl.utils 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | 9 | class TestSecretBox(unittest.TestCase): 10 | ''' 11 | Test sign functions 12 | ''' 13 | def test_secret_box(self): 14 | msg = b'Are you suggesting coconuts migrate?' 15 | sk1 = libnacl.utils.salsa_key() 16 | nonce1 = libnacl.utils.rand_nonce() 17 | enc_msg = libnacl.crypto_secretbox(msg, nonce1, sk1) 18 | self.assertNotEqual(msg, enc_msg) 19 | clear_msg = libnacl.crypto_secretbox_open(enc_msg, nonce1, sk1) 20 | self.assertEqual(msg, clear_msg) 21 | -------------------------------------------------------------------------------- /tests/unit/test_raw_auth_sym_easy.py: -------------------------------------------------------------------------------- 1 | # Import nacl libs 2 | import libnacl 3 | import libnacl.utils 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | 9 | class TestSecretBox(unittest.TestCase): 10 | ''' 11 | Test sign functions 12 | ''' 13 | def test_secret_box_easy(self): 14 | msg = b'Are you suggesting coconuts migrate?' 15 | sk1 = libnacl.utils.salsa_key() 16 | nonce1 = libnacl.utils.rand_nonce() 17 | enc_msg = libnacl.crypto_secretbox_easy(msg, nonce1, sk1) 18 | self.assertNotEqual(msg, enc_msg) 19 | clear_msg = libnacl.crypto_secretbox_open_easy(enc_msg, nonce1, sk1) 20 | self.assertEqual(msg, clear_msg) 21 | -------------------------------------------------------------------------------- /tests/unit/test_raw_generichash.py: -------------------------------------------------------------------------------- 1 | # Import nacl libs 2 | import libnacl 3 | 4 | # Import python libs 5 | import unittest 6 | 7 | 8 | class TestGenericHash(unittest.TestCase): 9 | ''' 10 | Test sign functions 11 | ''' 12 | def test_keyless_generichash(self): 13 | msg1 = b'Are you suggesting coconuts migrate?' 14 | msg2 = b'Not at all, they could be carried.' 15 | chash1 = libnacl.crypto_generichash(msg1) 16 | chash2 = libnacl.crypto_generichash(msg2) 17 | self.assertNotEqual(msg1, chash1) 18 | self.assertNotEqual(msg2, chash2) 19 | self.assertNotEqual(chash2, chash1) 20 | 21 | def test_key_generichash(self): 22 | msg1 = b'Are you suggesting coconuts migrate?' 23 | msg2 = b'Not at all, they could be carried.' 24 | key1 = libnacl.utils.rand_nonce() 25 | key2 = libnacl.utils.rand_nonce() 26 | khash1_1 = libnacl.crypto_generichash(msg1, key1) 27 | khash1_1_2 = libnacl.crypto_generichash(msg1, key1) 28 | khash1_2 = libnacl.crypto_generichash(msg1, key2) 29 | khash2_1 = libnacl.crypto_generichash(msg2, key1) 30 | khash2_2 = libnacl.crypto_generichash(msg2, key2) 31 | self.assertNotEqual(msg1, khash1_1) 32 | self.assertNotEqual(msg1, khash1_2) 33 | self.assertNotEqual(msg2, khash2_1) 34 | self.assertNotEqual(msg2, khash2_2) 35 | self.assertNotEqual(khash1_1, khash1_2) 36 | self.assertNotEqual(khash2_1, khash2_2) 37 | self.assertNotEqual(khash1_1, khash2_1) 38 | self.assertNotEqual(khash1_2, khash2_2) 39 | self.assertEqual(khash1_1, khash1_1_2) 40 | -------------------------------------------------------------------------------- /tests/unit/test_raw_hash.py: -------------------------------------------------------------------------------- 1 | # Import nacl libs 2 | import libnacl 3 | from hashlib import sha256, sha512 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | 9 | class TestHash(unittest.TestCase): 10 | """ 11 | Test sign functions 12 | """ 13 | def test_hash(self): 14 | msg1 = b'Are you suggesting coconuts migrate?' 15 | msg2 = b'Not at all, they could be carried.' 16 | chash1 = libnacl.crypto_hash(msg1) 17 | chash2 = libnacl.crypto_hash(msg2) 18 | self.assertNotEqual(msg1, chash1) 19 | self.assertNotEqual(msg2, chash2) 20 | self.assertNotEqual(chash2, chash1) 21 | 22 | ref256 = sha256(msg1) 23 | self.assertEqual(ref256.digest_size, libnacl.crypto_hash_sha256_BYTES) 24 | self.assertEqual(ref256.digest(), libnacl.crypto_hash_sha256(msg1)) 25 | 26 | ref512 = sha512(msg1) 27 | self.assertEqual(ref512.digest_size, libnacl.crypto_hash_sha512_BYTES) 28 | self.assertEqual(ref512.digest(), libnacl.crypto_hash_sha512(msg1)) 29 | 30 | -------------------------------------------------------------------------------- /tests/unit/test_raw_public.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl 3 | import libnacl.utils 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | 9 | class TestPublic(unittest.TestCase): 10 | ''' 11 | Test public functions 12 | ''' 13 | def test_gen(self): 14 | pk1, sk1 = libnacl.crypto_box_keypair() 15 | pk2, sk2 = libnacl.crypto_box_keypair() 16 | pk3, sk3 = libnacl.crypto_box_keypair() 17 | self.assertEqual(len(pk1), libnacl.crypto_box_PUBLICKEYBYTES) 18 | self.assertEqual(len(sk1), libnacl.crypto_box_PUBLICKEYBYTES) 19 | self.assertEqual(len(pk2), libnacl.crypto_box_PUBLICKEYBYTES) 20 | self.assertEqual(len(sk2), libnacl.crypto_box_PUBLICKEYBYTES) 21 | self.assertEqual(len(pk3), libnacl.crypto_box_PUBLICKEYBYTES) 22 | self.assertEqual(len(sk3), libnacl.crypto_box_PUBLICKEYBYTES) 23 | self.assertNotEqual(pk1, sk1) 24 | self.assertNotEqual(pk2, sk2) 25 | self.assertNotEqual(pk3, sk3) 26 | self.assertNotEqual(pk1, pk2) 27 | self.assertNotEqual(pk1, pk3) 28 | self.assertNotEqual(sk1, sk2) 29 | self.assertNotEqual(sk2, sk3) 30 | 31 | def test_box(self): 32 | msg = b'Are you suggesting coconuts migrate?' 33 | # run 1 34 | nonce1 = libnacl.utils.rand_nonce() 35 | pk1, sk1 = libnacl.crypto_box_keypair() 36 | pk2, sk2 = libnacl.crypto_box_keypair() 37 | enc_msg = libnacl.crypto_box(msg, nonce1, pk2, sk1) 38 | self.assertNotEqual(msg, enc_msg) 39 | clear_msg = libnacl.crypto_box_open(enc_msg, nonce1, pk1, sk2) 40 | self.assertEqual(clear_msg, msg) 41 | # run 2 42 | nonce2 = libnacl.utils.rand_nonce() 43 | pk3, sk3 = libnacl.crypto_box_keypair() 44 | pk4, sk4 = libnacl.crypto_box_keypair() 45 | enc_msg2 = libnacl.crypto_box(msg, nonce2, pk4, sk3) 46 | self.assertNotEqual(msg, enc_msg2) 47 | clear_msg2 = libnacl.crypto_box_open(enc_msg2, nonce2, pk3, sk4) 48 | self.assertEqual(clear_msg2, msg) 49 | # Check bits 50 | self.assertNotEqual(nonce1, nonce2) 51 | self.assertNotEqual(enc_msg, enc_msg2) 52 | 53 | def test_boxnm(self): 54 | msg = b'Are you suggesting coconuts migrate?' 55 | # run 1 56 | nonce1 = libnacl.utils.rand_nonce() 57 | pk1, sk1 = libnacl.crypto_box_keypair() 58 | pk2, sk2 = libnacl.crypto_box_keypair() 59 | k1 = libnacl.crypto_box_beforenm(pk2, sk1) 60 | k2 = libnacl.crypto_box_beforenm(pk1, sk2) 61 | enc_msg = libnacl.crypto_box_afternm(msg, nonce1, k1) 62 | self.assertNotEqual(msg, enc_msg) 63 | clear_msg = libnacl.crypto_box_open_afternm(enc_msg, nonce1, k2) 64 | self.assertEqual(clear_msg, msg) 65 | 66 | def test_box_seal(self): 67 | msg = b'Are you suggesting coconuts migrate?' 68 | # run 1 69 | pk, sk = libnacl.crypto_box_keypair() 70 | enc_msg = libnacl.crypto_box_seal(msg, pk) 71 | self.assertNotEqual(msg, enc_msg) 72 | clear_msg = libnacl.crypto_box_seal_open(enc_msg, pk, sk) 73 | self.assertEqual(clear_msg, msg) 74 | # run 2 75 | pk2, sk2 = libnacl.crypto_box_keypair() 76 | enc_msg2 = libnacl.crypto_box_seal(msg, pk2) 77 | self.assertNotEqual(msg, enc_msg2) 78 | clear_msg2 = libnacl.crypto_box_seal_open(enc_msg2, pk2, sk2) 79 | self.assertEqual(clear_msg2, msg) 80 | # Check bits 81 | self.assertNotEqual(enc_msg, enc_msg2) 82 | 83 | def test_scalarmult_rejects_wrong_length(self): 84 | good_key = b'This valid key is 32 bytes long.' 85 | 86 | for bad_key in (b'too short', b'too long' * 100): 87 | with self.assertRaises(ValueError) as context: 88 | libnacl.crypto_scalarmult_base(bad_key) 89 | self.assertEqual(context.exception.args, ('Invalid secret key',)) 90 | 91 | self.assertEqual(libnacl.crypto_box_PUBLICKEYBYTES, len(libnacl.crypto_scalarmult_base(good_key))) 92 | -------------------------------------------------------------------------------- /tests/unit/test_raw_random.py: -------------------------------------------------------------------------------- 1 | """ 2 | Basic tests for randombytes_* functions 3 | """ 4 | 5 | import libnacl 6 | import unittest 7 | 8 | 9 | class TestRandomBytes(unittest.TestCase): 10 | def test_randombytes_random(self): 11 | self.assertIsInstance(libnacl.randombytes_random(), int) 12 | 13 | def test_randombytes_uniform(self): 14 | self.assertIsInstance(libnacl.randombytes_uniform(200), int) 15 | 16 | freq = {libnacl.randombytes_uniform(256): 1 for _ in range(65536)} 17 | 18 | self.assertEqual(256, len(freq)) 19 | self.assertTrue(all(freq.values())) 20 | 21 | def test_randombytes(self): 22 | 'copied from libsodium default/randombytes.c' 23 | 24 | data = libnacl.randombytes(65536) 25 | 26 | freq = {x: 1 for x in data} 27 | 28 | self.assertEqual(256, len(freq)) 29 | self.assertTrue(all(freq.values())) 30 | 31 | def test_randombytes_buf_deterministic(self): 32 | 33 | seed = libnacl.randombytes_buf(32) 34 | seed2 = libnacl.randombytes_buf(32) 35 | data = libnacl.randombytes_buf_deterministic(32, seed) 36 | data2 = libnacl.randombytes_buf_deterministic(32, seed) 37 | data3 = libnacl.randombytes_buf_deterministic(32, seed2) 38 | 39 | self.assertEqual(32, len(data)) 40 | self.assertEqual(32, len(data)) 41 | self.assertEqual(32, len(data)) 42 | self.assertEqual(data, data2) 43 | self.assertNotEqual(data, data3) 44 | 45 | def test_crypto_kdf_keygen(self): 46 | 47 | master_key = libnacl.crypto_kdf_keygen() 48 | 49 | freq = {x: 1 for x in master_key} 50 | 51 | self.assertEqual(32, len(master_key)) 52 | self.assertTrue(all(freq.values())) 53 | 54 | def test_crypto_kdf_derive_from_key(self): 55 | 56 | master_key = libnacl.crypto_kdf_keygen() 57 | subkey = libnacl.crypto_kdf_derive_from_key(16, 1, "Examples", master_key) 58 | subkey2 = libnacl.crypto_kdf_derive_from_key(16, 1, "Examples", master_key) 59 | subkey3 = libnacl.crypto_kdf_derive_from_key(16, 2, "Examples", master_key) 60 | 61 | self.assertEqual(16, len(subkey)) 62 | self.assertEqual(16, len(subkey2)) 63 | self.assertEqual(16, len(subkey3)) 64 | self.assertEqual(subkey, subkey2) 65 | self.assertNotEqual(subkey, subkey3) 66 | 67 | def test_crypto_kx_keypair(self): 68 | pk, sk = libnacl.crypto_kx_keypair() 69 | self.assertEqual(32, len(pk)) 70 | self.assertEqual(32, len(sk)) 71 | 72 | def test_crypto_kx_seed_keypair(self): 73 | seed = libnacl.randombytes_buf(32) 74 | seed2 = libnacl.randombytes_buf(32) 75 | pk, sk = libnacl.crypto_kx_seed_keypair(seed) 76 | pk2, sk2 = libnacl.crypto_kx_seed_keypair(seed) 77 | pk3, sk3 = libnacl.crypto_kx_seed_keypair(seed2) 78 | 79 | self.assertEqual(pk, pk2) 80 | self.assertNotEqual(pk, pk3) 81 | self.assertEqual(sk, sk2) 82 | self.assertNotEqual(sk, sk3) 83 | 84 | def test_crypto_kx_client_session_keys(self): 85 | client_pk, client_sk = libnacl.crypto_kx_keypair() 86 | server_pk, server_sk = libnacl.crypto_kx_keypair() 87 | rx, tx, status = libnacl.crypto_kx_client_session_keys(client_pk, client_sk, server_pk) 88 | rx2, tx2, status = libnacl.crypto_kx_client_session_keys(client_pk, client_sk, server_pk) 89 | 90 | self.assertEqual(32, len(rx)) 91 | self.assertEqual(32, len(tx)) 92 | self.assertEqual(rx, rx2) 93 | self.assertEqual(tx, tx2) 94 | 95 | def test_crypto_kx_server_session_keys(self): 96 | client_pk, client_sk = libnacl.crypto_kx_keypair() 97 | server_pk, server_sk = libnacl.crypto_kx_keypair() 98 | rx, tx, status = libnacl.crypto_kx_server_session_keys(client_pk, client_sk, server_pk) 99 | rx2, tx2, status = libnacl.crypto_kx_server_session_keys(client_pk, client_sk, server_pk) 100 | 101 | self.assertEqual(32, len(rx)) 102 | self.assertEqual(32, len(tx)) 103 | self.assertEqual(rx, rx2) 104 | self.assertEqual(tx, tx2) 105 | -------------------------------------------------------------------------------- /tests/unit/test_raw_secret.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl 3 | import libnacl.utils 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | 9 | class TestSecret(unittest.TestCase): 10 | """ 11 | Test secret functions 12 | """ 13 | def test_secretbox(self): 14 | msg = b'Are you suggesting coconuts migrate?' 15 | 16 | nonce = libnacl.utils.rand_nonce() 17 | key = libnacl.utils.salsa_key() 18 | 19 | c = libnacl.crypto_secretbox(msg, nonce, key) 20 | m = libnacl.crypto_secretbox_open(c, nonce, key) 21 | self.assertEqual(msg, m) 22 | 23 | with self.assertRaises(ValueError): 24 | libnacl.crypto_secretbox(msg, b'too_short', key) 25 | 26 | with self.assertRaises(ValueError): 27 | libnacl.crypto_secretbox(msg, nonce, b'too_short') 28 | 29 | with self.assertRaises(ValueError): 30 | libnacl.crypto_secretbox_open(c, b'too_short', key) 31 | 32 | with self.assertRaises(ValueError): 33 | libnacl.crypto_secretbox_open(c, nonce, b'too_short') 34 | -------------------------------------------------------------------------------- /tests/unit/test_raw_secret_easy.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl 3 | import libnacl.utils 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | 9 | class TestSecret(unittest.TestCase): 10 | """ 11 | Test secret functions 12 | """ 13 | def test_secretbox_easy(self): 14 | msg = b'Are you suggesting coconuts migrate?' 15 | 16 | nonce = libnacl.utils.rand_nonce() 17 | key = libnacl.utils.salsa_key() 18 | 19 | c = libnacl.crypto_secretbox_easy(msg, nonce, key) 20 | m = libnacl.crypto_secretbox_open_easy(c, nonce, key) 21 | self.assertEqual(msg, m) 22 | 23 | with self.assertRaises(ValueError): 24 | libnacl.crypto_secretbox_easy(msg, b'too_short', key) 25 | 26 | with self.assertRaises(ValueError): 27 | libnacl.crypto_secretbox_easy(msg, nonce, b'too_short') 28 | 29 | with self.assertRaises(ValueError): 30 | libnacl.crypto_secretbox_open_easy(c, b'too_short', key) 31 | 32 | with self.assertRaises(ValueError): 33 | libnacl.crypto_secretbox_open_easy(c, nonce, b'too_short') 34 | -------------------------------------------------------------------------------- /tests/unit/test_raw_sign.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl 3 | import libnacl.utils 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | 9 | class TestSign(unittest.TestCase): 10 | ''' 11 | Test sign functions 12 | ''' 13 | def test_gen(self): 14 | vk1, sk1 = libnacl.crypto_sign_keypair() 15 | vk2, sk2 = libnacl.crypto_sign_keypair() 16 | vk3, sk3 = libnacl.crypto_sign_keypair() 17 | self.assertEqual(len(vk1), libnacl.crypto_sign_PUBLICKEYBYTES) 18 | self.assertEqual(len(sk1), libnacl.crypto_sign_SECRETKEYBYTES) 19 | self.assertEqual(len(vk2), libnacl.crypto_sign_PUBLICKEYBYTES) 20 | self.assertEqual(len(sk2), libnacl.crypto_sign_SECRETKEYBYTES) 21 | self.assertEqual(len(vk3), libnacl.crypto_sign_PUBLICKEYBYTES) 22 | self.assertEqual(len(sk3), libnacl.crypto_sign_SECRETKEYBYTES) 23 | self.assertNotEqual(vk1, sk1) 24 | self.assertNotEqual(vk2, sk2) 25 | self.assertNotEqual(vk3, sk3) 26 | self.assertNotEqual(vk1, vk2) 27 | self.assertNotEqual(vk1, vk3) 28 | self.assertNotEqual(sk1, sk2) 29 | self.assertNotEqual(sk2, sk3) 30 | 31 | def test_box(self): 32 | msg = b'Are you suggesting coconuts migrate?' 33 | # run 1 34 | vk1, sk1 = libnacl.crypto_sign_keypair() 35 | sig = libnacl.crypto_sign(msg, sk1) 36 | self.assertEqual(msg, sig[libnacl.crypto_sign_BYTES:]) 37 | sig_msg = libnacl.crypto_sign_open(sig, vk1) 38 | self.assertEqual(msg, sig_msg) 39 | -------------------------------------------------------------------------------- /tests/unit/test_save.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Import libnacl libs 3 | import libnacl.dual 4 | import libnacl.secret 5 | import libnacl.sign 6 | import libnacl.utils 7 | 8 | # Import pythonlibs 9 | import os 10 | import stat 11 | import unittest 12 | import tempfile 13 | import sys 14 | 15 | class TestSave(unittest.TestCase): 16 | ''' 17 | ''' 18 | def test_save_load(self): 19 | msg = b'then leap out of the rabbit, taking the French by surprise' 20 | bob = libnacl.dual.DualSecret() 21 | alice = libnacl.dual.DualSecret() 22 | fh_, bob_path = tempfile.mkstemp() 23 | os.close(fh_) 24 | fh_, alice_path = tempfile.mkstemp() 25 | os.close(fh_) 26 | bob.save(bob_path) 27 | alice.save(alice_path) 28 | bob_box = libnacl.public.Box(bob, alice.pk) 29 | alice_box = libnacl.public.Box(alice, bob.pk) 30 | bob_enc = bob_box.encrypt(msg) 31 | alice_enc = alice_box.encrypt(msg) 32 | bob_load = libnacl.utils.load_key(bob_path) 33 | alice_load = libnacl.utils.load_key(alice_path) 34 | bob_load_box = libnacl.public.Box(bob_load, alice_load.pk) 35 | alice_load_box = libnacl.public.Box(alice_load, bob_load.pk) 36 | self.assertEqual(bob.sk, bob_load.sk) 37 | self.assertEqual(bob.pk, bob_load.pk) 38 | self.assertEqual(bob.vk, bob_load.vk) 39 | self.assertEqual(bob.seed, bob_load.seed) 40 | self.assertEqual(alice.sk, alice_load.sk) 41 | self.assertEqual(alice.pk, alice_load.pk) 42 | self.assertEqual(alice.vk, alice_load.vk) 43 | self.assertEqual(alice.seed, alice_load.seed) 44 | bob_dec = alice_load_box.decrypt(bob_enc) 45 | alice_dec = bob_load_box.decrypt(alice_enc) 46 | self.assertEqual(bob_dec, msg) 47 | self.assertEqual(alice_dec, msg) 48 | 49 | bob2 = libnacl.utils.load_key(bob_path) 50 | self.assertEqual(bob.sk, bob2.sk) 51 | self.assertEqual(bob.pk, bob2.pk) 52 | self.assertEqual(bob.vk, bob2.vk) 53 | 54 | os.remove(bob_path) 55 | os.remove(alice_path) 56 | 57 | def test_save_load_secret(self): 58 | msg = b'then leap out of the rabbit, taking the French by surprise' 59 | box = libnacl.secret.SecretBox() 60 | fh_, box_path = tempfile.mkstemp() 61 | os.close(fh_) 62 | box.save(box_path) 63 | lbox = libnacl.utils.load_key(box_path) 64 | ctxt = box.encrypt(msg) 65 | out_msg = lbox.decrypt(ctxt) 66 | self.assertEqual(msg, out_msg) 67 | 68 | def test_save_load_sign(self): 69 | msg = b'then leap out of the rabbit, taking the French by surprise' 70 | signer = libnacl.sign.Signer() 71 | fh_, sign_path = tempfile.mkstemp() 72 | os.close(fh_) 73 | signer.save(sign_path) 74 | signer_load = libnacl.utils.load_key(sign_path) 75 | signed1 = signer.sign(msg) 76 | signed2 = signer_load.sign(msg) 77 | self.assertEqual(signed1, signed2) 78 | os.remove(sign_path) 79 | 80 | def test_save_perms(self): 81 | bob = libnacl.dual.DualSecret() 82 | fh_, bob_path = tempfile.mkstemp() 83 | os.close(fh_) 84 | bob.save(bob_path) 85 | stats = os.stat(bob_path) 86 | expected_perms = 0o100600 if sys.platform != 'win32' else 0o100666 87 | self.assertEqual(stats[stat.ST_MODE], expected_perms) 88 | os.remove(bob_path) 89 | -------------------------------------------------------------------------------- /tests/unit/test_seal.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl.sealed 3 | import libnacl.public 4 | 5 | # Import python libs 6 | import unittest 7 | 8 | class TestSealed(unittest.TestCase): 9 | ''' 10 | ''' 11 | def test_secretkey(self): 12 | ''' 13 | ''' 14 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 15 | key = libnacl.public.SecretKey() 16 | box = libnacl.sealed.SealedBox(key) 17 | ctxt = box.encrypt(msg) 18 | self.assertNotEqual(msg, ctxt) 19 | bclear = box.decrypt(ctxt) 20 | self.assertEqual(msg, bclear) 21 | 22 | def test_publickey_only(self): 23 | ''' 24 | ''' 25 | msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' 26 | key = libnacl.public.SecretKey() 27 | key_public = libnacl.public.PublicKey(key.pk) 28 | 29 | box = libnacl.sealed.SealedBox(key_public) 30 | ctxt = box.encrypt(msg) 31 | self.assertNotEqual(msg, ctxt) 32 | 33 | decrypting_box = libnacl.sealed.SealedBox(key) 34 | bclear = decrypting_box.decrypt(ctxt) 35 | self.assertEqual(msg, bclear) 36 | 37 | -------------------------------------------------------------------------------- /tests/unit/test_secret.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl.secret 3 | # Import python libs 4 | import unittest 5 | 6 | class TestSecret(unittest.TestCase): 7 | ''' 8 | ''' 9 | def test_secret(self): 10 | msg = b'But then of course African swallows are not migratory.' 11 | box = libnacl.secret.SecretBox() 12 | ctxt = box.encrypt(msg) 13 | self.assertNotEqual(msg, ctxt) 14 | box2 = libnacl.secret.SecretBox(box.sk) 15 | clear1 = box.decrypt(ctxt) 16 | self.assertEqual(msg, clear1) 17 | clear2 = box2.decrypt(ctxt) 18 | self.assertEqual(clear1, clear2) 19 | ctxt2 = box2.encrypt(msg) 20 | clear3 = box.decrypt(ctxt2) 21 | self.assertEqual(clear3, msg) 22 | 23 | -------------------------------------------------------------------------------- /tests/unit/test_secret_easy.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl.secret_easy 3 | # Import python libs 4 | import unittest 5 | 6 | class TestSecretEasy(unittest.TestCase): 7 | ''' 8 | ''' 9 | def test_secret(self): 10 | msg = b'But then of course African swallows are not migratory.' 11 | box = libnacl.secret_easy.SecretBoxEasy() 12 | ctxt = box.encrypt(msg) 13 | self.assertNotEqual(msg, ctxt) 14 | box2 = libnacl.secret_easy.SecretBoxEasy(box.sk) 15 | clear1 = box.decrypt(ctxt) 16 | self.assertEqual(msg, clear1) 17 | clear2 = box2.decrypt(ctxt) 18 | self.assertEqual(clear1, clear2) 19 | ctxt2 = box2.encrypt(msg) 20 | clear3 = box.decrypt(ctxt2) 21 | self.assertEqual(clear3, msg) 22 | 23 | -------------------------------------------------------------------------------- /tests/unit/test_sign.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl.sign 3 | 4 | # Import pythonlibs 5 | import unittest 6 | 7 | 8 | class TestSigning(unittest.TestCase): 9 | ''' 10 | ''' 11 | def test_sign(self): 12 | msg = (b'Well, that\'s no ordinary rabbit. That\'s the most foul, ' 13 | b'cruel, and bad-tempered rodent you ever set eyes on.') 14 | signer = libnacl.sign.Signer() 15 | signed = signer.sign(msg) 16 | signature = signer.signature(msg) 17 | self.assertNotEqual(msg, signed) 18 | veri = libnacl.sign.Verifier(signer.hex_vk()) 19 | verified = veri.verify(signed) 20 | verified2 = veri.verify(signature + msg) 21 | self.assertEqual(verified, msg) 22 | self.assertEqual(verified2, msg) 23 | 24 | def test_key_decomposition(self): 25 | prv_key = b'The two halves are understood to' 26 | pub_key = b'be essentially arbitrary values.' 27 | secret_key = prv_key + pub_key 28 | # The following functions should simply decompose a secret key 29 | # without performing real computation. libsodium understands secret 30 | # keys to be (private seed bytes || derived public key bytes). 31 | self.assertEqual(prv_key, libnacl.crypto_sign_ed25519_sk_to_seed(secret_key)) 32 | self.assertEqual(pub_key, libnacl.crypto_sign_ed25519_sk_to_pk(secret_key)) 33 | 34 | def test_key_decomposition_rejects_wrong_key_lengths(self): 35 | """ 36 | Too few bytes in a key passed through to libsodium will lead to bytes past the end 37 | of the string being read. We should be guarding against this dangerous case. 38 | """ 39 | for test_func in (libnacl.crypto_sign_ed25519_sk_to_seed, libnacl.crypto_sign_ed25519_sk_to_pk): 40 | for bad_key in (b'too short', b'too long' * 100): 41 | with self.assertRaises(ValueError) as context: 42 | test_func(bad_key) 43 | self.assertEqual(context.exception.args, ('Invalid secret key',)) 44 | 45 | def test_sign_rejects_wrong_key_lengths(self): 46 | """ 47 | Too few bytes in a key passed through to libsodium will lead to bytes past the end 48 | of the string being read. We should be guarding against this dangerous case. 49 | """ 50 | msg = b'The message does not matter.' 51 | for test_func in (libnacl.crypto_sign, libnacl.crypto_sign_detached): 52 | for bad_key in (b'too short', b'too long' * 100): 53 | with self.assertRaises(ValueError) as context: 54 | test_func(msg, bad_key) 55 | self.assertEqual(context.exception.args, ('Invalid secret key',)) 56 | 57 | def test_open_rejects_wrong_key_lengths(self): 58 | """ 59 | Too few bytes in a key passed through to libsodium will lead to bytes past the end 60 | of the string being read. We should be guarding against this dangerous case. 61 | """ 62 | msg = b'The message does not matter.' 63 | good_key = b'This valid key is 32 bytes long.' 64 | for bad_key in (b'too short', b'too long' * 100): 65 | with self.assertRaises(ValueError) as context: 66 | libnacl.crypto_sign_open(msg, bad_key) 67 | self.assertEqual(context.exception.args, ('Invalid public key',)) 68 | 69 | with self.assertRaises(ValueError) as context: 70 | libnacl.crypto_sign_open(msg, good_key) 71 | self.assertEqual(context.exception.args, ('Failed to validate message',)) 72 | 73 | def test_verify_detached_rejects_wrong_key_lengths(self): 74 | """ 75 | Too few bytes in a key passed through to libsodium will lead to bytes past the end 76 | of the string being read. We should be guarding against this dangerous case. 77 | """ 78 | msg = b'The message does not matter.' 79 | good_signature = b'This is a valid signature; it is 64 bytes long, no more, no less' 80 | good_key = b'This valid key is 32 bytes long.' 81 | for bad_key in (b'too short', b'too long' * 100): 82 | with self.assertRaises(ValueError) as context: 83 | libnacl.crypto_sign_verify_detached(good_signature, msg, bad_key) 84 | self.assertEqual(context.exception.args, ('Invalid public key',)) 85 | 86 | for bad_signature in (b'too short', b'too long' * 100): 87 | with self.assertRaises(ValueError) as context: 88 | libnacl.crypto_sign_verify_detached(bad_signature, msg, good_key) 89 | self.assertEqual(context.exception.args, ('Invalid signature',)) 90 | 91 | with self.assertRaises(ValueError) as context: 92 | libnacl.crypto_sign_verify_detached(good_signature, msg, good_key) 93 | self.assertEqual(context.exception.args, ('Failed to validate message',)) 94 | -------------------------------------------------------------------------------- /tests/unit/test_stream.py: -------------------------------------------------------------------------------- 1 | # Import libnacl libs 2 | import libnacl.sign 3 | 4 | # Import pythonlibs 5 | import unittest 6 | 7 | 8 | class TestStream(unittest.TestCase): 9 | def test_stream_rejects_wrong_lengths(self): 10 | """ 11 | Too few bytes in a key or nonce passed through to libsodium will lead to bytes past the end 12 | of the string being read. We should be guarding against this dangerous case. 13 | """ 14 | msg_len = 100 # whatever 15 | good_nonce= b'Nonces must be 24 bytes.' 16 | good_key = b'This valid key is 32 bytes long.' 17 | for bad_nonce in (b'too short', b'too long' * 100): 18 | with self.assertRaises(ValueError) as context: 19 | libnacl.crypto_stream(msg_len, bad_nonce, good_key) 20 | self.assertEqual(context.exception.args, ('Invalid nonce',)) 21 | 22 | for bad_key in (b'too short', b'too long' * 100): 23 | with self.assertRaises(ValueError) as context: 24 | libnacl.crypto_stream(msg_len, good_nonce, bad_key) 25 | self.assertEqual(context.exception.args, ('Invalid secret key',)) 26 | 27 | def test_stream_xor_rejects_wrong_lengths(self): 28 | """ 29 | Too few bytes in a key or nonce passed through to libsodium will lead to bytes past the end 30 | of the string being read. We should be guarding against this dangerous case. 31 | """ 32 | msg = b'The message does not matter.' 33 | good_nonce = b'Nonces must be 24 bytes.' 34 | good_key = b'This valid key is 32 bytes long.' 35 | for bad_nonce in (b'too short', b'too long' * 100): 36 | with self.assertRaises(ValueError) as context: 37 | libnacl.crypto_stream_xor(msg, bad_nonce, good_key) 38 | self.assertEqual(context.exception.args, ('Invalid nonce',)) 39 | 40 | for bad_key in (b'too short', b'too long' * 100): 41 | with self.assertRaises(ValueError) as context: 42 | libnacl.crypto_stream_xor(msg, good_nonce, bad_key) 43 | self.assertEqual(context.exception.args, ('Invalid secret key',)) 44 | -------------------------------------------------------------------------------- /tests/unit/test_verify.py: -------------------------------------------------------------------------------- 1 | """ 2 | Basic tests for verify functions 3 | """ 4 | 5 | import libnacl 6 | import unittest 7 | 8 | 9 | # These are copied from libsodium test suite 10 | class TestVerify(unittest.TestCase): 11 | def test_verify16(self): 12 | v16 = libnacl.randombytes_buf(16) 13 | v16x = v16[:] 14 | self.assertTrue(libnacl.crypto_verify_16(v16, v16x)) 15 | self.assertTrue(libnacl.bytes_eq(v16, v16x)) 16 | v16x = bytearray(v16x) 17 | i = libnacl.randombytes_random() & 15 18 | v16x[i] = (v16x[i] + 1) % 256 19 | v16x = bytes(v16x) 20 | self.assertFalse(libnacl.crypto_verify_16(v16, v16x)) 21 | self.assertFalse(libnacl.bytes_eq(v16, v16x)) 22 | 23 | self.assertEqual(libnacl.crypto_verify_16_BYTES, 16) 24 | 25 | def test_verify32(self): 26 | v32 = libnacl.randombytes_buf(32) 27 | v32x = v32[:] 28 | self.assertTrue(libnacl.crypto_verify_32(v32, v32x)) 29 | self.assertTrue(libnacl.bytes_eq(v32, v32x)) 30 | v32x = bytearray(v32x) 31 | i = libnacl.randombytes_random() & 31 32 | v32x[i] = (v32x[i] + 1) % 256 33 | v32x = bytes(v32x) 34 | self.assertFalse(libnacl.crypto_verify_32(v32, v32x)) 35 | self.assertFalse(libnacl.bytes_eq(v32, v32x)) 36 | 37 | self.assertEqual(libnacl.crypto_verify_32_BYTES, 32) 38 | 39 | def test_verify64(self): 40 | v64 = libnacl.randombytes_buf(64) 41 | v64x = v64[:] 42 | self.assertTrue(libnacl.crypto_verify_64(v64, v64x)) 43 | self.assertTrue(libnacl.bytes_eq(v64, v64x)) 44 | v64x = bytearray(v64x) 45 | i = libnacl.randombytes_random() & 63 46 | v64x[i] = (v64x[i] + 1) % 256 47 | v64x = bytes(v64x) 48 | self.assertFalse(libnacl.crypto_verify_64(v64, v64x)) 49 | self.assertFalse(libnacl.bytes_eq(v64, v64x)) 50 | 51 | self.assertEqual(libnacl.crypto_verify_64_BYTES, 64) 52 | 53 | 54 | class TestVerifyBytesEq(unittest.TestCase): 55 | def test_equal(self): 56 | a = libnacl.randombytes_buf(122) 57 | b = a[:] 58 | self.assertTrue(libnacl.bytes_eq(a, b)) 59 | 60 | def test_different(self): 61 | a = libnacl.randombytes_buf(122) 62 | b = bytearray(a) 63 | b[87] = (b[87] + 1) % 256 64 | b = bytes(b) 65 | self.assertFalse(libnacl.bytes_eq(a, b)) 66 | 67 | def test_invalid_type(self): 68 | a = libnacl.randombytes_buf(122) 69 | b = bytearray(a) 70 | with self.assertRaises(TypeError): 71 | libnacl.bytes_eq(a, b) 72 | 73 | def test_different_length(self): 74 | a = libnacl.randombytes_buf(122) 75 | b = a[:-1] 76 | self.assertFalse(libnacl.bytes_eq(a, b)) 77 | -------------------------------------------------------------------------------- /tests/unit/test_version.py: -------------------------------------------------------------------------------- 1 | """ 2 | Basic tests for version functions 3 | """ 4 | 5 | import libnacl 6 | import unittest 7 | 8 | 9 | # These are copied from libsodium test suite 10 | class TestSodiumVersion(unittest.TestCase): 11 | def test_version_string(self): 12 | self.assertIsNotNone(libnacl.sodium_version_string()) 13 | 14 | def test_library_version_major(self): 15 | # Using assertTrue to keep tests "uniform" and keep compatibility with 16 | # Python 2.6 17 | self.assertTrue(libnacl.sodium_library_version_major() > 0) 18 | 19 | def test_library_version_minor(self): 20 | # Using assertTrue to keep tests "uniform" and keep compatibility with 21 | # Python 2.6 (assertGreaterEqual appeared in Python 2.7 only) 22 | self.assertTrue(libnacl.sodium_library_version_minor() >= 0) 23 | --------------------------------------------------------------------------------