Python hashlib.sha384() Examples

The following are 30 code examples of hashlib.sha384(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module hashlib , or try the search function .
Example #1
Source File: utils.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def sri_hash(data, url_safe=False):
    """
    Return a subresource integrity attribute string for a file
    containing the given binary data.

    SRI attributes are a string of the form "{algorithm}-{hash}", where
    {algorithm} is the hash algorithm, and {hash} is a base64-encoded
    hash of the data using the specified algorithm.

    :param data:
        Bytes-like object containing the data to hash.
    """
    digest = sha384(data).digest()
    if url_safe:
        data_hash = urlsafe_b64encode(digest)
    else:
        data_hash = b64encode(digest)
    return "sha384-" + data_hash.decode() 
Example #2
Source File: rocktrading.py    From bitex with MIT License 6 votes vote down vote up
def sign(self, uri, endpoint, endpoint_path, method_verb, *args, **kwargs):
        nonce = self.nonce()
        try:
            params = kwargs['params']
        except KeyError:
            params = {}
        payload = params
        payload['nonce'] = int(nonce)
        payload['request'] = endpoint_path

        msg = nonce + uri
        sig = hmac.new(self.secret.encode(), msg.encode(), hashlib.sha384).hexdigest()
        headers = {'X-TRT-APIKEY': self.key,
                   'X-TRT-Nonce': nonce,
                   'X-TRT-SIGNATURE': sig, 'Content-Type': 'application/json'}
        return uri, {'headers': headers} 
Example #3
Source File: gemini.py    From bitex with MIT License 6 votes vote down vote up
def sign(self, uri, endpoint, endpoint_path, method_verb, *args, **kwargs):
        nonce = self.nonce()
        try:
            params = kwargs['params']
        except KeyError:
            params = {}
        payload = params
        payload['nonce'] = nonce
        payload['request'] = endpoint_path

        js = json.dumps(payload)
        data = base64.standard_b64encode(js.encode('utf8'))
        h = hmac.new(self.secret.encode('utf8'), data, hashlib.sha384)
        signature = h.hexdigest()
        headers = {'X-GEMINI-APIKEY': self.key,
                   'X-GEMINI-PAYLOAD': data,
                   'X-GEMINI-SIGNATURE': signature}
        return uri, {'headers': headers} 
Example #4
Source File: bitfinex.py    From bitex with MIT License 6 votes vote down vote up
def sign(self, url, endpoint, endpoint_path, method_verb, *args, **kwargs):
        try:
            req = kwargs['params']
        except KeyError:
            req = {}
        if self.version == 'v1':
            req['request'] = endpoint_path
            req['nonce'] = self.nonce()

            js = json.dumps(req)
            data = base64.standard_b64encode(js.encode('utf8'))
        else:
            data = '/api/' + endpoint_path + self.nonce() + json.dumps(req)
        h = hmac.new(self.secret.encode('utf8'), data, hashlib.sha384)
        signature = h.hexdigest()
        headers = {"X-BFX-APIKEY": self.key,
                   "X-BFX-SIGNATURE": signature,
                   "X-BFX-PAYLOAD": data}
        if self.version == 'v2':
            headers['content-type'] = 'application/json'

        return url, {'headers': headers} 
Example #5
Source File: hashing.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def sha2_384(self):
        """Get SHA2-384 hash
        
        The SHA-2 (Secure Hash Algorithm 2) hash functions were designed by the NSA. SHA-2 
        includes significant changes from its predecessor, SHA-1. The SHA-2 family consists of 
        hash functions with digests (hash values) that are 224, 256, 384 or 512 bits: SHA224, 
        SHA256, SHA384, SHA512. SHA-512 operates on 64-bit words. SHA-256 operates on 32-bit 
        words. SHA-384 is largely identical to SHA-512 but is truncated to 384 bytes. SHA-224 
        is largely identical to SHA-256 but is truncated to 224 bytes. SHA-512/224 and SHA-512/256 
        are truncated versions of SHA-512, but the initial values are generated using the method 
        described in Federal Information Processing Standards (FIPS) PUB 180-4.

        Returns:
            Chepy: The Chepy object. 
        """
        self.state = hashlib.sha384(self._convert_to_bytes()).hexdigest()
        return self 
Example #6
Source File: test_idx.py    From dffml with MIT License 6 votes vote down vote up
def test_idx3(self, filename):
        feature_name = "image"
        async with IDX3Source(
            IDX3SourceConfig(filename=str(filename), feature=feature_name)
        ) as source:
            async with source() as sctx:
                records = [record async for record in sctx.records()]
                self.assertEqual(len(records), 60000)
                self.assertIn(feature_name, records[0].features())
                for i in range(-1, 1):
                    with self.subTest(index=i):
                        is_hash = hashlib.sha384(
                            json.dumps(
                                records[i].feature(feature_name)
                            ).encode()
                        ).hexdigest()
                        self.assertEqual(is_hash, IDX3_FIRST_LAST[i]) 
Example #7
Source File: test_config.py    From dffml with MIT License 6 votes vote down vote up
def test_dumpb_loadb(self):
        async with PNGConfigLoader.withconfig({}) as configloader:
            async with configloader() as ctx:
                image_bytes = (
                    pathlib.Path(__file__).parent
                    / ".."
                    / ".."
                    / ".."
                    / "examples"
                    / "MNIST"
                    / "image1.png"
                ).read_bytes()
                original = await ctx.loadb(image_bytes)
                hash_original = hashlib.sha384(
                    json.dumps(original.flatten().tolist()).encode()
                ).hexdigest()
                self.assertEqual(original.shape, (280, 280, 3))
                self.assertEqual(hash_original, IMAGE1_HASH) 
Example #8
Source File: text_to_hash.py    From PyCk with GNU General Public License v3.0 6 votes vote down vote up
def main(text, hashType):
    encoder = text.encode('utf_8')
    myHash = ''

    if hashType.lower() == 'md5':
        myHash = hashlib.md5(encoder).hexdigest()
    elif hashType.lower() == 'sha1':
        myHash = hashlib.sha1(encoder).hexdigest()
    elif hashType.lower() == 'sha224':
        myHash = hashlib.sha224(encoder).hexdigest()
    elif hashType.lower() == 'sha256':
        myHash = hashlib.sha256(encoder).hexdigest()
    elif hashType.lower() == 'sha384':
        myHash = hashlib.sha384(encoder).hexdigest()
    elif hashType.lower() == 'sha512':
        myHash = hashlib.sha512(encoder).hexdigest()
    else:
        print('[!] The script does not support this hash type')
        exit(0)
    print("Your hash is: ", myHash) 
Example #9
Source File: vw_base.py    From dffml with MIT License 6 votes vote down vote up
def _feature_predict_hash(self):
        params = sorted(
            [
                "{}{}".format(k, v)
                for k, v in self.parent.config._asdict().items()
                if k
                not in [
                    "features",
                    "predict",
                    "vwcmd",
                    "class_cost",
                    "importance",
                    "tag",
                    "base",
                ]
            ]
        )
        params = "".join(params)
        return hashlib.sha384(
            "".join([params] + self.features).encode()
        ).hexdigest() 
Example #10
Source File: text_classifier.py    From dffml with MIT License 6 votes vote down vote up
def _model_dir_path(self):
        if self.parent.config.directory is None:
            return None
        _to_hash = self.features + [
            self.classification,
            str(len(self.cids)),
            self.parent.config.model_path,
        ]
        model = hashlib.sha384("".join(_to_hash).encode("utf-8")).hexdigest()
        # Needed to save updated model
        if not os.path.isdir(self.parent.config.directory):
            raise NotADirectoryError(
                "%s is not a directory" % (self.parent.config.directory)
            )
        os.makedirs(
            os.path.join(self.parent.config.directory, model), exist_ok=True
        )
        return os.path.join(self.parent.config.directory, model) 
Example #11
Source File: ICObenchAPIpy3.py    From data-api with MIT License 6 votes vote down vote up
def sendIcoBenchRequest(cls, queryParams=(), pathParams={}, data=()):
        hash = hmac.new(cls.icoBenchApi["ICOBENCH_PRIVATE_KEY"].encode('utf-8'), ''.encode('utf-8'), hashlib.sha384)

        dataJSON = json.dumps(data)
        hash.update(dataJSON.encode('utf-8'))
        sign = hash.digest()
        sign = base64.b64encode(sign)

        request_headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-ICObench-Key': cls.icoBenchApi["ICOBENCH_PUBLIC_KEY"],
            'X-ICObench-Sig': sign
        }

        url = cls.icoBenchApi["API_URL"];
        for val in pathParams:
            url = url + val + "/"
        if all(queryParams) and url.endswith('/'):
            url = url[:-1]
        dataJSON = json.dumps(data)

        response = requests.post(url=url, params=queryParams, data=dataJSON, headers=request_headers)
        return response.json() 
