Beispiel #1
0
        def __init__(self, key = None):  # pylint: disable=super-init-not-called

            _Rsa.__init__(self)  # pylint: disable=non-parent-init-called

            idx = _ffi.new("word32*")
            idx[0] = 0

            if key != None:
                key = t2b(key)
                ret = _lib.wc_RsaPrivateKeyDecode(key, idx,
                                              self.native_object, len(key))
                if ret < 0:
                    idx[0] = 0
                    ret = _lib.wc_GetPkcs8TraditionalOffset(key, idx, len(key))
                    if ret < 0:
                        raise WolfCryptError("Invalid key error (%d)" % ret)

                    ret = _lib.wc_RsaPrivateKeyDecode(key, idx,
                                              self.native_object, len(key))
                    if ret < 0:
                        raise WolfCryptError("Invalid key error (%d)" % ret)

                self.size = len(key)
                self.output_size = _lib.wc_RsaEncryptSize(self.native_object)
                if self.output_size <= 0:  # pragma: no cover
                    raise WolfCryptError("Invalid key size error (%d)" %
                            self.output_size)
Beispiel #2
0
            def verify_raw(self, R, S, data):
                """
                Verifies signature from its raw elements **R** and **S**, using
                the public key data in the object.

                Returns **True** in case of a valid signature, otherwise
                **False**.
                """
                data = t2b(data)
                status = _ffi.new("int[1]")
                mpR = _ffi.new("mp_int[1]")
                mpS = _ffi.new("mp_int[1]")
                ret = _lib.mp_init(mpR)
                if ret != 0:  # pragma: no cover
                    raise WolfCryptError("wolfCrypt error (%d)" % ret)
                ret = _lib.mp_init(mpS)
                if ret != 0:  # pragma: no cover
                    raise WolfCryptError("wolfCrypt error (%d)" % ret)

                ret = _lib.mp_read_unsigned_bin(mpR, R, len(R))
                if ret != 0:  # pragma: no cover
                    raise WolfCryptError("wolfCrypt error (%d)" % ret)

                ret = _lib.mp_read_unsigned_bin(mpS, S, len(S))
                if ret != 0:  # pragma: no cover
                    raise WolfCryptError("wolfCrypt error (%d)" % ret)

                ret = _lib.wc_ecc_verify_hash_ex(mpR, mpS, data, len(data),
                                                 status, self.native_object)

                if ret < 0:
                    raise WolfCryptError("Verify error (%d)" % ret)

                return status[0] == 1
Beispiel #3
0
    def encrypt(self, string):
        """
        Encrypts a non-empty string, using the key-dependent data in
        the object, and with the appropriate feedback mode.

        The string's length must be an exact multiple of the algorithm's
        block size or, in CFB mode, of the segment size.

        Returns a string containing the ciphertext.
        """
        string = t2b(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)
            ret = self._set_key(_ENCRYPTION)
            if ret < 0:  # pragma: no cover
                raise WolfCryptError("Invalid key error (%d)" % ret)

        result = _ffi.new("byte[%d]" % len(string))
        ret = self._encrypt(result, string)
        if ret < 0:  # pragma: no cover
            raise WolfCryptError("Encryption error (%d)" % ret)

        return _ffi.buffer(result)[:]
Beispiel #4
0
    def decrypt(self, string):
        """
        Decrypts **string**, using the key-dependent data in the
        object and with the appropriate feedback mode.

        The string's length must be an exact multiple of the algorithm's
        block size or, in CFB mode, of the segment size.

        Returns a string containing the plaintext.
        """
        string = t2b(string)

        if not string:
            raise ValueError(
                    "empty string not allowed")

        if len(string) % self.block_size and not "ChaCha" in self._native_type:
            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)
            ret = self._set_key(_DECRYPTION)
            if ret < 0:  # pragma: no cover
                raise WolfCryptError("Invalid key error (%d)" % ret)

        result = _ffi.new("byte[%d]" % len(string))
        ret = self._decrypt(result, string)
        if ret < 0:  # pragma: no cover
            raise WolfCryptError("Decryption error (%d)" % ret)

        return _ffi.buffer(result)[:]
Beispiel #5
0
    def __init__(self):
        self.native_object = _ffi.new("RsaKey *")
        ret = _lib.wc_InitRsaKey(self.native_object, _ffi.NULL)
        if ret < 0:  # pragma: no cover
            raise WolfCryptError("Invalid key error (%d)" % ret)

        self._random = Random()
        ret = _lib.wc_RsaSetRNG(self.native_object, self._random.native_object)
        if ret < 0:  # pragma: no cover
            raise WolfCryptError("Key initialization error (%d)" % ret)
Beispiel #6
0
    def __init__(self, key):
        key = t2b(key)

        _Rsa.__init__(self)

        idx = _ffi.new("word32*")
        idx[0] = 0

        ret = _lib.wc_RsaPublicKeyDecode(key, idx, self.native_object,
                                         len(key))
        if ret < 0:
            raise WolfCryptError("Invalid key error (%d)" % ret)

        self.output_size = _lib.wc_RsaEncryptSize(self.native_object)
        if self.output_size <= 0:  # pragma: no cover
            raise WolfCryptError("Invalid key error (%d)" % self.output_size)
Beispiel #7
0
    def __init__(self):
        self.native_object = _ffi.new("WC_RNG *")

        ret = _lib.wc_InitRng(self.native_object)
        if ret < 0:  # pragma: no cover
            self.native_object = None
            raise WolfCryptError("RNG init error (%d)" % ret)
Beispiel #8
0
 def import_x963(self, x963):
     """
     Imports an ECC public key in ANSI X9.63 format.
     """
     ret = _lib.wc_ecc_import_x963(x963, len(x963), self.native_object)
     if ret != 0:
         raise WolfCryptError("x963 import error (%d)" % ret)
Beispiel #9
0
 def decode_key_raw(self, qx, qy, curve_id=ECC_SECP256R1):
     """
     Decodes an ECC public key from its raw elements: (Qx,Qy)
     """
     ret = _lib.wc_ecc_import_unsigned(self.native_object, qx, qy,
             _ffi.NULL, curve_id)
     if ret != 0:
         raise WolfCryptError("Key decode error (%d)" % ret)
Beispiel #10
0
    def __init__(self, string=None):
        self._native_object = _ffi.new(self._native_type)
        ret = self._init()
        if ret < 0:  # pragma: no cover
            raise WolfCryptError("Hash init error (%d)" % ret)

        if string:
            self.update(string)
Beispiel #11
0
 def __init__(self, string, size=SHA3_384_DIGEST_SIZE):  # pylint: disable=W0231
     self._native_object = _ffi.new(self._native_type)
     self.digest_size = size
     ret = self._init()
     if ret < 0:  # pragma: no cover
         raise WolfCryptError("Sha3 init error (%d)" % ret)
     if string:
         self.update(string)
Beispiel #12
0
        def decode_key(self, key):
            """
            Decodes an ECC private key from an ASN sequence.
            """
            key = t2b(key)

            idx = _ffi.new("word32*")
            idx[0] = 0

            ret = _lib.wc_EccPrivateKeyDecode(key, idx,
                                              self.native_object, len(key))
            if ret < 0:
                raise WolfCryptError("Key decode error (%d)" % ret)
            if self.size <= 0:  # pragma: no cover
                raise WolfCryptError("Key decode error (%d)" % self.size)
            if self.max_signature_size <= 0:  # pragma: no cover
                raise WolfCryptError(
                    "Key decode error (%d)" % self.max_signature_size)
Beispiel #13
0
        def decode_key(self, key):
            """
            Decodes an ED25519 public key
            """
            key = t2b(key)
            if (len(key) < _lib.wc_ed25519_pub_size(self.native_object)):
                raise WolfCryptError("Key decode error: key too short")

            idx = _ffi.new("word32*")
            idx[0] = 0
            ret = _lib.wc_ed25519_import_public(key, len(key),
                    self.native_object)
            if ret < 0:
                raise WolfCryptError("Key decode error (%d)" % ret)
            if self.size <= 0:  # pragma: no cover
                raise WolfCryptError("Key decode error (%d)" % self.size)
            if self.max_signature_size <= 0:  # pragma: no cover
                raise WolfCryptError(
                    "Key decode error (%d)" % self.max_signature_size)
Beispiel #14
0
            def make_key(cls, size, rng=Random()):
                """
                Generates a new key pair of desired length **size**.
                """
                rsa = cls(None)
                if rsa == None:  # pragma: no cover
                    raise WolfCryptError("Invalid key error (%d)" % ret)

                ret = _lib.wc_MakeRsaKey(rsa.native_object, size, 65537,
                        rng.native_object)
                if ret < 0:
                    raise WolfCryptError("Key generation error (%d)" % ret)

                rsa.output_size = _lib.wc_RsaEncryptSize(rsa.native_object)
                rsa.size = size
                if rsa.output_size <= 0:  # pragma: no cover
                    raise WolfCryptError("Invalid key size error (%d)" % ret)

                return rsa
Beispiel #15
0
        def __init__(self, key, string=None):  # pylint: disable=W0231
            key = t2b(key)

            self._native_object = _ffi.new(self._native_type)
            ret = self._init(self._type, key)
            if ret < 0:  # pragma: no cover
                raise WolfCryptError("Hmac init error (%d)" % ret)

            if string:
                self.update(string)
Beispiel #16
0
 def _init(self, hmac, key):
     if _lib.wc_HmacInit(self._native_object, _ffi.NULL, -2) != 0:
         raise WolfCryptError("wc_HmacInit error")
     # If the key isn't set, don't call wc_HmacSetKey. This can happen,
     # for example, when the HMAC object is being copied. See the copy
     # function of _Hash.
     ret = 0
     if len(key) > 0:
         ret = _lib.wc_HmacSetKey(self._native_object, hmac, key,
                                  len(key))
         if ret < 0:
             err_str = "no error description found"
             try:
                 err_str = _ffi.string(
                     _lib.wc_GetErrorString(ret)).decode()
             except:
                 pass
             raise WolfCryptError(
                 "wc_HmacSetKey returned {}: {}".format(ret, err_str))
     return ret
Beispiel #17
0
    def make_key(cls, size, rng=Random()):
        """
        Generates a new key pair of desired length **size**.
        """
        ecc = cls()

        ret = _lib.wc_ecc_make_key(rng.native_object, size, ecc.native_object)
        if ret < 0:
            raise WolfCryptError("Key generation error (%d)" % ret)

        return ecc
Beispiel #18
0
    def update(self, string):
        """
        Hashes **string** into the current state of the hashing
        object. update() can be called any number of times during
        a hashing object's lifetime.
        """
        string = t2b(string)

        ret = self._update(string)
        if ret < 0:  # pragma: no cover
            raise WolfCryptError("Hash update error (%d)" % ret)
Beispiel #19
0
    def bytes(self, length):
        """
        Generate and return a random sequence of length bytes.
        """
        result = _ffi.new('byte[%d]' % length)

        ret = _lib.wc_RNG_GenerateBlock(self.native_object, result, length)
        if ret < 0:  # pragma: no cover
            raise WolfCryptError("RNG generate block error (%d)" % ret)

        return _ffi.buffer(result, length)[:]
Beispiel #20
0
    def byte(self):
        """
        Generate and return a random byte.
        """
        result = _ffi.new('byte[1]')

        ret = _lib.wc_RNG_GenerateByte(self.native_object, result)
        if ret < 0:  # pragma: no cover
            raise WolfCryptError("RNG generate byte error (%d)" % ret)

        return _ffi.buffer(result, 1)[:]
Beispiel #21
0
            def encode_key(self):
                """
                Encodes the RSA private and public keys in an ASN sequence.

                Returns the encoded key.
                """
                priv = _ffi.new("byte[%d]" % (self.size * 4))
                pub = _ffi.new("byte[%d]" % (self.size * 4))

                ret = _lib.wc_RsaKeyToDer(self.native_object, priv, self.size)
                if ret <= 0:  # pragma: no cover
                    raise WolfCryptError("Private RSA key error (%d)" % ret)
                privlen = ret
                ret = _lib.wc_RsaKeyToPublicDer(self.native_object, pub,
                                                self.size)
                if ret <= 0:  # pragma: no cover
                    raise WolfCryptError("Public RSA key encode error (%d)" %
                                         ret)
                publen = ret
                return _ffi.buffer(priv, privlen)[:], _ffi.buffer(pub,
                                                                  publen)[:]
Beispiel #22
0
        def decode_key(self, key, pub = None):
            """
            Decodes an ED25519 private + pub key
            """
            key = t2b(key)

            if (len(key) < _lib.wc_ed25519_priv_size(self.native_object)/2):
                raise WolfCryptError("Key decode error: key too short")

            idx = _ffi.new("word32*")
            idx[0] = 0
            if pub:
                ret = _lib.wc_ed25519_import_private_key(key, len(key), pub,
                        len(pub), self.native_object);
                if ret < 0:
                    raise WolfCryptError("Key decode error (%d)" % ret)
            else:
                ret = _lib.wc_ed25519_import_private_only(key, len(key),
                        self.native_object);
                if ret < 0:
                    raise WolfCryptError("Key decode error (%d)" % ret)
                pubkey = _ffi.new("byte[%d]" % (self.size * 4))
                ret = _lib.wc_ed25519_make_public(self.native_object, pubkey,
                        self.size)
                if ret < 0:
                    raise WolfCryptError("Public key generate error (%d)" % ret)
                ret = _lib.wc_ed25519_import_public(pubkey, self.size,
                        self.native_object);

            if self.size <= 0:  # pragma: no cover
                raise WolfCryptError("Key decode error (%d)" % self.size)
            if self.max_signature_size <= 0:  # pragma: no cover
                raise WolfCryptError(
                    "Key decode error (%d)" % self.max_signature_size)
Beispiel #23
0
        def encode_key(self):
            """
            Encodes the ED25519 private key.

            Returns the encoded key.
            """
            key = _ffi.new("byte[%d]" % (self.size * 4))
            pubkey = _ffi.new("byte[%d]" % (self.size * 4))
            size = _ffi.new("word32[1]")

            size[0] = _lib.wc_ed25519_priv_size(self.native_object)

            ret = _lib.wc_ed25519_export_private_only(self.native_object,
                    key, size)
            if ret != 0:  # pragma: no cover
                raise WolfCryptError("Private key encode error (%d)" % ret)
            ret = _lib.wc_ed25519_export_public(self.native_object, pubkey,
                    size)
            if ret != 0:  # pragma: no cover
                raise WolfCryptError("Public key encode error (%d)" % ret)

            return _ffi.buffer(key, size[0])[:], _ffi.buffer(pubkey, size[0])[:]
Beispiel #24
0
        def encode_key(self):
            """
            Encodes the ECC private key in an ASN sequence.

            Returns the encoded key.
            """
            key = _ffi.new("byte[%d]" % (self.size * 4))

            ret = _lib.wc_EccKeyToDer(self.native_object, key, len(key))
            if ret <= 0:  # pragma: no cover
                raise WolfCryptError("Key encode error (%d)" % ret)

            return _ffi.buffer(key, ret)[:]
Beispiel #25
0
            def sign_raw(self, plaintext, rng=Random()):
                """
                Signs **plaintext**, using the private key data in the object.

                Returns the signature in its two raw components r, s
                """
                plaintext = t2b(plaintext)
                R = _ffi.new("mp_int[1]");
                S = _ffi.new("mp_int[1]");

                R_bin = _ffi.new("unsigned char[%d]" % self.size )
                S_bin = _ffi.new("unsigned char[%d]" % self.size )

                ret = _lib.mp_init(R)
                if ret != 0:  # pragma: no cover
                    raise WolfCryptError("wolfCrypt error (%d)" % ret)
                ret = _lib.mp_init(S)
                if ret != 0:  # pragma: no cover
                    raise WolfCryptError("wolfCrypt error (%d)" % ret)

                ret = _lib.wc_ecc_sign_hash_ex(plaintext, len(plaintext),
                                            rng.native_object,
                                            self.native_object,
                                            R, S)
                if ret != 0:  # pragma: no cover
                    raise WolfCryptError("Signature error (%d)" % ret)

                ret = _lib.mp_to_unsigned_bin(R, R_bin)
                if ret != 0:  # pragma: no cover
                    raise WolfCryptError("wolfCrypt error (%d)" % ret)

                ret = _lib.mp_to_unsigned_bin(S, S_bin)
                if ret != 0:  # pragma: no cover
                    raise WolfCryptError("wolfCrypt error (%d)" % ret)

                return _ffi.buffer(R_bin, self.size)[:], _ffi.buffer(S_bin,
                        self.size)[:]
Beispiel #26
0
        def export_x963(self):
            """
            Exports the public key data of the object in ANSI X9.63 format.

            Returns the exported key.
            """
            x963 = _ffi.new("byte[%d]" % (self.size * 4))
            x963_size = _ffi.new("word32[1]")
            x963_size[0] = self.size * 4

            ret = _lib.wc_ecc_export_x963(self.native_object, x963, x963_size)
            if ret != 0:  # pragma: no cover
                raise WolfCryptError("x963 export error (%d)" % ret)

            return _ffi.buffer(x963, x963_size[0])[:]
Beispiel #27
0
    def PBKDF2(password, salt, iterations, key_length, hash_type):
        if isinstance(salt, str):
            salt = str.encode(salt)

        if isinstance(password, str):
            password = str.encode(password)

        key = _ffi.new("byte[%d]" % key_length)
        ret = _lib.wc_PBKDF2(key, password, len(password), salt, len(salt),
                             iterations, key_length, hash_type)

        if ret != 0:
            raise WolfCryptError("PBKDF2 error (%d)" % ret)

        return _ffi.buffer(key, key_length)[:]
Beispiel #28
0
    def verify(self, signature, data):
        """
        Verifies **signature**, using the public key data in the object.

        Returns **True** in case of a valid signature, otherwise **False**.
        """
        data = t2b(data)
        status = _ffi.new("int[1]")

        ret = _lib.wc_ecc_verify_hash(signature, len(signature), data,
                                      len(data), status, self.native_object)

        if ret < 0:
            raise WolfCryptError("Verify error (%d)" % ret)

        return status[0] == 1
Beispiel #29
0
    def shared_secret(self, peer):
        """
        Generates a new secret key using the private key data in the object
        and the peer's public key.

        Returns the shared secret.
        """
        shared_secret = _ffi.new("byte[%d]" % self.max_signature_size)
        secret_size = _ffi.new("word32[1]")
        secret_size[0] = self.max_signature_size

        ret = _lib.wc_ecc_shared_secret(self.native_object, peer.native_object,
                                        shared_secret, secret_size)

        if ret != 0:  # pragma: no cover
            raise WolfCryptError("Shared secret error (%d)" % ret)

        return _ffi.buffer(shared_secret, secret_size[0])[:]
Beispiel #30
0
    def digest(self):
        """
        Returns the hash value of this hashing object as a string
        containing 8-bit data. The object is not altered in any
        way by this function; you can continue updating the object
        after calling this function.
        """
        result = _ffi.new("byte[%d]" % self.digest_size)

        if self._native_object:
            obj = _ffi.new(self._native_type)

            _ffi.memmove(obj, self._native_object, self._native_size)

            ret = self._final(obj, result)
            if ret < 0:  # pragma: no cover
                raise WolfCryptError("Hash finalize error (%d)" % ret)

        return _ffi.buffer(result, self.digest_size)[:]