Python hmac.digest() Examples

The following are 14 code examples of hmac.digest(). 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 hmac , or try the search function .
Example #1
Source File: bip32.py    From btclib with MIT License 6 votes vote down vote up
def rootxprv_from_seed(seed: Octets, version: Optional[Octets] = None) -> bytes:
    """Return BIP32 root master extended private key from seed."""

    seed = bytes_from_octets(seed)
    hd = hmac.digest(b"Bitcoin seed", seed, "sha512")
    k = b"\x00" + hd[:32]
    if version is None:
        v = NETWORKS["mainnet"]["bip32_prv"]
    else:
        v = bytes_from_octets(version)
    if v not in _XPRV_VERSIONS_ALL:
        raise ValueError(f"unknown extended private key version {v!r}")

    d: BIP32KeyDict = {
        "version": v,
        "depth": 0,
        "parent_fingerprint": b"\x00\x00\x00\x00",
        "index": b"\x00\x00\x00\x00",
        "chain_code": hd[32:],
        "key": k,
    }
    return serialize(d) 
Example #2
Source File: auth.py    From aws-extender with MIT License 6 votes vote down vote up
def add_auth(self, req, **kwargs):
        """
        Add AWS3 authentication to a request.

        :type req: :class`boto.connection.HTTPRequest`
        :param req: The HTTPRequest object.
        """
        # This could be a retry.  Make sure the previous
        # authorization header is removed first.
        if 'X-Amzn-Authorization' in req.headers:
            del req.headers['X-Amzn-Authorization']
        req.headers['X-Amz-Date'] = formatdate(usegmt=True)
        if self._provider.security_token:
            req.headers['X-Amz-Security-Token'] = self._provider.security_token
        string_to_sign, headers_to_sign = self.string_to_sign(req)
        boto.log.debug('StringToSign:\n%s' % string_to_sign)
        hash_value = sha256(string_to_sign.encode('utf-8')).digest()
        b64_hmac = self.sign_string(hash_value)
        s = "AWS3 AWSAccessKeyId=%s," % self._provider.access_key
        s += "Algorithm=%s," % self.algorithm()
        s += "SignedHeaders=%s," % ';'.join(headers_to_sign)
        s += "Signature=%s" % b64_hmac
        req.headers['X-Amzn-Authorization'] = s 
Example #3
Source File: auth.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _calc_signature(self, params, verb, path, server_name):
        boto.log.debug('using _calc_signature_2')
        string_to_sign = '%s\n%s\n%s\n' % (verb, server_name.lower(), path)
        if self._hmac_256:
            hmac = self._hmac_256.copy()
            params['SignatureMethod'] = 'HmacSHA256'
        else:
            hmac = self._hmac.copy()
            params['SignatureMethod'] = 'HmacSHA1'
        keys = params.keys()
        keys.sort()
        pairs = []
        for key in keys:
            val = boto.utils.get_utf8_value(params[key])
            pairs.append(urllib.quote(key, safe='') + '=' +
                         urllib.quote(val, safe='-_~'))
        qs = '&'.join(pairs)
        boto.log.debug('query string: %s' % qs)
        string_to_sign += qs
        boto.log.debug('string_to_sign: %s' % string_to_sign)
        hmac.update(string_to_sign)
        b64 = base64.b64encode(hmac.digest())
        boto.log.debug('len(b64)=%d' % len(b64))
        boto.log.debug('base64 encoded digest: %s' % b64)
        return (qs, b64) 
Example #4
Source File: adapters.py    From ptadapter with GNU General Public License v3.0 5 votes vote down vote up
def hash(self, msg: bytes) -> bytes:
        return hmac.digest(self._cookie, msg, self.digest) 
Example #5
Source File: bip32.py    From btclib with MIT License 5 votes vote down vote up
def _ckd(d: ExtendedBIP32KeyDict, index: bytes) -> None:

    # d is a prvkey
    if d["key"][0] == 0:
        d["depth"] += 1
        Pbytes = bytes_from_point(mult(d["q"]))
        d["parent_fingerprint"] = hash160(Pbytes)[:4]
        d["index"] = index
        if index[0] >= 0x80:  # hardened derivation
            h = hmac.digest(d["chain_code"], d["key"] + index, "sha512")
        else:  # normal derivation
            h = hmac.digest(d["chain_code"], Pbytes + index, "sha512")
        d["chain_code"] = h[32:]
        offset = int.from_bytes(h[:32], byteorder="big")
        d["q"] = (d["q"] + offset) % ec.n
        d["key"] = b"\x00" + d["q"].to_bytes(32, "big")
        d["Q"] = INF
    # d is a pubkey
    else:
        if index[0] >= 0x80:
            raise ValueError("hardened derivation from pubkey is impossible")
        d["depth"] += 1
        d["parent_fingerprint"] = hash160(d["key"])[:4]
        d["index"] = index
        h = hmac.digest(d["chain_code"], d["key"] + index, "sha512")
        d["chain_code"] = h[32:]
        offset = int.from_bytes(h[:32], byteorder="big")
        Offset = mult(offset)
        d["Q"] = ec.add(d["Q"], Offset)
        d["key"] = bytes_from_point(d["Q"])
        d["q"] = 0 
Example #6
Source File: bip32.py    From btclib with MIT License 5 votes vote down vote up
def crack_prvkey(parent_xpub: BIP32Key, child_xprv: BIP32Key) -> bytes:

    if isinstance(parent_xpub, dict):
        p = copy.copy(parent_xpub)
    else:
        p = deserialize(parent_xpub)

    if p["key"][0] not in (2, 3):
        m = "extended parent key is not a public key: "
        m += f"{serialize(p).decode()}"
        raise ValueError(m)

    if isinstance(child_xprv, dict):
        c = child_xprv
    else:
        c = deserialize(child_xprv)
    if c["key"][0] != 0:
        m = f"extended child key is not a private key: {serialize(c).decode()}"
        raise ValueError(m)

    # check depth
    if c["depth"] != p["depth"] + 1:
        raise ValueError("not a parent's child: wrong depths")

    # check fingerprint
    if c["parent_fingerprint"] != hash160(p["key"])[:4]:
        raise ValueError("not a parent's child: wrong parent fingerprint")

    # check normal derivation
    if c["index"][0] >= 0x80:
        raise ValueError("hardened child derivation")

    p["version"] = c["version"]

    h = hmac.digest(p["chain_code"], p["key"] + c["index"], "sha512")
    child_q = int.from_bytes(c["key"][1:], byteorder="big")
    offset = int.from_bytes(h[:32], byteorder="big")
    parent_q = (child_q - offset) % ec.n
    p["key"] = b"\x00" + parent_q.to_bytes(32, byteorder="big")

    return serialize(p) 
Example #7
Source File: hotp.py    From authenticator with MIT License 5 votes vote down vote up
def generate_hmac(self, secret_key, counter):
        """Create a 160-bit HMAC from secret and counter.

        Args:
            secret_key: a byte string (recommended minimum 20 bytes) that is
                the shared secret between the client and server.
            counter: an integer value represented in an 8-byte string with
                the most significant byte first and least significant byte
                last

        Returns:
            The HMAC digest; a byte string, 20 bytes long.

        Raises:
            TypeError: if the counter and secret are not byte strings.
            ValueError: if the counter is not 8 bytes long.

        """
        from hashlib import sha1
        import hmac

        if not isinstance(secret_key, bytes):
            raise TypeError('secret_key must be a byte string')
        if not isinstance(counter, bytes):
            raise TypeError('counter must be a byte string')
        if (8 != len(counter)):
            raise ValueError('counter must be 8 bytes')

        hmac = hmac.new(secret_key, counter, sha1)
        hash = hmac.digest()
        return hash 
Example #8
Source File: auth.py    From aws-extender with MIT License 5 votes vote down vote up
def sign_string(self, string_to_sign):
        new_hmac = self._get_hmac()
        new_hmac.update(string_to_sign.encode('utf-8'))
        return encodebytes(new_hmac.digest()).decode('utf-8').strip() 
Example #9
Source File: auth.py    From aws-extender with MIT License 5 votes vote down vote up
def _sign(self, key, msg, hex=False):
        if not isinstance(key, bytes):
            key = key.encode('utf-8')

        if hex:
            sig = hmac.new(key, msg.encode('utf-8'), sha256).hexdigest()
        else:
            sig = hmac.new(key, msg.encode('utf-8'), sha256).digest()
        return sig 
Example #10
Source File: auth.py    From aws-extender with MIT License 5 votes vote down vote up
def _calc_signature(self, params, *args):
        boto.log.debug('using _calc_signature_0')
        hmac = self._get_hmac()
        s = params['Action'] + params['Timestamp']
        hmac.update(s.encode('utf-8'))
        keys = params.keys()
        keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
        pairs = []
        for key in keys:
            val = boto.utils.get_utf8_value(params[key])
            pairs.append(key + '=' + urllib.parse.quote(val))
        qs = '&'.join(pairs)
        return (qs, base64.b64encode(hmac.digest())) 
Example #11
Source File: auth.py    From aws-extender with MIT License 5 votes vote down vote up
def _calc_signature(self, params, *args):
        boto.log.debug('using _calc_signature_1')
        hmac = self._get_hmac()
        keys = list(params.keys())
        keys.sort(key=lambda x: x.lower())
        pairs = []
        for key in keys:
            hmac.update(key.encode('utf-8'))
            val = boto.utils.get_utf8_value(params[key])
            hmac.update(val)
            pairs.append(key + '=' + urllib.parse.quote(val))
        qs = '&'.join(pairs)
        return (qs, base64.b64encode(hmac.digest())) 
Example #12
Source File: auth.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sign_string(self, string_to_sign):
        boto.log.debug('Canonical: %s' % string_to_sign)
        if self._hmac_256:
            hmac = self._hmac_256.copy()
        else:
            hmac = self._hmac.copy()
        hmac.update(string_to_sign)
        return base64.encodestring(hmac.digest()).strip() 
Example #13
Source File: auth.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _calc_signature(self, params, *args):
        boto.log.debug('using _calc_signature_0')
        hmac = self._hmac.copy()
        s = params['Action'] + params['Timestamp']
        hmac.update(s)
        keys = params.keys()
        keys.sort(cmp = lambda x, y: cmp(x.lower(), y.lower()))
        pairs = []
        for key in keys:
            val = boto.utils.get_utf8_value(params[key])
            pairs.append(key + '=' + urllib.quote(val))
        qs = '&'.join(pairs)
        return (qs, base64.b64encode(hmac.digest())) 
Example #14
Source File: auth.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _calc_signature(self, params, *args):
        boto.log.debug('using _calc_signature_1')
        hmac = self._hmac.copy()
        keys = params.keys()
        keys.sort(cmp = lambda x, y: cmp(x.lower(), y.lower()))
        pairs = []
        for key in keys:
            hmac.update(key)
            val = boto.utils.get_utf8_value(params[key])
            hmac.update(val)
            pairs.append(key + '=' + urllib.quote(val))
        qs = '&'.join(pairs)
        return (qs, base64.b64encode(hmac.digest()))