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

Working cxfreeze version on windows

Wont run because we have to port Pynacl code to libnacl
parent 61d2ac48
No related branches found
No related tags found
No related merge requests found
Showing
with 0 additions and 1063 deletions
# 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
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "PyNaCl"
__summary__ = ("Python binding to the Networking and Cryptography (NaCl) "
"library")
__uri__ = "https://github.com/pyca/pynacl/"
__version__ = "0.3.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License 2.0"
__copyright__ = "Copyright 2013 Donald Stufft and individual contributors"
# 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 glob
import os.path
from cffi import FFI
from cffi.verifier import Verifier
__all__ = ["ffi"]
HEADERS = glob.glob(
os.path.join(os.path.abspath(os.path.dirname(__file__)), "*.h")
)
# Build our FFI instance
ffi = FFI()
# Add all of our header files, but sort first for consistency of the
# hash that CFFI generates and uses in the .so filename (the order of
# glob() results cannot be relied on)
for header in sorted(HEADERS):
with open(header, "r") as hfile:
ffi.cdef(hfile.read())
# TODO: Can we use the ABI of libsodium for this instead?
ffi.verifier = Verifier(
ffi,
"#include <sodium.h>",
# We need to link to the sodium library
libraries=["sodium"],
# Our ext_package is nacl so look for it
ext_package="nacl._lib",
)
class Library(object):
def __init__(self, ffi):
self.ffi = ffi
self._lib = None
# This prevents the compile_module() from being called, the module
# should have been compiled by setup.py
def _compile_module(*args, **kwargs):
raise RuntimeError("Cannot compile module during runtime")
self.ffi.verifier.compile_module = _compile_module
def __getattr__(self, name):
if self._lib is None:
self._lib = self.ffi.verifier.load_library()
# redirect attribute access to the underlying lib
return getattr(self._lib, name)
lib = Library(ffi)
/* 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.
*/
size_t crypto_box_secretkeybytes();
size_t crypto_box_publickeybytes();
size_t crypto_box_zerobytes();
size_t crypto_box_boxzerobytes();
size_t crypto_box_noncebytes();
size_t crypto_box_beforenmbytes();
int crypto_box_keypair(unsigned char *pk, unsigned char *sk);
int crypto_box(unsigned char *c, const unsigned char *m,
unsigned long long mlen, const unsigned char *n,
const unsigned char *pk, const unsigned char *sk);
int crypto_box_open(unsigned char *m, const unsigned char *c,
unsigned long long clen, const unsigned char *n,
const unsigned char *pk, const unsigned char *sk);
int crypto_box_beforenm(unsigned char *k, const unsigned char *pk,
const unsigned char *sk);
int crypto_box_afternm(unsigned char *c, const unsigned char *m,
unsigned long long mlen, const unsigned char *n,
const unsigned char *k);
int crypto_box_open_afternm(unsigned char *m, const unsigned char *c,
unsigned long long clen, const unsigned char *n,
const unsigned char *k);
/* 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.
*/
// size_t crypto_hash_bytes();
size_t crypto_hash_sha256_bytes();
size_t crypto_hash_sha512_bytes();
int crypto_hash(unsigned char *out, const unsigned char *in,
unsigned long long inlen);
int crypto_hash_sha256(unsigned char *out, const unsigned char *in,
unsigned long long inlen);
int crypto_hash_sha512(unsigned char *out, const unsigned char *in,
unsigned long long inlen);
/* 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.
*/
size_t crypto_scalarmult_bytes();
size_t crypto_scalarmult_scalarbytes();
int crypto_scalarmult_base(unsigned char *q, const unsigned char *n);
int crypto_scalarmult(unsigned char *q, const unsigned char *n, const unsigned char *p);
/* 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.
*/
size_t crypto_secretbox_keybytes();
size_t crypto_secretbox_noncebytes();
size_t crypto_secretbox_zerobytes();
size_t crypto_secretbox_boxzerobytes();
int crypto_secretbox(unsigned char *c, const unsigned char *m,
unsigned long long mlen, const unsigned char *n,
const unsigned char *k);
int crypto_secretbox_open(unsigned char *m, const unsigned char *c,
unsigned long long clen, const unsigned char *n,
const unsigned char *k);
/* 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.
*/
size_t crypto_sign_bytes();
// size_t crypto_sign_seedbytes();
size_t crypto_sign_publickeybytes();
size_t crypto_sign_secretkeybytes();
int crypto_sign_keypair(unsigned char *pk, unsigned char *sk);
int crypto_sign_seed_keypair(unsigned char *pk, unsigned char *sk,
const unsigned char *seed);
int crypto_sign(unsigned char *sm, unsigned long long *smlen,
const unsigned char *m, unsigned long long mlen,
const unsigned char *sk);
int crypto_sign_open(unsigned char *m, unsigned long long *mlen,
const unsigned char *sm, unsigned long long smlen,
const unsigned char *pk);
/* 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.
*/
void randombytes(unsigned char * const buf, const unsigned long long buf_len);
/* 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.
*/
int sodium_init();
# 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
from nacl.c.crypto_box import (
crypto_box, crypto_box_BEFORENMBYTES, crypto_box_BOXZEROBYTES,
crypto_box_NONCEBYTES, crypto_box_PUBLICKEYBYTES,
crypto_box_SECRETKEYBYTES, crypto_box_ZEROBYTES, crypto_box_afternm,
crypto_box_beforenm, crypto_box_keypair, crypto_box_open,
crypto_box_open_afternm,
)
from nacl.c.crypto_hash import (
crypto_hash, crypto_hash_BYTES, crypto_hash_sha256,
crypto_hash_sha256_BYTES, crypto_hash_sha512, crypto_hash_sha512_BYTES,
)
from nacl.c.crypto_scalarmult import (
crypto_scalarmult, crypto_scalarmult_BYTES, crypto_scalarmult_SCALARBYTES,
crypto_scalarmult_base
)
from nacl.c.crypto_secretbox import (
crypto_secretbox, crypto_secretbox_BOXZEROBYTES, crypto_secretbox_KEYBYTES,
crypto_secretbox_NONCEBYTES, crypto_secretbox_ZEROBYTES,
crypto_secretbox_open
)
from nacl.c.crypto_sign import (
crypto_sign, crypto_sign_BYTES, crypto_sign_PUBLICKEYBYTES,
crypto_sign_SECRETKEYBYTES, crypto_sign_SEEDBYTES, crypto_sign_keypair,
crypto_sign_open, crypto_sign_seed_keypair,
)
from nacl.c.randombytes import randombytes
from nacl.c.sodium_core import sodium_init
__all__ = [
"crypto_box_SECRETKEYBYTES",
"crypto_box_PUBLICKEYBYTES",
"crypto_box_NONCEBYTES",
"crypto_box_ZEROBYTES",
"crypto_box_BOXZEROBYTES",
"crypto_box_BEFORENMBYTES",
"crypto_box_keypair",
"crypto_box",
"crypto_box_open",
"crypto_box_beforenm",
"crypto_box_afternm",
"crypto_box_open_afternm",
"crypto_hash_BYTES",
"crypto_hash_sha256_BYTES",
"crypto_hash_sha512_BYTES",
"crypto_hash",
"crypto_hash_sha256",
"crypto_hash_sha512",
"crypto_scalarmult_BYTES",
"crypto_scalarmult_SCALARBYTES",
"crypto_scalarmult",
"crypto_scalarmult_base",
"crypto_secretbox_KEYBYTES",
"crypto_secretbox_NONCEBYTES",
"crypto_secretbox_ZEROBYTES",
"crypto_secretbox_BOXZEROBYTES",
"crypto_secretbox",
"crypto_secretbox_open",
"crypto_sign_BYTES",
"crypto_sign_SEEDBYTES",
"crypto_sign_PUBLICKEYBYTES",
"crypto_sign_SECRETKEYBYTES",
"crypto_sign_keypair",
"crypto_sign_seed_keypair",
"crypto_sign",
"crypto_sign_open",
"randombytes",
"sodium_init",
]
# Initialize Sodium
sodium_init()
# 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
from nacl._lib import lib
from nacl.exceptions import CryptoError
__all__ = ["crypto_box_keypair", "crypto_box"]
crypto_box_SECRETKEYBYTES = lib.crypto_box_secretkeybytes()
crypto_box_PUBLICKEYBYTES = lib.crypto_box_publickeybytes()
crypto_box_NONCEBYTES = lib.crypto_box_noncebytes()
crypto_box_ZEROBYTES = lib.crypto_box_zerobytes()
crypto_box_BOXZEROBYTES = lib.crypto_box_boxzerobytes()
crypto_box_BEFORENMBYTES = lib.crypto_box_beforenmbytes()
def crypto_box_keypair():
"""
Returns a randomly generated public and secret key.
:rtype: (bytes(public_key), bytes(secret_key))
"""
pk = lib.ffi.new("unsigned char[]", crypto_box_PUBLICKEYBYTES)
sk = lib.ffi.new("unsigned char[]", crypto_box_SECRETKEYBYTES)
if lib.crypto_box_keypair(pk, sk) != 0:
raise CryptoError("An error occurred trying to generate the keypair")
return (
lib.ffi.buffer(pk, crypto_box_PUBLICKEYBYTES)[:],
lib.ffi.buffer(sk, crypto_box_SECRETKEYBYTES)[:],
)
def crypto_box(message, nonce, pk, sk):
"""
Encrypts and returns a message ``message`` using the secret key ``sk``,
public key ``pk``, and the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES:
raise ValueError("Invalid nonce size")
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise ValueError("Invalid secret key")
padded = (b"\x00" * crypto_box_ZEROBYTES) + message
ciphertext = lib.ffi.new("unsigned char[]", len(padded))
if lib.crypto_box(ciphertext, padded, len(padded), nonce, pk, sk) != 0:
raise CryptoError("An error occurred trying to encrypt the message")
return lib.ffi.buffer(ciphertext, len(padded))[crypto_box_BOXZEROBYTES:]
def crypto_box_open(ciphertext, nonce, pk, sk):
"""
Decrypts and returns an encrypted message ``ciphertext``, using the secret
key ``sk``, public key ``pk``, and the nonce ``nonce``.
:param ciphertext: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES:
raise ValueError("Invalid nonce size")
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise ValueError("Invalid secret key")
padded = (b"\x00" * crypto_box_BOXZEROBYTES) + ciphertext
plaintext = lib.ffi.new("unsigned char[]", len(padded))
if lib.crypto_box_open(plaintext, padded, len(padded), nonce, pk, sk) != 0:
raise CryptoError("An error occurred trying to decrypt the message")
return lib.ffi.buffer(plaintext, len(padded))[crypto_box_ZEROBYTES:]
def crypto_box_beforenm(pk, sk):
"""
Computes and returns the shared key for the public key ``pk`` and the
secret key ``sk``. This can be used to speed up operations where the same
set of keys is going to be used multiple times.
:param pk: bytes
:param sk: bytes
:rtype: bytes
"""
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise ValueError("Invalid secret key")
k = lib.ffi.new("unsigned char[]", crypto_box_BEFORENMBYTES)
if lib.crypto_box_beforenm(k, pk, sk) != 0:
raise CryptoError("An error occurred computing the shared key.")
return lib.ffi.buffer(k, crypto_box_BEFORENMBYTES)[:]
def crypto_box_afternm(message, nonce, k):
"""
Encrypts and returns the message ``message`` using the shared key ``k`` and
the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param k: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES:
raise ValueError("Invalid nonce")
if len(k) != crypto_box_BEFORENMBYTES:
raise ValueError("Invalid shared key")
padded = b"\x00" * crypto_box_ZEROBYTES + message
ciphertext = lib.ffi.new("unsigned char[]", len(padded))
if lib.crypto_box_afternm(ciphertext, padded, len(padded), nonce, k) != 0:
raise CryptoError("An error occurred trying to encrypt the message")
return lib.ffi.buffer(ciphertext, len(padded))[crypto_box_BOXZEROBYTES:]
def crypto_box_open_afternm(ciphertext, nonce, k):
"""
Decrypts and returns the encrypted message ``ciphertext``, using the shared
key ``k`` and the nonce ``nonce``.
:param ciphertext: bytes
:param nonce: bytes
:param k: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES:
raise ValueError("Invalid nonce")
if len(k) != crypto_box_BEFORENMBYTES:
raise ValueError("Invalid shared key")
padded = (b"\x00" * crypto_box_BOXZEROBYTES) + ciphertext
plaintext = lib.ffi.new("unsigned char[]", len(padded))
if lib.crypto_box_open_afternm(
plaintext, padded, len(padded), nonce, k) != 0:
raise CryptoError("An error occurred trying to decrypt the message")
return lib.ffi.buffer(plaintext, len(padded))[crypto_box_ZEROBYTES:]
# 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
from nacl._lib import lib
from nacl.exceptions import CryptoError
# crypto_hash_BYTES = lib.crypto_hash_bytes()
crypto_hash_BYTES = lib.crypto_hash_sha512_bytes()
crypto_hash_sha256_BYTES = lib.crypto_hash_sha256_bytes()
crypto_hash_sha512_BYTES = lib.crypto_hash_sha512_bytes()
def crypto_hash(message):
"""
Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes
"""
digest = lib.ffi.new("unsigned char[]", crypto_hash_BYTES)
if lib.crypto_hash(digest, message, len(message)) != 0:
raise CryptoError("Hashing failed")
return lib.ffi.buffer(digest, crypto_hash_BYTES)[:]
def crypto_hash_sha256(message):
"""
Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes
"""
digest = lib.ffi.new("unsigned char[]", crypto_hash_sha256_BYTES)
if lib.crypto_hash_sha256(digest, message, len(message)) != 0:
raise CryptoError("Hashing failed")
return lib.ffi.buffer(digest, crypto_hash_sha256_BYTES)[:]
def crypto_hash_sha512(message):
"""
Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes
"""
digest = lib.ffi.new("unsigned char[]", crypto_hash_sha512_BYTES)
if lib.crypto_hash_sha512(digest, message, len(message)) != 0:
raise CryptoError("Hashing failed")
return lib.ffi.buffer(digest, crypto_hash_sha512_BYTES)[:]
# 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
from nacl._lib import lib
crypto_scalarmult_BYTES = lib.crypto_scalarmult_bytes()
crypto_scalarmult_SCALARBYTES = lib.crypto_scalarmult_scalarbytes()
def crypto_scalarmult_base(n):
"""
Computes and returns the scalar product of a standard group element and an
integer ``n``.
:param n: bytes
:rtype: bytes
"""
q = lib.ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
rc = lib.crypto_scalarmult_base(q, n)
assert rc == 0
return lib.ffi.buffer(q, crypto_scalarmult_SCALARBYTES)[:]
def crypto_scalarmult(n, p):
"""
Computes and returns the scalar product of the given group element and an
integer ``n``.
:param p: bytes
:param n: bytes
:rtype: bytes
"""
q = lib.ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
rc = lib.crypto_scalarmult(q, n, p)
assert rc == 0
return lib.ffi.buffer(q, crypto_scalarmult_SCALARBYTES)[:]
# 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
from nacl._lib import lib
from nacl.exceptions import CryptoError
crypto_secretbox_KEYBYTES = lib.crypto_secretbox_keybytes()
crypto_secretbox_NONCEBYTES = lib.crypto_secretbox_noncebytes()
crypto_secretbox_ZEROBYTES = lib.crypto_secretbox_zerobytes()
crypto_secretbox_BOXZEROBYTES = lib.crypto_secretbox_boxzerobytes()
def crypto_secretbox(message, nonce, key):
"""
Encrypts and returns the message ``message`` with the secret ``key`` and
the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param key: bytes
:rtype: bytes
"""
if len(key) != crypto_secretbox_KEYBYTES:
raise ValueError("Invalid key")
if len(nonce) != crypto_secretbox_NONCEBYTES:
raise ValueError("Invalid nonce")
padded = b"\x00" * crypto_secretbox_ZEROBYTES + message
ciphertext = lib.ffi.new("unsigned char[]", len(padded))
if lib.crypto_secretbox(ciphertext, padded, len(padded), nonce, key) != 0:
raise CryptoError("Encryption failed")
ciphertext = lib.ffi.buffer(ciphertext, len(padded))
return ciphertext[crypto_secretbox_BOXZEROBYTES:]
def crypto_secretbox_open(ciphertext, nonce, key):
"""
Decrypt and returns the encrypted message ``ciphertext`` with the secret
``key`` and the nonce ``nonce``.
:param ciphertext: bytes
:param nonce: bytes
:param key: bytes
:rtype: bytes
"""
if len(key) != crypto_secretbox_KEYBYTES:
raise ValueError("Invalid key")
if len(nonce) != crypto_secretbox_NONCEBYTES:
raise ValueError("Invalid nonce")
padded = b"\x00" * crypto_secretbox_BOXZEROBYTES + ciphertext
plaintext = lib.ffi.new("unsigned char[]", len(padded))
if lib.crypto_secretbox_open(
plaintext, padded, len(padded), nonce, key) != 0:
raise CryptoError("Decryption failed. Ciphertext failed verification")
plaintext = lib.ffi.buffer(plaintext, len(padded))
return plaintext[crypto_secretbox_ZEROBYTES:]
# 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
from nacl._lib import lib
from nacl.exceptions import BadSignatureError, CryptoError
crypto_sign_BYTES = lib.crypto_sign_bytes()
# crypto_sign_SEEDBYTES = lib.crypto_sign_seedbytes()
crypto_sign_SEEDBYTES = lib.crypto_sign_secretkeybytes() // 2
crypto_sign_PUBLICKEYBYTES = lib.crypto_sign_publickeybytes()
crypto_sign_SECRETKEYBYTES = lib.crypto_sign_secretkeybytes()
def crypto_sign_keypair():
"""
Returns a randomly generated public key and secret key.
:rtype: (bytes(public_key), bytes(secret_key))
"""
pk = lib.ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
sk = lib.ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
if lib.crypto_sign_keypair(pk, sk) != 0:
raise CryptoError("An error occurred while generating keypairs")
return (
lib.ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
lib.ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
)
def crypto_sign_seed_keypair(seed):
"""
Computes and returns the public key and secret key using the seed ``seed``.
:param seed: bytes
:rtype: (bytes(public_key), bytes(secret_key))
"""
if len(seed) != crypto_sign_SEEDBYTES:
raise ValueError("Invalid seed")
pk = lib.ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
sk = lib.ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
if lib.crypto_sign_seed_keypair(pk, sk, seed) != 0:
raise CryptoError("An error occurred while generating keypairs")
return (
lib.ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
lib.ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
)
def crypto_sign(message, sk):
"""
Signs the message ``message`` using the secret key ``sk`` and returns the
signed message.
:param message: bytes
:param sk: bytes
:rtype: bytes
"""
signed = lib.ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
signed_len = lib.ffi.new("unsigned long long *")
if lib.crypto_sign(signed, signed_len, message, len(message), sk) != 0:
raise CryptoError("Failed to sign the message")
return lib.ffi.buffer(signed, signed_len[0])[:]
def crypto_sign_open(signed, pk):
"""
Verifies the signature of the signed message ``signed`` using the public
key ``pkg`` and returns the unsigned message.
:param signed: bytes
:param pk: bytes
:rtype: bytes
"""
message = lib.ffi.new("unsigned char[]", len(signed))
message_len = lib.ffi.new("unsigned long long *")
if lib.crypto_sign_open(
message, message_len, signed, len(signed), pk) != 0:
raise BadSignatureError("Signature was forged or corrupt")
return lib.ffi.buffer(message, message_len[0])[:]
# 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
from nacl._lib import lib
def randombytes(size):
"""
Returns ``size`` number of random bytes from a cryptographically secure
random source.
:param size: int
:rtype: bytes
"""
buf = lib.ffi.new("unsigned char[]", size)
lib.randombytes(buf, size)
return lib.ffi.buffer(buf, size)[:]
# 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
from nacl._lib import lib
from nacl.exceptions import CryptoError
def sodium_init():
"""
Initializes sodium, picking the best implementations available for this
machine.
"""
if lib.sodium_init() != 0:
raise CryptoError("Could not initialize sodium")
# 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 base64
import binascii
class RawEncoder(object):
@staticmethod
def encode(data):
return data
@staticmethod
def decode(data):
return data
class HexEncoder(object):
@staticmethod
def encode(data):
return binascii.hexlify(data)
@staticmethod
def decode(data):
return binascii.unhexlify(data)
class Base16Encoder(object):
@staticmethod
def encode(data):
return base64.b16encode(data)
@staticmethod
def decode(data):
return base64.b16decode(data)
class Base32Encoder(object):
@staticmethod
def encode(data):
return base64.b32encode(data)
@staticmethod
def decode(data):
return base64.b32decode(data)
class Base64Encoder(object):
@staticmethod
def encode(data):
return base64.b64encode(data)
@staticmethod
def decode(data):
return base64.b64decode(data)
class URLSafeBase64Encoder(object):
@staticmethod
def encode(data):
return base64.urlsafe_b64encode(data)
@staticmethod
def decode(data):
return base64.urlsafe_b64decode(data)
class Encodable(object):
def encode(self, encoder=RawEncoder):
return encoder.encode(bytes(self))
# 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
class CryptoError(Exception):
"""
Base exception for all nacl related errors
"""
class BadSignatureError(CryptoError):
"""
Raised when the signature was forged or otherwise corrupt.
"""
# 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 nacl.c
import nacl.encoding
def sha256(message, encoder=nacl.encoding.HexEncoder):
return encoder.encode(nacl.c.crypto_hash_sha256(message))
def sha512(message, encoder=nacl.encoding.HexEncoder):
return encoder.encode(nacl.c.crypto_hash_sha512(message))
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment