importing wolfcrypt-py repo

This commit is contained in:
Moisés Guimarães
2016-04-28 13:20:10 -03:00
parent a54b0f9d0c
commit 7e661ab866
12 changed files with 1419 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
# WolfCrypt
#
# Copyright (C) 2006-2016 wolfSSL Inc.
#
# This file is part of wolfSSL. (formerly known as CyaSSL)
#
# wolfSSL is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# wolfSSL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
# dummy file

View File

@@ -0,0 +1,133 @@
# build_random.py
#
# Copyright (C) 2006-2016 wolfSSL Inc.
#
# This file is part of wolfSSL. (formerly known as CyaSSL)
#
# wolfSSL is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# wolfSSL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
import os
from cffi import FFI
ffi = FFI()
ffi.set_source("wolfcrypt._ffi",
"""
#include <wolfssl/options.h>
#include <wolfssl/wolfcrypt/sha.h>
#include <wolfssl/wolfcrypt/sha256.h>
#include <wolfssl/wolfcrypt/sha512.h>
#include <wolfssl/wolfcrypt/hmac.h>
#include <wolfssl/wolfcrypt/aes.h>
#include <wolfssl/wolfcrypt/des3.h>
#include <wolfssl/wolfcrypt/asn.h>
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/rsa.h>
""",
include_dirs=["/usr/local/include"],
library_dirs=["/usr/local/lib"],
libraries=["wolfssl"],
)
ffi.cdef(
"""
typedef unsigned char byte;
typedef unsigned int word32;
typedef struct { ...; } Sha;
int wc_InitSha(Sha*);
int wc_ShaUpdate(Sha*, const byte*, word32);
int wc_ShaFinal(Sha*, byte*);
typedef struct { ...; } Sha256;
int wc_InitSha256(Sha256*);
int wc_Sha256Update(Sha256*, const byte*, word32);
int wc_Sha256Final(Sha256*, byte*);
typedef struct { ...; } Sha384;
int wc_InitSha384(Sha384*);
int wc_Sha384Update(Sha384*, const byte*, word32);
int wc_Sha384Final(Sha384*, byte*);
typedef struct { ...; } Sha512;
int wc_InitSha512(Sha512*);
int wc_Sha512Update(Sha512*, const byte*, word32);
int wc_Sha512Final(Sha512*, byte*);
typedef struct { ...; } Hmac;
int wc_HmacSetKey(Hmac*, int, const byte*, word32);
int wc_HmacUpdate(Hmac*, const byte*, word32);
int wc_HmacFinal(Hmac*, byte*);
typedef struct { ...; } Aes;
int wc_AesSetKey(Aes*, const byte*, word32, const byte*, int);
int wc_AesCbcEncrypt(Aes*, byte*, const byte*, word32);
int wc_AesCbcDecrypt(Aes*, byte*, const byte*, word32);
typedef struct { ...; } Des3;
int wc_Des3_SetKey(Des3*, const byte*, const byte*, int);
int wc_Des3_CbcEncrypt(Des3*, byte*, const byte*, word32);
int wc_Des3_CbcDecrypt(Des3*, byte*, const byte*, word32);
typedef struct { ...; } WC_RNG;
int wc_InitRng(WC_RNG*);
int wc_RNG_GenerateBlock(WC_RNG*, byte*, word32);
int wc_RNG_GenerateByte(WC_RNG*, byte*);
int wc_FreeRng(WC_RNG*);
typedef struct {...; } RsaKey;
int wc_InitRsaKey(RsaKey* key, void*);
int wc_FreeRsaKey(RsaKey* key);
int wc_RsaPrivateKeyDecode(const byte*, word32*, RsaKey*, word32);
int wc_RsaPublicKeyDecode(const byte*, word32*, RsaKey*, word32);
int wc_RsaEncryptSize(RsaKey*);
int wc_RsaPrivateDecrypt(const byte*, word32, byte*, word32,
RsaKey* key);
int wc_RsaPublicEncrypt(const byte*, word32, byte*, word32,
RsaKey*, WC_RNG*);
int wc_RsaSSL_Sign(const byte*, word32, byte*, word32, RsaKey*, WC_RNG*);
int wc_RsaSSL_Verify(const byte*, word32, byte*, word32, RsaKey*);
"""
)
if __name__ == "__main__":
ffi.compile(verbose=1)

View File

@@ -0,0 +1,252 @@
# ciphers.py
#
# Copyright (C) 2006-2016 wolfSSL Inc.
#
# This file is part of wolfSSL. (formerly known as CyaSSL)
#
# wolfSSL is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# wolfSSL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
from wolfcrypt._ffi import ffi as _ffi
from wolfcrypt._ffi import lib as _lib
from wolfcrypt.random import Random
# key direction flags
_ENCRYPTION = 0
_DECRYPTION = 1
# feedback modes
MODE_ECB = 1 # Electronic Code Book
MODE_CBC = 2 # Cipher Block Chaining
MODE_CFB = 3 # Cipher Feedback
MODE_OFB = 5 # Output Feedback
MODE_CTR = 6 # Counter
_FEEDBACK_MODES = [MODE_ECB, MODE_CBC, MODE_CFB, MODE_OFB, MODE_CTR]
class _Cipher(object):
# Magic object that protects against constructors.
_JAPANESE_CYBER_SWORD = object()
def __init__(self, token=""):
if token is not self._JAPANESE_CYBER_SWORD:
# PEP 272 -- API for Block Encryption Algorithms v1.0
raise ValueError("don't construct directly, use new([string])")
@classmethod
def new(cls, key, mode, IV=None, **kwargs):
if mode not in _FEEDBACK_MODES:
raise ValueError("this mode is not supported")
if mode != MODE_CBC:
raise ValueError("this mode is not supported by this cipher")
self = cls(_Cipher._JAPANESE_CYBER_SWORD)
if self.key_size:
if self.key_size != len(key):
raise ValueError("key must be %d in length" % self.key_size)
elif self._key_sizes:
if len(key) not in self._key_sizes:
raise ValueError("key must be %s in length" % self._key_sizes)
else:
if not len(key):
raise ValueError("key must not be 0 in length")
if IV is not None and len(IV) != self.block_size:
raise ValueError("IV must be %d in length" % self.block_size)
self._native_object = _ffi.new(self._native_type)
self._enc = None
self._dec = None
self._key = key
self._IV = IV if IV else "\0" * self.block_size
return self
def encrypt(self, string):
if not string or len(string) % self.block_size:
raise ValueError(
"string must be a multiple of %d in length" % self.block_size)
if self._enc is None:
self._enc = _ffi.new(self._native_type)
self._set_key(_ENCRYPTION)
result = "\0" * len(string)
self._encrypt(result, string)
return result
def decrypt(self, string):
if not string or len(string) % self.block_size:
raise ValueError(
"string must be a multiple of %d in length" % self.block_size)
if self._dec is None:
self._dec = _ffi.new(self._native_type)
self._set_key(_DECRYPTION)
result = "\0" * len(string)
self._decrypt(result, string)
return result
class Aes(_Cipher):
block_size = 16
key_size = None # 16, 24, 32
_key_sizes = [16, 24, 32]
_native_type = "Aes *"
def _set_key(self, direction):
if direction == _ENCRYPTION:
_lib.wc_AesSetKey(
self._enc, self._key, len(self._key), self._IV, _ENCRYPTION)
else:
_lib.wc_AesSetKey(
self._dec, self._key, len(self._key), self._IV, _DECRYPTION)
def _encrypt(self, destination, source):
_lib.wc_AesCbcEncrypt(self._enc, destination, source, len(source))
def _decrypt(self, destination, source):
_lib.wc_AesCbcDecrypt(self._dec, destination, source, len(source))
class Des3(_Cipher):
block_size = 8
key_size = 24
_native_type = "Des3 *"
def _set_key(self, direction):
if direction == _ENCRYPTION:
_lib.wc_Des3_SetKey(self._enc, self._key, self._IV, _ENCRYPTION)
else:
_lib.wc_Des3_SetKey(self._dec, self._key, self._IV, _DECRYPTION)
def _encrypt(self, destination, source):
_lib.wc_Des3_CbcEncrypt(self._enc, destination, source, len(source))
def _decrypt(self, destination, source):
_lib.wc_Des3_CbcDecrypt(self._dec, destination, source, len(source))
class _Rsa(object):
def __init__(self):
self.native_object = _ffi.new("RsaKey *")
if _lib.wc_InitRsaKey(self.native_object, _ffi.NULL) != 0:
raise KeyError
self._random = Random()
def __del__(self):
if self.native_object:
_lib.wc_FreeRsaKey(self.native_object)
class RsaPublic(_Rsa):
def __init__(self, key):
_Rsa.__init__(self)
idx = _ffi.new("word32*")
idx[0] = 0
if _lib.wc_RsaPublicKeyDecode(key, idx, self.native_object, len(key)):
raise KeyError
self.output_size = _lib.wc_RsaEncryptSize(self.native_object)
if self.output_size <= 0:
raise KeyError
def encrypt(self, plaintext):
ciphertext = "\0" * self.output_size
ret = _lib.wc_RsaPublicEncrypt(plaintext, len(plaintext),
ciphertext, len(ciphertext),
self.native_object,
self._random.native_object)
if ret != self.output_size:
raise KeyError
return ciphertext
def verify(self, signature):
plaintext = "\0" * self.output_size
ret = _lib.wc_RsaSSL_Verify(signature, len(signature),
plaintext, len(plaintext),
self.native_object)
if ret < 0:
raise KeyError
return plaintext[:ret]
class RsaPrivate(RsaPublic):
def __init__(self, key):
_Rsa.__init__(self)
idx = _ffi.new("word32*")
idx[0] = 0
if _lib.wc_RsaPrivateKeyDecode(key, idx, self.native_object, len(key)):
raise KeyError
self.output_size = _lib.wc_RsaEncryptSize(self.native_object)
def decrypt(self, ciphertext):
plaintext = "\0" * self.output_size
ret = _lib.wc_RsaPrivateDecrypt(ciphertext, len(ciphertext),
plaintext, len(plaintext),
self.native_object)
if ret < 0:
raise KeyError
return plaintext[:ret]
def sign(self, plaintext):
signature = "\0" * self.output_size
ret = _lib.wc_RsaSSL_Sign(plaintext, len(plaintext),
signature, len(signature),
self.native_object,
self._random.native_object)
if ret != self.output_size:
raise KeyError
return signature

View File

@@ -0,0 +1,210 @@
# hashes.py
#
# Copyright (C) 2006-2016 wolfSSL Inc.
#
# This file is part of wolfSSL. (formerly known as CyaSSL)
#
# wolfSSL is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# wolfSSL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
from wolfcrypt._ffi import ffi as _ffi
from wolfcrypt._ffi import lib as _lib
class _Hash(object):
# Magic object that protects against constructors.
_JAPANESE_CYBER_SWORD = object()
def __init__(self, token=""):
if token is not self._JAPANESE_CYBER_SWORD:
# PEP 247 -- API for Cryptographic Hash Functions
raise ValueError("don't construct directly, use new([string])")
@classmethod
def new(cls, string=None):
self = cls(cls._JAPANESE_CYBER_SWORD)
self._native_object = _ffi.new(self._native_type)
self._init()
if (string):
self._update(string)
return self
def copy(self):
copy = self.new("")
_ffi.memmove(copy._native_object,
self._native_object,
self._native_size)
return copy
def update(self, string):
self._update(string)
def digest(self):
ret = "\0" * self.digest_size
if self._native_object:
obj = _ffi.new(self._native_type)
_ffi.memmove(obj, self._native_object, self._native_size)
self._final(obj, ret)
return ret
def hexdigest(self):
return self.digest().encode("hex")
class Sha(_Hash):
digest_size = 20
_native_type = "Sha *"
_native_size = _ffi.sizeof("Sha")
def _init(self):
_lib.wc_InitSha(self._native_object)
def _update(self, data):
_lib.wc_ShaUpdate(self._native_object, data, len(data))
def _final(self, obj, ret):
_lib.wc_ShaFinal(obj, ret)
class Sha256(_Hash):
digest_size = 32
_native_type = "Sha256 *"
_native_size = _ffi.sizeof("Sha256")
def _init(self):
_lib.wc_InitSha256(self._native_object)
def _update(self, data):
_lib.wc_Sha256Update(self._native_object, data, len(data))
def _final(self, obj, ret):
_lib.wc_Sha256Final(obj, ret)
class Sha384(_Hash):
digest_size = 48
_native_type = "Sha384 *"
_native_size = _ffi.sizeof("Sha384")
def _init(self):
_lib.wc_InitSha384(self._native_object)
def _update(self, data):
_lib.wc_Sha384Update(self._native_object, data, len(data))
def _final(self, obj, ret):
_lib.wc_Sha384Final(obj, ret)
class Sha512(_Hash):
digest_size = 64
_native_type = "Sha512 *"
_native_size = _ffi.sizeof("Sha512")
def _init(self):
_lib.wc_InitSha512(self._native_object)
def _update(self, data):
_lib.wc_Sha512Update(self._native_object, data, len(data))
def _final(self, obj, ret):
_lib.wc_Sha512Final(obj, ret)
# Hmac types
_TYPE_SHA = 1
_TYPE_SHA256 = 2
_TYPE_SHA384 = 5
_TYPE_SHA512 = 4
_HMAC_TYPES = [_TYPE_SHA, _TYPE_SHA256, _TYPE_SHA384, _TYPE_SHA512]
class _Hmac(_Hash):
digest_size = None
_native_type = "Hmac *"
_native_size = _ffi.sizeof("Hmac")
@classmethod
def new(cls, key, string=None):
self = cls(cls._JAPANESE_CYBER_SWORD)
self._native_object = _ffi.new(self._native_type)
self._init(self._type, key)
if (string):
self._update(string)
return self
def _init(self, type, key):
_lib.wc_HmacSetKey(self._native_object, type, key, len(key))
def _update(self, data):
_lib.wc_HmacUpdate(self._native_object, data, len(data))
def _final(self, obj, ret):
_lib.wc_HmacFinal(obj, ret)
class HmacSha(_Hmac):
_type = _TYPE_SHA
digest_size = Sha.digest_size
class HmacSha256(_Hmac):
_type = _TYPE_SHA256
digest_size = Sha256.digest_size
class HmacSha384(_Hmac):
_type = _TYPE_SHA384
digest_size = Sha384.digest_size
class HmacSha512(_Hmac):
_type = _TYPE_SHA512
digest_size = Sha512.digest_size

View File

@@ -0,0 +1,49 @@
# random.py
#
# Copyright (C) 2006-2016 wolfSSL Inc.
#
# This file is part of wolfSSL. (formerly known as CyaSSL)
#
# wolfSSL is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# wolfSSL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
from wolfcrypt._ffi import ffi as _ffi
from wolfcrypt._ffi import lib as _lib
class Random(object):
def __init__(self):
self.native_object = _ffi.new("WC_RNG *")
if _lib.wc_InitRng(self.native_object) != 0:
self.native_object = None
def __del__(self):
if self.native_object:
_lib.wc_FreeRng(self.native_object)
def byte(self):
ret = "\0"
_lib.wc_RNG_GenerateByte(self.native_object, ret)
return ret
def bytes(self, length):
ret = "\0" * length
_lib.wc_RNG_GenerateBlock(self.native_object, ret, length)
return ret