Example #12
Source File: test_nonce_generation.py    From fastecdsa with The Unlicense 6 votes vote down vote up
def test_rfc_6979(self):
        msg = 'sample'
        x = 0x09A4D6792295A7F730FC3F2B49CBC0F62E862272F
        q = 0x4000000000000000000020108A2E0CC0D99F8A5EF

        expected = 0x09744429FA741D12DE2BE8316E35E84DB9E5DF1CD
        nonce = RFC6979(msg, x, q, sha1).gen_nonce()
        self.assertTrue(nonce == expected)

        expected = 0x323E7B28BFD64E6082F5B12110AA87BC0D6A6E159
        nonce = RFC6979(msg, x, q, sha224).gen_nonce()
        self.assertTrue(nonce == expected)

        expected = 0x23AF4074C90A02B3FE61D286D5C87F425E6BDD81B
        nonce = RFC6979(msg, x, q, sha256).gen_nonce()
        self.assertTrue(nonce == expected)

        expected = 0x2132ABE0ED518487D3E4FA7FD24F8BED1F29CCFCE
        nonce = RFC6979(msg, x, q, sha384).gen_nonce()
        self.assertTrue(nonce == expected)

        expected = 0x00BBCC2F39939388FDFE841892537EC7B1FF33AA3
        nonce = RFC6979(msg, x, q, sha512).gen_nonce()
        self.assertTrue(nonce == expected) 
Example #13
Source File: ECDSA.py    From Number-Theory-Python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def define384(self):
		p = 2**384 - 2**128 - 2**96 + 2**32 - 1 # 3940...2319
		b = 27580193559959705877849011840389048093056905856361568521428707301988689241309860865136260764883745107765439761230575
		n = 39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643
		E = EllipticCurve(GF(p),[-3,b])
		E.set_order(n)  # Set the pre-computed curve order
		gx = 26247035095799689268623156744566981891852923491109213387815615900925518854738050089022388053975719786650872476732087
		gy = 8325710961489029985546751289520108179287853048861315594709205902480503199884419224438643760392947333078086511627871
		g = E.point([gx,gy])  # The basepoint
		return [E,g,n,hashlib.sha384,384]

############################################################################
# License: Freely available for use, abuse and modification
# (this is the Simplified BSD License, aka FreeBSD license)
# Copyright 2014 Robert Campbell. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#    1. Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in 
#       the documentation and/or other materials provided with the distribution.
############################################################################ 
Example #14
Source File: cert.py    From mptcp-abuse with GNU General Public License v2.0 5 votes vote down vote up
def pkcs_emsa_pkcs1_v1_5_encode(M, emLen, h): # section 9.2 of RFC 3447
    """
    Implements EMSA-PKCS1-V1_5-ENCODE() function described in Sect.
    9.2 of RFC 3447.

    Input:
       M    : message to be encode, an octet string
       emLen: intended length in octets of the encoded message, at least
              tLen + 11, where tLen is the octet length of the DER encoding
              T of a certain value computed during the encoding operation.
       h    : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
              'sha256', 'sha384'). hLen denotes the length in octets of
              the hash function output.

    Output:
       encoded message, an octet string of length emLen

    On error, None is returned.
    """
    hLen = _hashFuncParams[h][0]                             # 1)
    hFunc = _hashFuncParams[h][1]
    H = hFunc(M)
    hLeadingDigestInfo = _hashFuncParams[h][2]               # 2)
    T = hLeadingDigestInfo + H
    tLen = len(T)
    if emLen < tLen + 11:                                    # 3)
        warning("pkcs_emsa_pkcs1_v1_5_encode: intended encoded message length too short")
        return None
    PS = '\xff'*(emLen - tLen - 3)                           # 4)
    EM = '\x00' + '\x01' + PS + '\x00' + T                   # 5)
    return EM                                                # 6)


# XXX should add other pgf1 instance in a better fashion. 
Example #15
Source File: test_transport.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_hmacsha2384(self):
        """
        When L{SSHCiphers._getMAC} is called with the C{b"hmac-sha2-384"} MAC
        algorithm name it returns a tuple of (sha384 digest object, inner pad,
        outer pad, sha384 digest size) with a C{key} attribute set to the
        value of the key supplied.
        """
        self.assertGetMAC(
            b"hmac-sha2-384", sha384, digestSize=48, blockPadSize=80) 
Example #16
Source File: scikit_base.py    From dffml with MIT License 5 votes vote down vote up
def _feature_predict_hash(self):
        params = "".join(
            [
                "{}{}".format(k, v)
                for k, v in self.parent.config._asdict().items()
                if k not in ["features", "tcluster", "predict"]
            ]
        )
        return hashlib.sha384(
            "".join([params] + self.features).encode()
        ).hexdigest() 
Example #17
Source File: vw_base.py    From dffml with MIT License 5 votes vote down vote up
def _filename(self):
        return os.path.join(
            self.config.directory,
            hashlib.sha384(self.config.predict.name.encode()).hexdigest()
            + ".json",
        ) 
Example #18
Source File: hash.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
def sha384_generic_passwd(password, uppercase=False):
    """
    >>> sha384_generic_passwd(password='testpass', uppercase=False)
    '6823546e56adf46849343be991d4b1be9b432e42ed1b4bb90635a0e4b930e49b9ca007bc3e04bf0a4e0df6f1f82769bf'
    """

    retVal = sha384(password).hexdigest()

    return retVal.upper() if uppercase else retVal.lower() 
Example #19
Source File: hash.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
def sha384_generic_passwd(password, uppercase=False):
    """
    >>> sha384_generic_passwd(password='testpass', uppercase=False)
    '6823546e56adf46849343be991d4b1be9b432e42ed1b4bb90635a0e4b930e49b9ca007bc3e04bf0a4e0df6f1f82769bf'
    """

    retVal = sha384(password).hexdigest()

    return retVal.upper() if uppercase else retVal.lower() 
Example #20
Source File: test_pep247.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_sha(self):
        self.check_object(sha1, None, None)
        self.check_object(sha224, None, None)
        self.check_object(sha256, None, None)
        self.check_object(sha384, None, None)
        self.check_object(sha512, None, None) 
Example #21
Source File: encode.py    From FATE with Apache License 2.0 5 votes vote down vote up
def __compute_sha384(self, value):
        if self.base64 == 1:
            return str(base64.b64encode(hashlib.sha384(bytes(value, encoding='utf-8')).digest()), "utf-8")
        else:
            return hashlib.sha384(bytes(value, encoding='utf-8')).hexdigest() 
Example #22
Source File: tpm_abstract.py    From keylime with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hashdigest(self, payload, algorithm=None):
        if algorithm is None:
            algorithm = self.defaults['hash']

        if algorithm == Hash_Algorithms.SHA1:
            measured = hashlib.sha1(payload).hexdigest()
        elif algorithm == Hash_Algorithms.SHA256:
            measured = hashlib.sha256(payload).hexdigest()
        elif algorithm == Hash_Algorithms.SHA384:
            measured = hashlib.sha384(payload).hexdigest()
        elif algorithm == Hash_Algorithms.SHA512:
            measured = hashlib.sha512(payload).hexdigest()
        else:
            measured = None
        return measured 
Example #23
Source File: crypto.py    From keylime with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def do_hmac(key, value):
    """ Generate HMAC  """
    h = hmac.new(key, msg=None, digestmod=hashlib.sha384)
    h.update(value.encode('utf-8'))
    return h.hexdigest() 
Example #24
Source File: cert.py    From CVE-2016-6366 with MIT License 5 votes vote down vote up
def _rsassa_pkcs1_v1_5_sign(self, M, h):
        """
        Implements RSASSA-PKCS1-v1_5-SIGN() function as described in
        Sect. 8.2.1 of RFC 3447.

        Input:
           M: message to be signed, an octet string
           h: hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls'
                'sha256', 'sha384').
           
        Output:
           the signature, an octet string.
        """
        
        # 1) EMSA-PKCS1-v1_5 encoding
        k = self.modulusLen / 8
        EM = pkcs_emsa_pkcs1_v1_5_encode(M, k, h)
        if EM is None:
            warning("Key._rsassa_pkcs1_v1_5_sign(): unable to encode")
            return None

        # 2) RSA signature
        m = pkcs_os2ip(EM)                          # 2.a)
        s = self._rsasp1(m)                         # 2.b)
        S = pkcs_i2osp(s, k)                        # 2.c)

        return S                                    # 3) 
Example #25
Source File: cert.py    From CVE-2016-6366 with MIT License 5 votes vote down vote up
def pkcs_emsa_pkcs1_v1_5_encode(M, emLen, h): # section 9.2 of RFC 3447
    """
    Implements EMSA-PKCS1-V1_5-ENCODE() function described in Sect.
    9.2 of RFC 3447.

    Input:
       M    : message to be encode, an octet string
       emLen: intended length in octets of the encoded message, at least
              tLen + 11, where tLen is the octet length of the DER encoding
              T of a certain value computed during the encoding operation.
       h    : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
              'sha256', 'sha384'). hLen denotes the length in octets of
              the hash function output.

    Output:
       encoded message, an octet string of length emLen

    On error, None is returned.
    """
    hLen = _hashFuncParams[h][0]                             # 1)
    hFunc = _hashFuncParams[h][1]
    H = hFunc(M)
    hLeadingDigestInfo = _hashFuncParams[h][2]               # 2)
    T = hLeadingDigestInfo + H
    tLen = len(T)
    if emLen < tLen + 11:                                    # 3)
        warning("pkcs_emsa_pkcs1_v1_5_encode: intended encoded message length too short")
        return None
    PS = '\xff'*(emLen - tLen - 3)                           # 4)
    EM = '\x00' + '\x01' + PS + '\x00' + T                   # 5)
    return EM                                                # 6)


# XXX should add other pgf1 instance in a better fashion. 
Example #26
Source File: cert.py    From CVE-2016-6366 with MIT License 5 votes vote down vote up
def pkcs_mgf1(mgfSeed, maskLen, h):
    """
    Implements generic MGF1 Mask Generation function as described in
    Appendix B.2.1 of RFC 3447. The hash function is passed by name.
    valid values are 'md2', 'md4', 'md5', 'sha1', 'tls, 'sha256',
    'sha384' and 'sha512'. Returns None on error.

    Input:
       mgfSeed: seed from which mask is generated, an octet string
       maskLen: intended length in octets of the mask, at most 2^32 * hLen
                hLen (see below)
       h      : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
                'sha256', 'sha384'). hLen denotes the length in octets of
                the hash function output.

    Output:
       an octet string of length maskLen
    """

    # steps are those of Appendix B.2.1
    if not _hashFuncParams.has_key(h):
        warning("pkcs_mgf1: invalid hash (%s) provided")
        return None
    hLen = _hashFuncParams[h][0]
    hFunc = _hashFuncParams[h][1]
    if maskLen > 2**32 * hLen:                               # 1)
        warning("pkcs_mgf1: maskLen > 2**32 * hLen")         
        return None
    T = ""                                                   # 2)
    maxCounter = math.ceil(float(maskLen) / float(hLen))     # 3)
    counter = 0
    while counter < maxCounter:
        C = pkcs_i2osp(counter, 4)
        T += hFunc(mgfSeed + C)
        counter += 1
    return T[:maskLen] 
Example #27
Source File: cert.py    From smod-1 with GNU General Public License v2.0 5 votes vote down vote up
def _rsassa_pkcs1_v1_5_sign(self, M, h):
        """
        Implements RSASSA-PKCS1-v1_5-SIGN() function as described in
        Sect. 8.2.1 of RFC 3447.

        Input:
           M: message to be signed, an octet string
           h: hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls'
                'sha256', 'sha384').
           
        Output:
           the signature, an octet string.
        """
        
        # 1) EMSA-PKCS1-v1_5 encoding
        k = self.modulusLen / 8
        EM = pkcs_emsa_pkcs1_v1_5_encode(M, k, h)
        if EM is None:
            warning("Key._rsassa_pkcs1_v1_5_sign(): unable to encode")
            return None

        # 2) RSA signature
        m = pkcs_os2ip(EM)                          # 2.a)
        s = self._rsasp1(m)                         # 2.b)
        S = pkcs_i2osp(s, k)                        # 2.c)

        return S                                    # 3) 
Example #28
Source File: cert.py    From smod-1 with GNU General Public License v2.0 5 votes vote down vote up
def pkcs_emsa_pkcs1_v1_5_encode(M, emLen, h): # section 9.2 of RFC 3447
    """
    Implements EMSA-PKCS1-V1_5-ENCODE() function described in Sect.
    9.2 of RFC 3447.

    Input:
       M    : message to be encode, an octet string
       emLen: intended length in octets of the encoded message, at least
              tLen + 11, where tLen is the octet length of the DER encoding
              T of a certain value computed during the encoding operation.
       h    : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
              'sha256', 'sha384'). hLen denotes the length in octets of
              the hash function output.

    Output:
       encoded message, an octet string of length emLen

    On error, None is returned.
    """
    hLen = _hashFuncParams[h][0]                             # 1)
    hFunc = _hashFuncParams[h][1]
    H = hFunc(M)
    hLeadingDigestInfo = _hashFuncParams[h][2]               # 2)
    T = hLeadingDigestInfo + H
    tLen = len(T)
    if emLen < tLen + 11:                                    # 3)
        warning("pkcs_emsa_pkcs1_v1_5_encode: intended encoded message length too short")
        return None
    PS = '\xff'*(emLen - tLen - 3)                           # 4)
    EM = '\x00' + '\x01' + PS + '\x00' + T                   # 5)
    return EM                                                # 6)


# XXX should add other pgf1 instance in a better fashion. 
Example #29
Source File: cert.py    From smod-1 with GNU General Public License v2.0 5 votes vote down vote up
def pkcs_mgf1(mgfSeed, maskLen, h):
    """
    Implements generic MGF1 Mask Generation function as described in
    Appendix B.2.1 of RFC 3447. The hash function is passed by name.
    valid values are 'md2', 'md4', 'md5', 'sha1', 'tls, 'sha256',
    'sha384' and 'sha512'. Returns None on error.

    Input:
       mgfSeed: seed from which mask is generated, an octet string
       maskLen: intended length in octets of the mask, at most 2^32 * hLen
                hLen (see below)
       h      : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
                'sha256', 'sha384'). hLen denotes the length in octets of
                the hash function output.

    Output:
       an octet string of length maskLen
    """

    # steps are those of Appendix B.2.1
    if not _hashFuncParams.has_key(h):
        warning("pkcs_mgf1: invalid hash (%s) provided")
        return None
    hLen = _hashFuncParams[h][0]
    hFunc = _hashFuncParams[h][1]
    if maskLen > 2**32 * hLen:                               # 1)
        warning("pkcs_mgf1: maskLen > 2**32 * hLen")         
        return None
    T = ""                                                   # 2)
    maxCounter = math.ceil(float(maskLen) / float(hLen))     # 3)
    counter = 0
    while counter < maxCounter:
        C = pkcs_i2osp(counter, 4)
        T += hFunc(mgfSeed + C)
        counter += 1
    return T[:maskLen] 
Example #30
Source File: signing.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def verify_signature_pubkey(data, signature, pubkey):
    """
    Verify a signature.

    If the signature is valid, returns True. If the signature is invalid, raise
    an exception explaining why.
    """
    # Data must be encoded as bytes
    if isinstance(data, str):
        data = data.encode()

    # Content signature implicitly adds a prefix to signed data
    data = b"Content-Signature:\x00" + data

    # fastecdsa expects ASCII armored keys, but ours is unarmored. Add the
    # armor before passing the key to the library.
    EC_PUBLIC_HEADER = "-----BEGIN PUBLIC KEY-----"
    EC_PUBLIC_FOOTER = "-----END PUBLIC KEY-----"
    verifying_pubkey = PEMEncoder.decode_public_key(
        "\n".join([EC_PUBLIC_HEADER, pubkey, EC_PUBLIC_FOOTER])
    )

    try:
        signature = base64.urlsafe_b64decode(signature)
        signature = ecdsa.util.sigdecode_string(signature, order=ecdsa.curves.NIST384p.order)
    except binascii.Error as e:
        if BASE64_WRONG_LENGTH_RE.match(e.args[0]):
            raise WrongSignatureSize("Base64 encoded signature was not a multiple of 4")
        else:
            raise
    except ecdsa.util.MalformedSignature:
        raise WrongSignatureSize()

    verified = fastecdsa.ecdsa.verify(
        signature, data, verifying_pubkey, curve=fastecdsa.curve.P384, hashfunc=hashlib.sha384
    )

    if not verified:
        raise SignatureDoesNotMatch()

    return True