Skip to content
Snippets Groups Projects
Commit ca6cb150 authored by inso's avatar inso
Browse files

Added a pynacl to lib/ so that we can build our own pynacl during freezing

parent 71bc57fc
No related branches found
No related tags found
No related merge requests found
Showing
with 0 additions and 1282 deletions
File moved
File moved
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PyNaCl.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PyNaCl.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/PyNaCl"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PyNaCl"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
lib/nacl/docs/_static/ed25519.png

91.2 KiB

nacl.hash
=========
.. currentmodule:: nacl.hash
.. function:: sha256(message, encoder)
Hashes ``message`` with SHA256.
:param bytes message: The message to hash.
:param encoder: A class that is able to encode the hashed message.
:return bytes: The hashed message.
.. function:: sha512(message, encoder)
Hashes ``message`` with SHA512.
:param bytes message: The message to hash.
:param encoder: A class that is able to encode the hashed message.
:return bytes: The hashed message.
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing dir
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import sys
try:
import sphinx_rtd_theme
except ImportError:
sphinx_rtd_theme = None
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath("../src"))
import nacl
# -- General configuration ----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = "1.0"
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named "sphinx.ext.*") or your custom ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.doctest",
"sphinx.ext.intersphinx",
"sphinx.ext.viewcode",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = ".rst"
# The encoding of source files.
# source_encoding = "utf-8-sig"
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "PyNaCl"
copyright = "2013, Donald Stufft and Individual Contributors"
# The version info for the project you"re documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = "".join(nacl.__version__.split(".")[:2])
# The full version, including alpha/beta/rc tags.
release = nacl.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ""
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = "%B %d, %Y"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all documents
# default_role = None
# If true, "()" will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
if sphinx_rtd_theme:
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else:
html_theme = "default"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# If not "", a "Last updated on:" timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = "%b %d, %Y"
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ""
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "PyNaCldoc"
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {"http://docs.python.org/": None}
# Enable the new ReadTheDocs theme
RTD_NEW_THEME = True
Encoders
========
.. currentmodule:: nacl.encoding
PyNaCl supports a simple method of encoding and decoding messages in different
formats. Encoders are simple classes with staticmethods that encode/decode and
are typically passed as a keyword argument `encoder` to various methods.
For example you can generate a signing key and encode it in hex with:
.. code-block:: python
hex_key = nacl.signing.SigningKey.generate().encode(encoder=nacl.encoding.HexEncoder)
Then you can later decode it from hex:
.. code-block:: python
signing_key = nacl.signing.SigningKey(hex_key, encoder=nacl.encoding.HexEncoder)
Built in Encoders
-----------------
.. class:: RawEncoder
.. class:: HexEncoder
.. class:: Base16Encoder
.. class:: Base32Encoder
.. class:: Base64Encoder
.. class:: URLSafeBase64Encoder
Defining your own Encoder
-------------------------
Defining your own encoder is easy. Each encoder is simply a class with 2 static
methods. For example here is the hex encoder:
.. code-block:: python
import binascii
class HexEncoder(object):
@staticmethod
def encode(data):
return binascii.hexlify(data)
@staticmethod
def decode(data):
return binascii.unhexlify(data)
Exceptions
==========
.. class:: CryptoError
Base exception for all nacl related errors
.. class:: BadSignatureError
Raised when the signature was forged or otherwise corrupt.
PyNaCl: Python binding to the Networking and Cryptography (NaCl) library
========================================================================
Contents
--------
.. toctree::
:maxdepth: 2
public
secret
signing
Support Features
----------------
.. toctree::
:maxdepth: 2
encoding
exceptions
utils
Api Documentation
-----------------
.. toctree::
:maxdepth: 2
:glob:
api/hash
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
Public Key Encryption
=====================
.. currentmodule:: nacl.public
Imagine Alice wants something valuable shipped to her. Because it's valuable,
she wants to make sure it arrives securely (i.e. hasn't been opened or
tampered with) and that it's not a forgery (i.e. it's actually from the sender
she's expecting it to be from and nobody's pulling the old switcheroo)
One way she can do this is by providing the sender (let's call him Bob) with a
high-security box of her choosing. She provides Bob with this box, and
something else: a padlock, but a padlock without a key. Alice is keeping that
key all to herself. Bob can put items in the box then put the padlock onto it,
but once the padlock snaps shut, the box cannot be opened by anyone who
doesn't have Alice's private key.
Here's the twist though, Bob also puts a padlock onto the box. This padlock
uses a key Bob has published to the world, such that if you have one of Bob's
keys, you know a box came from him because Bob's keys will open Bob's padlocks
(let's imagine a world where padlocks cannot be forged even if you know the
key). Bob then sends the box to Alice.
In order for Alice to open the box, she needs two keys: her private key that
opens her own padlock, and Bob's well-known key. If Bob's key doesn't open the
second padlock then Alice knows that this is not the box she was expecting
from Bob, it's a forgery.
This bidirectional guarantee around identity is known as mutual authentication.
Example
-------
The :class:`~nacl.public.Box` class uses the given public and private (secret)
keys to derive a shared key, which is used with the nonce given to encrypt the
given messages and decrypt the given ciphertexts. The same shared key will
generated from both pairing of keys, so given two keypairs belonging to alice
(pkalice, skalice) and bob(pkbob, skbob), the key derived from (pkalice, skbob)
with equal that from (pkbob, skalice). This is how the system works:
.. code-block:: python
import nacl.utils
from nacl.public import PrivateKey, Box
# generate the private key which must be kept secret
skbob = PrivateKey.generate()
# the public key can be given to anyone wishing to send
# Bob an encrypted message
pkbob = skbob.public_key
# Alice does the same and then
# sends her public key to Bob and Bob his public key to Alice
skalice = PrivateKey.generate()
pkalice = skalice.public_key
# Bob wishes to send Alice an encrypted message
# So Bob must make a Box with his private key and Alice's public key
bob_box = Box(skbob, pkalice)
# This is our message to send, it must be a bytestring as Box will
# treat is as just a binary blob of data.
message = b"Kill all humans"
# This is a nonce, it *MUST* only be used once, but it is not considered
# secret and can be transmitted or stored alongside the ciphertext. A
# good source of nonce is just 24 random bytes.
nonce = nacl.utils.random(Box.NONCE_SIZE)
# Encrypt our message, it will be exactly 40 bytes longer than the original
# message as it stores authentication information and nonce alongside it.
encrypted = bob_box.encrypt(message, nonce)
# Alice creates a second box with her private key to decrypt the message
alice_box = Box(skalice, pkbob)
# Decrypt our message, an exception will be raised if the encryption was
# tampered with or there was otherwise an error.
plaintext = alice_box.decrypt(encrypted)
Reference
---------
.. class:: PublicKey(public_key, encoder)
The public key counterpart to an Curve25519
:class:`~nacl.public.PrivateKey` for encrypting messages.
:param bytes public_key: Encoded Curve25519 public key.
:param encoder: A class that is able to decode the ``public_key``.
.. class:: PrivateKey(private_key, encoder)
Private key for decrypting messages using the Curve25519 algorithm.
.. warning:: This **must** be protected and remain secret. Anyone who
knows the value of your :class:`~nacl.public.PrivateKey` can decrypt
any message encrypted by the corresponding
:class:`~nacl.public.PublicKey`
:param bytes private_key: The private key used to decrypt messages.
:param encoder: A class that is able to decode the ``private_key``.
.. attribute:: public_key
An instance of :class:`~.nacl.public.PublicKey` that corresponds with
the private key.
.. classmethod:: generate()
Generates a random :class:`~nacl.public.PrivateKey` object
:return: An instance of :class:`~nacl.public.PrivateKey`.
.. class:: Box(private_key, public_key)
The Box class boxes and unboxes messages between a pair of keys
The ciphertexts generated by :class:`~nacl.public.Box` include a 16
byte authenticator which is checked as part of the decryption. An invalid
authenticator will cause the decrypt function to raise an exception. The
authenticator is not a signature. Once you've decrypted the message you've
demonstrated the ability to create arbitrary valid message, so messages you
send are repudiable. For non-repudiable messages, sign them after
encryption.
:param private_key: An instance of :class:`~nacl.public.PrivateKey` used
to encrypt and decrypt messages
:param public_key: An instance of :class:`~nacl.public.PublicKey` used to
encrypt and decrypt messages
.. classmethod:: decode(encoded, encoder)
Decodes a serialized :class:`~nacl.public.Box`.
:return: An instance of :class:`~nacl.public.Box`.
.. method:: encrypt(plaintext, nonce, encoder)
Encrypts the plaintext message using the given `nonce` and returns
the ciphertext encoded with the encoder.
.. warning:: It is **VITALLY** important that the nonce is a nonce,
i.e. it is a number used only once for any given key. If you
fail to do this, you compromise the privacy of the messages
encrypted.
:param bytes plaintext: The plaintext message to encrypt.
:param bytes nonce: The nonce to use in the encryption.
:param encoder: A class that is able to decode the ciphertext.
:return: An instance of :class:`~nacl.utils.EncryptedMessage`.
.. method:: decrypt(ciphertext, nonce, encoder)
Decrypts the ciphertext using the given nonce and returns the
plaintext message.
:param bytes ciphertext: The encrypted message to decrypt.
:param bytes nonce: The nonce to use in the decryption.
:param encoder: A class that is able to decode the plaintext.
:return bytes: The decrypted plaintext.
Secret Key Encryption
=====================
.. currentmodule:: nacl.secret
Secret key encryption (also called symmetric key encryption) is analogous to a
safe. You can store something secret through it and anyone who has the key can
open it and view the contents. :class:`~nacl.secret.SecretBox` functions as
just such a safe, and like any good safe any attempts to tamper with the
contents is easily detected.
Secret Key Encryption allows you to store or transmit data over insecure
channels without leaking the contents of that message, nor anything about it
other than the length.
Example
-------
.. code-block:: python
import nacl.secret
import nacl.utils
# This must be kept secret, this is the combination to your safe
key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
# This is your safe, you can use it to encrypt or decrypt messages
box = nacl.secret.SecretBox(key)
# This is our message to send, it must be a bytestring as SecretBox will
# treat is as just a binary blob of data.
message = b"The president will be exiting through the lower levels"
# This is a nonce, it *MUST* only be used once, but it is not considered
# secret and can be transmitted or stored alongside the ciphertext. A
# good source of nonce is just 24 random bytes.
nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)
# Encrypt our message, it will be exactly 40 bytes longer than the original
# message as it stores authentication information and nonce alongside it.
encrypted = box.encrypt(message, nonce)
# Decrypt our message, an exception will be raised if the encryption was
# tampered with or there was otherwise an error.
plaintext = box.decrypt(encrypted)
Requirements
------------
Key
~~~
The 32 bytes key given to :class:`~nacl.secret.SecretBox` must be kept secret.
It is the combination to your "safe" and anyone with this key will be able to
decrypt the data, or encrypt new data.
Nonce
~~~~~
The 24-byte nonce (`Number used once <https://en.wikipedia.org/wiki/Cryptographic_nonce>`_)
given to :meth:`~nacl.secret.SecretBox.encrypt` and
:meth:`~nacl.secret.SecretBox.decrypt` must **NEVER** be reused for a
particular key. Reusing a nonce may give an attacker enough information to
decrypt or forge other messages. A nonce is not considered secret and may be
freely transmitted or stored in plaintext alongside the ciphertext.
A nonce does not need to be random or unpredictable, nor does the method of
generating them need to be secret. A nonce could simply be a counter
incremented with each message encrypted, which can be useful in
connection-oriented protocols to reject duplicate messages ("replay
attacks"). A bidirectional connection could use the same key for both
directions, as long as their nonces never overlap (e.g. one direction always
sets the high bit to "1", the other always sets it to "0").
If you use a counter-based nonce along with a key that is persisted from one
session to another (e.g. saved to disk), you must store the counter along
with the key, to avoid accidental nonce reuse on the next session. For this
reason, many protocols derive a new key for each session, reset the counter
to zero with each new key, and never store the derived key or the counter.
You can safely generate random nonces by calling
:class:``~nacl.utils.random(SecretBox.NONCE_SIZE)``.
Reference
---------
.. class:: SecretBox(key, encoder)
The SecretBox class encrypts and decrypts messages using the given secret
key.
The ciphertexts generated by :class:`~nacl.secret.Secretbox` include a 16
byte authenticator which is checked as part of the decryption. An invalid
authenticator will cause the decrypt function to raise an exception. The
authenticator is not a signature. Once you've decrypted the message you've
demonstrated the ability to create arbitrary valid message, so messages you
send are repudiable. For non-repudiable messages, sign them after
encryption.
:param bytes key: The secret key used to encrypt and decrypt messages.
:param encoder: A class that is able to decode the ``key``.
.. method:: encrypt(plaintext, nonce, encoder)
Encrypts the plaintext message using the given nonce and returns the
ciphertext encoded with the encoder.
.. warning:: It is **VITALLY** important that the nonce is a nonce,
i.e. it is a number used only once for any given key. If you fail
to do this, you compromise the privacy of the messages encrypted.
Give your nonces a different prefix, or have one side use an odd
counter and one an even counter. Just make sure they are different.
:param bytes plaintext: The plaintext message to encrypt.
:param bytes nonce: The nonce to use in the encryption.
:param encoder: A class that is able to decode the ciphertext.
:return: An instance of :class:`~nacl.utils.EncryptedMessage`.
.. method:: decrypt(ciphertext, nonce, encoder)
Decrypts the ciphertext using the given nonce and returns the plaintext
message.
:param bytes ciphertext: The encrypted message to decrypt.
:param bytes nonce: The nonce to use in the decryption.
:param encoder: A class that is able to decode the plaintext.
:return bytes: The decrypted plaintext.
Algorithm details
-----------------
:Encryption: `Salsa20 steam cipher <https://en.wikipedia.org/wiki/Salsa20>`_
:Authentication: `Poly1305 MAC <https://en.wikipedia.org/wiki/Poly1305-AES>`_
Digital Signatures
==================
.. currentmodule:: nacl.signing
You can use a digital signature for many of the same reasons that you might
sign a paper document. A valid digital signature gives a recipient reason to
believe that the message was created by a known sender such that they cannot
deny sending it (authentication and non-repudiation) and that the message was
not altered in transit (integrity).
Digital signatures allow you to publish a public key, and then you can use your
private signing key to sign messages. Others who have your public key can then
use it to validate that your messages are actually authentic.
Example
-------
Signer's perspective (:class:`~nacl.signing.SigningKey`)
.. code-block:: python
import nacl.encoding
import nacl.signing
# Generate a new random signing key
signing_key = nacl.signing.SigningKey.generate()
# Sign a message with the signing key
signed = signing_key.sign(b"Attack at Dawn")
# Obtain the verify key for a given signing key
verify_key = signing_key.verify_key
# Serialize the verify key to send it to a third party
verify_key_hex = verify_key.encode(encoder=nacl.encoding.HexEncoder)
Verifier's perspective (:class:`~nacl.signing.VerifyKey`)
.. code-block:: python
import nacl.signing
# Create a VerifyKey object from a hex serialized public key
verify_key = nacl.signing.VerifyKey(verify_key_hex, encoder=nacl.encoding.HexEncoder)
# Check the validity of a message's signature
# Will raise nacl.signing.BadSignatureError if the signature check fails
verify_key.verify(signed)
Reference
---------
.. class:: SigningKey(seed, encoder)
Private key for producing digital signatures using the Ed25519 algorithm.
Signing keys are produced from a 32-byte (256-bit) random seed value. This
value can be passed into the :class:`~nacl.signing.SigningKey` as a
:func:`bytes` whose length is 32.
.. warning:: This **must** be protected and remain secret. Anyone who knows
the value of your :class:`~nacl.signing.SigningKey` or it's seed can
masquerade as you.
:param bytes seed: Random 32-byte value (i.e. private key).
:param encoder: A class that is able to decode the ``seed``.
.. attribute:: verify_key
An instance of :class:`~.nacl.signing.VerifyKey` (i.e. public key)
that corresponds with the signing key.
.. classmethod:: generate()
Generates a random :class:`~nacl.signing.SigningKey` object
:return: An instance of :class:`~nacl.signing.SigningKey`.
.. method:: sign(message, encoder)
Sign a message using this key.
:param bytes message: The data to be signed.
:param encoder: A class that is able to decode the signed message.
:return: An instance of :class:`~nacl.signing.SignedMessage`.
.. class:: VerifyKey(key, encoder)
The public key counterpart to an Ed25519 :class:`~nacl.signing.SigningKey`
for producing digital signatures.
:param bytes key: A serialized Ed25519 public key.
:param encoder: A class that is able to decode the ``key``.
.. method:: verify(smessage, signature, encoder)
Verifies the signature of a signed message.
:param bytes smessage: The signed message to verify. This is either
the original message or the concated signature and message.
:param bytes signature: The signature of the message to verify against.
If the value of ``smessage`` is the concated signature and message,
this parameter can be ``None``.
:param encoder: A class that is able to decode the secret message and
signature.
:return bytes: The message if successfully verified.
:raises nacl.exceptions.BadSignatureError: This is raised if the
signature is invalid.
.. class:: SignedMessage()
A bytes subclass that holds a messaged that has been signed by a
:class:`SigningKey`.
.. attribute:: signature
The signature contained within the
:class:`~nacl.signing.SignedMessage`.
.. attribute:: message
The message contained within the :class:`~nacl.signing.SignedMessage`.
Ed25519
-------
Ed25519 is a public-key signature system with several attractive features:
* **Fast single-signature verification:** Ed25519 takes only 273364 cycles
to verify a signature on Intel's widely deployed Nehalem/Westmere lines of
CPUs. (This performance measurement is for short messages; for very long
messages, verification time is dominated by hashing time.) Nehalem and
Westmere include all Core i7, i5, and i3 CPUs released between 2008 and
2010, and most Xeon CPUs released in the same period.
* **Even faster batch verification:** Ed25519 performs a batch of 64
separate signature verifications (verifying 64 signatures of 64 messages
under 64 public keys) in only 8.55 million cycles, i.e., under 134000
cycles per signature. Ed25519 fits easily into L1 cache, so contention
between cores is negligible: a quad-core 2.4GHz Westmere verifies 71000
signatures per second, while keeping the maximum verification latency
below 4 milliseconds.
* **Very fast signing:** Ed25519 takes only 87548 cycles to sign a
message. A quad-core 2.4GHz Westmere signs 109000 messages per second.
* **Fast key generation:** Key generation is almost as fast as signing. There
is a slight penalty for key generation to obtain a secure random number
from the operating system; /dev/urandom under Linux costs about 6000
cycles.
* **High security level:** This system has a 2^128 security target; breaking it
has similar difficulty to breaking NIST P-256, RSA with ~3000-bit keys,
strong 128-bit block ciphers, etc. The best attacks known actually cost
more than 2^140 bit operations on average, and degrade quadratically in
success probability as the number of bit operations drops.
* **Collision resilience:** Hash-function collisions do not break this system.
This adds a layer of defense against the possibility of weakness in the
selected hash function.
* **No secret array indices:** Ed25519 never reads or writes data from secret
addresses in RAM; the pattern of addresses is completely predictable.
Ed25519 is therefore immune to cache-timing attacks, hyperthreading
attacks, and other side-channel attacks that rely on leakage of addresses
through the CPU cache.
* **No secret branch conditions:** Ed25519 never performs conditional branches
based on secret data; the pattern of jumps is completely predictable.
Ed25519 is therefore immune to side-channel attacks that rely on leakage of
information through the branch-prediction unit.
* **Small signatures:** Ed25519 signatures are only 512-bits (64 bytes), one
of the smallest signature sizes available.
* **Small keys:** Ed25519 keys are only 256-bits (32 bytes), making them small
enough to easily copy and paste. Ed25519 also allows the public key to be
derived from the private key, meaning that it doesn't need to be included
in a serialized private key in cases you want both.
* **Deterministic:** Unlike (EC)DSA, Ed25519 does not rely on an entropy
source when signing messages (which has lead to `catastrophic private key <http://www.mydigitallife.info/fail0verflow-hack-permanent-sony-ps3-crack-to-code-sign-homebrew-games-and-apps/>`_
compromises), but instead computes signature nonces from a combination of
a hash of the signing key's "seed" and the message to be signed. This
avoids using an entropy source for nonces, which can be a potential attack
vector if the entropy source is not generating good random numbers. Even a
single reused nonce can lead to a complete disclosure of the private key in
these schemes, which Ed25519 avoids entirely by being deterministic instead
of tied to an entropy source.
The numbers 87548 and 273364 shown above are official
`eBATS <http://bench.cr.yp.to/>` reports for a Westmere CPU (Intel Xeon E5620,
hydra2).
Ed25519 signatures are elliptic-curve signatures, carefully engineered at
several levels of design and implementation to achieve very high speeds without
compromising security.
Algorithm
~~~~~~~~~
* **Public Keys:** `Curve25519 high-speed elliptic curve cryptography <http://cr.yp.to/ecdh.html>`_
* **Signatures:** `Ed25519 digital signature system <http://cr.yp.to/ecdh.html>`_
.. image:: _static/ed25519.png
:k: Ed25519 private key (passed into :class:`~nacl.signing.SigningKey`)
:A: Ed25519 public key derived from k
:M: message to be signed
:R: a deterministic nonce value calculated from a combination of private key
data RH and the message M
:S: Ed25519 signature
Utility Classes
===============
.. class:: EncryptedMessage
A ``bytes`` subclass that holds a message that has been encrypted by a
:class:`~nacl.secret.SecretBox` or :class:`~nacl.public.Box`. The full
content of the ``bytes`` object is the combined ``nonce`` and
``ciphertext``.
.. attribute:: nonce
The nonce used during the encryption of the :class:`EncryptedMessage`.
.. attribute:: ciphertext
The ciphertext contained within the :class:`EncryptedMessage`.
File moved
File moved
File moved
File moved
File moved
#!/usr/bin/env python
# Copyright 2013 Donald Stufft and individual contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
import functools
import glob
import os
import os.path
import subprocess
import sys
from distutils.command.build import build
from distutils.command.build_clib import build_clib as _build_clib
from distutils.command.build_ext import build_ext as _build_ext
from setuptools import Distribution, setup
from setuptools.command.install import install
SODIUM_MAJOR = 4
SODIUM_MINOR = 5
CFFI_DEPENDENCY = "cffi>=0.8"
def here(*paths):
return os.path.abspath(os.path.join(os.path.dirname(__file__), *paths))
sodium = functools.partial(here, "src/libsodium/src/libsodium")
sys.path.insert(0, here("src"))
import nacl
def which(name, flags=os.X_OK): # Taken from twisted
result = []
exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep))
path = os.environ.get('PATH', None)
if path is None:
return []
for p in os.environ.get('PATH', '').split(os.pathsep):
p = os.path.join(p, name)
if os.access(p, flags):
result.append(p)
for e in exts:
pext = p + e
if os.access(pext, flags):
result.append(pext)
return result
def get_ext_modules():
import nacl._lib
return [nacl._lib.ffi.verifier.get_extension()]
class CFFIBuild(build):
"""
This class exists, instead of just providing ``ext_modules=[...]`` directly
in ``setup()`` because importing cryptography requires we have several
packages installed first.
By doing the imports here we ensure that packages listed in
``setup_requires`` are already installed.
"""
def finalize_options(self):
self.distribution.ext_modules = get_ext_modules()
build.finalize_options(self)
class CFFIInstall(install):
"""
As a consequence of CFFIBuild and it's late addition of ext_modules, we
need the equivalent for the ``install`` command to install into platlib
install-dir rather than purelib.
"""
def finalize_options(self):
self.distribution.ext_modules = get_ext_modules()
install.finalize_options(self)
def use_system():
install_type = os.environ.get("SODIUM_INSTALL")
if install_type == "system":
# If we are forcing system installs, don't compile the bundled one
return True
elif install_type == "bundled":
# If we are forcing bundled installs, compile it
return False
# Detect if we have libsodium available
import cffi
ffi = cffi.FFI()
ffi.cdef("""
int sodium_library_version_major();
int sodium_library_version_minor();
""")
try:
system = ffi.dlopen("libsodium")
except OSError:
# We couldn't locate libsodium so we'll use the bundled one
return False
if system.sodium_library_version_major() != SODIUM_MAJOR:
return False
if system.sodium_library_version_minor() < SODIUM_MINOR:
return False
# If we got this far then the system library should be good enough
return True
class Distribution(Distribution):
def has_c_libraries(self):
return not use_system()
class build_clib(_build_clib):
def get_source_files(self):
files = glob.glob(here("src/libsodium/*"))
files += glob.glob(here("src/libsodium/*/*"))
files += glob.glob(here("src/libsodium/*/*/*"))
files += glob.glob(here("src/libsodium/*/*/*/*"))
files += glob.glob(here("src/libsodium/*/*/*/*/*"))
files += glob.glob(here("src/libsodium/*/*/*/*/*/*"))
return files
def build_libraries(self, libraries):
raise Exception("build_libraries")
def check_library_list(self, libraries):
raise Exception("check_library_list")
def get_library_names(self):
return ["sodium"]
def run(self):
if use_system():
return
build_temp = os.path.abspath(self.build_temp)
# Ensure our temporary build directory exists
try:
os.makedirs(build_temp)
except IOError:
pass
# Ensure all of our executanle files have their permission set
for filename in [
"src/libsodium/autogen.sh",
"src/libsodium/compile",
"src/libsodium/config.guess",
"src/libsodium/config.sub",
"src/libsodium/configure",
"src/libsodium/depcomp",
"src/libsodium/install-sh",
"src/libsodium/missing",
"src/libsodium/msvc-scripts/process.bat",
"src/libsodium/test/default/wintest.bat",
"src/libsodium/test-driver"]:
os.chmod(here(filename), 0o755)
# Locate our configure script
configure = here("src/libsodium/configure")
# Run ./configure
subprocess.check_call(
[
configure, "--disable-shared", "--enable-static",
"--disable-debug", "--disable-dependency-tracking",
"--with-pic", "--prefix", os.path.abspath(self.build_clib),
],
cwd=build_temp,
)
# Build the library
subprocess.check_call(["make"], cwd=build_temp)
# Check the build library
subprocess.check_call(["make", "check"], cwd=build_temp)
# Install the built library
subprocess.check_call(["make", "install"], cwd=build_temp)
class build_ext(_build_ext):
def run(self):
if self.distribution.has_c_libraries():
build_clib = self.get_finalized_command("build_clib")
self.include_dirs.append(
os.path.join(build_clib.build_clib, "include"),
)
self.library_dirs.append(
os.path.join(build_clib.build_clib, "lib"),
)
return _build_ext.run(self)
setup(
name=nacl.__title__,
version=nacl.__version__,
description=nacl.__summary__,
long_description=open("README.rst").read(),
url=nacl.__uri__,
license=nacl.__license__,
author=nacl.__author__,
author_email=nacl.__email__,
setup_requires=[
CFFI_DEPENDENCY
],
install_requires=[
CFFI_DEPENDENCY,
"six",
],
extras_require={
"tests": ["pytest"],
},
tests_require=["pytest"],
package_dir={"": "src"},
packages=[
"nacl",
"nacl._lib",
"nacl.c",
],
package_data={"nacl._lib": ["*.h"]},
ext_package="nacl._lib",
cmdclass={
"build": CFFIBuild,
"install": CFFIInstall,
"build_clib": build_clib,
"build_ext": build_ext,
},
distclass=Distribution,
zip_safe=False,
classifiers=[
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
]
)
File moved
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment