Python hashlib 模块,sha384() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用hashlib.sha384()

项目:PyPPSPP    作者:justas-    | 项目源码 | 文件源码
def GetIntegrity(self, data):
        """Calculate the integirty value of given data using remote peers hash"""
        if self.hash_type == None:
            return None
        elif self.hash_type == 0:
            # SHA-1
            return hashlib.sha1(data).digest()
        elif self.hash_type == 1:
            # SHA-224
            return hashlib.sha224(data).digest()
        elif self.hash_type == 2:
            # SHA-256
            return hashlib.sha256(data).digest()
        elif self.hash_type == 3:
            # SHA-384
            return hashlib.sha384(data).digest()
        elif self.hash_type == 4:
            # SHA-512
            return hashlib.sha512(data).digest()
        else:
            return None
项目:nautilus_scripts    作者:SergKolo    | 项目源码 | 文件源码
def get_hashsums(file_path):
    hash_sums = od()
    hash_sums['md5sum'] = hashlib.md5()
    hash_sums['sha1sum'] = hashlib.sha1()
    hash_sums['sha224sum'] = hashlib.sha224()
    hash_sums['sha256sum'] = hashlib.sha256()
    hash_sums['sha384sum'] = hashlib.sha384()
    hash_sums['sha512sum'] = hashlib.sha512()

    with open(file_path, 'rb') as fd:
        data_chunk = fd.read(1024)
        while data_chunk:
              for hashsum in hash_sums.keys():
                  hash_sums[hashsum].update(data_chunk)
              data_chunk = fd.read(1024)

    results = od()
    for key,value in hash_sums.items():
         results[key] = value.hexdigest()         
    return results
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def get_digest(value):
    """Return a hashlib digest algorithm from a string."""
    if not isinstance(value, str):
        return value
    value = value.lower()
    if value == "md5":
        return md5
    elif value == "sha1":
        return sha1
    elif value == "sha224":
        return sha224
    elif value == "sha256":
        return sha256
    elif value == "sha384":
        return sha384
    elif value == "sha512":
        return sha512
    else:
        raise ValueError("Invalid digest algorithm: %s" % value)
项目:bitex    作者:nlsdfnbch    | 项目源码 | 文件源码
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}
项目:bitex    作者:nlsdfnbch    | 项目源码 | 文件源码
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}
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def get_digest(value):
    """
    Returns a hashlib digest algorithm from a string
    """
    if not isinstance(value, str):
        return value
    value = value.lower()
    if value == "md5":
        return md5
    elif value == "sha1":
        return sha1
    elif value == "sha224":
        return sha224
    elif value == "sha256":
        return sha256
    elif value == "sha384":
        return sha384
    elif value == "sha512":
        return sha512
    else:
        raise ValueError("Invalid digest algorithm: %s" % value)
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def get_digest(value):
    """
    Returns a hashlib digest algorithm from a string
    """
    if not isinstance(value, str):
        return value
    value = value.lower()
    if value == "md5":
        return hashlib.md5
    elif value == "sha1":
        return hashlib.sha1
    elif value == "sha224":
        return hashlib.sha224
    elif value == "sha256":
        return hashlib.sha256
    elif value == "sha384":
        return hashlib.sha384
    elif value == "sha512":
        return hashlib.sha512
    else:
        raise ValueError("Invalid digest algorithm: %s" % value)
项目:bitex    作者:nlsdfnbch    | 项目源码 | 文件源码
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}
项目:geminipy    作者:geminipy    | 项目源码 | 文件源码
def prepare(self, params):
        """
        Prepare, return the required HTTP headers.

        Base 64 encode the parameters, sign it with the secret key,
        create the HTTP headers, return the whole payload.

        Arguments:
        params -- a dictionary of parameters
        """
        jsonparams = json.dumps(params)
        payload = base64.b64encode(jsonparams.encode())
        signature = hmac.new(self.secret_key.encode(), payload,
                             hashlib.sha384).hexdigest()

        return {'X-GEMINI-APIKEY': self.api_key,
                'X-GEMINI-PAYLOAD': payload,
                'X-GEMINI-SIGNATURE': signature}
项目:trading-api-wrappers    作者:delta575    | 项目源码 | 文件源码
def _sign_payload(self, method, path, params=None, payload=None):

        route = build_route(path, params)
        nonce = gen_nonce()

        if payload:
            j = json.dumps(payload).encode('utf-8')
            encoded_body = base64.standard_b64encode(j).decode('utf-8')
            string = method + ' ' + route + ' ' + encoded_body + ' ' + nonce
        else:
            string = method + ' ' + route + ' ' + nonce

        h = hmac.new(key=self.SECRET.encode('utf-8'),
                     msg=string.encode('utf-8'),
                     digestmod=hashlib.sha384)

        signature = h.hexdigest()

        return {
            'X-SBTC-APIKEY': self.KEY,
            'X-SBTC-NONCE': nonce,
            'X-SBTC-SIGNATURE': signature,
            'Content-Type': 'application/json',
        }
项目:trading-api-wrappers    作者:delta575    | 项目源码 | 文件源码
def _sign_payload(self, path, payload=None):

        timestamp = str(int(time.time()))
        msg = timestamp + path

        if payload:
            for value in [str(payload[k]) for k in sorted(payload.keys())]:
                msg += value

        signature = hmac.new(key=self.SECRET.encode('utf-8'),
                             msg=msg.encode('utf-8'),
                             digestmod=hashlib.sha384).hexdigest()

        # Request fails with 'get_requests_not_allowed' when
        # 'Content-Type': 'application/json' is present
        return {
            'X-MKT-APIKEY': self.KEY,
            'X-MKT-SIGNATURE': signature,
            'X-MKT-TIMESTAMP': timestamp,
        }

    # Request fails with 'get_requests_not_allowed' when
    # json.dumps()' is used
项目:Problematica-public    作者:TechMaz    | 项目源码 | 文件源码
def get_digest(value):
    """
    Returns a hashlib digest algorithm from a string
    """
    if not isinstance(value, str):
        return value
    value = value.lower()
    if value == "md5":
        return md5
    elif value == "sha1":
        return sha1
    elif value == "sha224":
        return sha224
    elif value == "sha256":
        return sha256
    elif value == "sha384":
        return sha384
    elif value == "sha512":
        return sha512
    else:
        raise ValueError("Invalid digest algorithm: %s" % value)
项目:fastecdsa    作者:AntonKueltz    | 项目源码 | 文件源码
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)
项目:rekall-agent-server    作者:rekall-innovations    | 项目源码 | 文件源码
def get_digest(value):
    """Return a hashlib digest algorithm from a string."""
    if not isinstance(value, str):
        return value
    value = value.lower()
    if value == "md5":
        return md5
    elif value == "sha1":
        return sha1
    elif value == "sha224":
        return sha224
    elif value == "sha256":
        return sha256
    elif value == "sha384":
        return sha384
    elif value == "sha512":
        return sha512
    else:
        raise ValueError("Invalid digest algorithm: %s" % value)
项目:zual    作者:ninadmhatre    | 项目源码 | 文件源码
def authenticate(u, p):
    if u and p:
        if u in (current_app.config['ADMIN_MAIL'],):
            p_salt = p + current_app.config["SECRET_KEY"]
            e_salt = chaabi + current_app.config["SECRET_KEY"]

            d = hashlib.sha384()
            e = hashlib.sha384()

            d.update(p_salt.encode())
            e.update(e_salt.encode())
            return d.hexdigest() == e.hexdigest()
        else:
            return False
    else:
        return False
项目:web3py    作者:web2py    | 项目源码 | 文件源码
def get_digest(value):
    """
    Returns a hashlib digest algorithm from a string
    """
    if not isinstance(value, str):
        return value
    value = value.lower()
    if value == "md5":
        return md5
    elif value == "sha1":
        return sha1
    elif value == "sha224":
        return sha224
    elif value == "sha256":
        return sha256
    elif value == "sha384":
        return sha384
    elif value == "sha512":
        return sha512
    else:
        raise ValueError("Invalid digest algorithm: %s" % value)
项目:reflector-cluster    作者:lbryio    | 项目源码 | 文件源码
def main():
    redis_conn = Redis()
    q = Queue(connection=redis_conn)

    if not os.path.isdir(BLOB_DIR):
        os.mkdir(BLOB_DIR)

    try:
        num_blobs = int(sys.argv[1])
    except IndexError:
        num_blobs = 1

    blobs = []

    for i in range(num_blobs):
        blob_contents = os.urandom(BLOB_SIZE)
        blob_hash = hashlib.sha384(blob_contents).hexdigest()
        blob_path = os.path.join(BLOB_DIR, blob_hash)
        with open(blob_path, 'wb') as f:
            f.write(blob_contents)
        blobs.append(blob_hash)

    for blob_hash in blobs:
        q.enqueue(process_blob, blob_hash, 1)
项目:Dagon    作者:Ekultek    | 项目源码 | 文件源码
def sha384(string, salt=None, front=False, back=False, **placeholder):
    """
      Create an SHA384 hash from a given string

      > :param string:
      > :return:

      Example:
        >>> sha384("test")
        768412320f7b0aa5812fce428dc4706b3cae50e02a64caa16a782249bfe8efc4b7ef1ccb126255d196047dfedf17a0a9
    """
    if type(string) is unicode:
        string = lib.settings.force_encoding(string)
        if type(string) is unicode:
            string = lib.settings.force_encoding(string)
    obj = hashlib.sha384()
    if salt is not None and front and not back:
        obj.update(salt + string)
    elif salt is not None and back and not front:
        obj.update(string + salt)
    else:
        obj.update(string)
    return obj.hexdigest()
项目:python-surbtc-api    作者:delta575    | 项目源码 | 文件源码
def _sign_payload(self, method, path, params=None, payload=None):

        route = build_route(path, params)
        nonce = gen_nonce()

        if payload:
            j = json.dumps(payload).encode('utf-8')
            encoded_body = base64.standard_b64encode(j).decode('utf-8')
            string = method + ' ' + route + ' ' + encoded_body + ' ' + nonce
        else:
            string = method + ' ' + route + ' ' + nonce

        h = hmac.new(key=self.SECRET.encode('utf-8'),
                     msg=string.encode('utf-8'),
                     digestmod=hashlib.sha384)

        signature = h.hexdigest()

        return {
            'X-SBTC-APIKEY': self.KEY,
            'X-SBTC-NONCE': nonce,
            'X-SBTC-SIGNATURE': signature,
            'Content-Type': 'application/json',
        }
项目:slugiot-client    作者:slugiot    | 项目源码 | 文件源码
def get_digest(value):
    """
    Returns a hashlib digest algorithm from a string
    """
    if not isinstance(value, str):
        return value
    value = value.lower()
    if value == "md5":
        return md5
    elif value == "sha1":
        return sha1
    elif value == "sha224":
        return sha224
    elif value == "sha256":
        return sha256
    elif value == "sha384":
        return sha384
    elif value == "sha512":
        return sha512
    else:
        raise ValueError("Invalid digest algorithm: %s" % value)
项目:00scanner    作者:xiaoqin00    | 项目源码 | 文件源码
def hash(self, method="md5"):
        '''
        ??hash??
        '''
        content = open(self._fileName,"rb").read(self._MAXSIZE)
        if method == "md5":
            return hashlib.md5(content).hexdigest()
        if method == "sha" or method == "sha1":
            return hashlib.sha1(content).hexdigest()
        if method == "sha224":
            return hashlib.sha224(content).hexdigest()
        if method == "sha256":
            return hashlib.sha256(content).hexdigest()
        if method == "sha384":
            return hashlib.sha384(content).hexdigest()
        if method == "sha512":
            return hashlib.sha512(content).hexdigest()
        if method == "crc32":
            return "{0:x}".format(binascii.crc32(content) & 0xffffffff)
项目:sv3c_decrypt    作者:mon    | 项目源码 | 文件源码
def generate_keys(path):
    salt = '5dIFp5Nb8n1kyPRSU8dKGyhJHx317PA3'
    keyOffsets = [8, 25, 22, 47, 24,  5, 16,  9, 33,  3, 45,  1, 30, 34, 37, 36,
                  15, 39, 11, 14, 23, 29, 26, 40, 31,  7, 13, 38, 27, 17, 12, 21]
    ivOffsets  = [28, 19, 2,  46, 4,  20, 18, 41, 32, 43, 0,  6,  44, 10, 35, 42]
    filename = basename(path)

    toHash = salt + filename + salt + filename
    hashed = bytes(hashlib.sha384(toHash.encode('ASCII')).digest())
    key = [0] * 32
    for offset, i in zip(keyOffsets, range(32)):
        key[i] = hashed[offset]

    iv = bytearray([0]*16)
    for offset, i in zip(ivOffsets, range(16)):
        iv[i] = hashed[offset]
    iv = bytes(iv)

    iv = unpack('<Q', iv[:8])[0] | (unpack('<Q', iv[8:])[0] << 64)

    return key, iv
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def encode_sha384(self, *, message : str):
        '''Generate SHA-384 hash'''
        await self.bot.embed_reply(hashlib.sha384(message.encode("utf-8")).hexdigest())
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def sha384(hash): 
        climax = hashlib.sha384(hash).hexdigest() 
        return climax
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def toptobottom(crack): 
    i = 0 
    while i < (len(asshole)/2): 
        if len(crack) == 32: 
            if crack == md5(asshole[i]): 
                print "\n\t[p1] 3===D  passwd is = %s\n"%asshole[i] 
                break 
        elif len(crack) == 40: 
            if crack == sha1(asshole[i]): 
                print "\n\t[p1] 3===D  passwd is = %s\n"%asshole[i] 
                break 
                elif len(crack) == 56: 
                        if crack == sha224(asshole[i]): 
                                print "\n\t[p1] 3===D  passwd is = %s\n"%asshole[i] 
                                break 
                elif len(crack) == 64: 
                        if crack == sha256(asshole[i]): 
                                print "\n\t[p1] 3===D  passwd is = %s\n"%asshole[i] 
                                break 
                elif len(crack) == 96: 
                        if crack == sha384(asshole[i]): 
                                print "\n\t[p1] 3===D  passwd is = %s\n"%asshole[i] 
                                break 
                elif len(crack) == 128: 
                        if crack == sha512(asshole[i]): 
                                print "\n\t[p1] 3===D  passwd is = %s\n"%asshole[i] 
                                break 
                else: 
            print "[-] not support hash" 
            sys.exit() 
        i += 1
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def bottomtotop(crack): 
    k = 0 
    big = len(asshole) - len(asshole)/2 
    while k < (big): 
        if len(crack) == 32: 
            if crack == md5(asshole[-k]): 
                print "\n\t[p2] 3===D  passwd is = %s\n"%asshole[-k] 
                break 
        elif len(crack) == 40: 
                        if crack == sha1(asshole[-k]): 
                                print "\n\t[p2] 3===D  passwd is = %s\n"%asshole[-k] 
                                break 
                elif len(crack) == 56: 
                        if crack == sha224(asshole[-k]): 
                                print "\n\t[p2] 3===D  passwd is = %s\n"%asshole[-k] 
                                break 
                elif len(crack) == 64: 
                        if crack == sha256(asshole[-k]): 
                                print "\n\t[p2] 3===D  passwd is = %s\n"%asshole[-k] 
                                break 
                elif len(crack) == 96: 
                        if crack == sha384(asshole[-k]): 
                                print "\n\t[p2] 3===D  passwd is = %s\n"%asshole[-k] 
                                break 
                elif len(crack) == 128: 
                        if crack == sha512(asshole[-k]): 
                                print "\n\t[p2] 3===D  passwd is = %s\n"%asshole[-k] 
                                break 
        else: 
            sys.exit() 
        k += 1
项目:CyberScan    作者:medbenali    | 项目源码 | 文件源码
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]
项目:CyberScan    作者:medbenali    | 项目源码 | 文件源码
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.
项目:CyberScan    作者:medbenali    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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]
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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.
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def _setup():
    global _hashes
    _hashes = {}
    try:
        import hashlib
        _hashes['MD5'] = hashlib.md5
        _hashes['SHA1'] = hashlib.sha1
        _hashes['SHA224'] = hashlib.sha224
        _hashes['SHA256'] = hashlib.sha256
        if sys.hexversion >= 0x02050200:
            _hashes['SHA384'] = hashlib.sha384
            _hashes['SHA512'] = hashlib.sha512
        else:
            _hashes['SHA384'] = _need_later_python('SHA384')
            _hashes['SHA512'] = _need_later_python('SHA512')

        if sys.hexversion < 0x02050000:
            # hashlib doesn't conform to PEP 247: API for
            # Cryptographic Hash Functions, which hmac before python
            # 2.5 requires, so add the necessary items.
            class HashlibWrapper:
                def __init__(self, basehash):
                    self.basehash = basehash
                    self.digest_size = self.basehash().digest_size

                def new(self, *args, **kwargs):
                    return self.basehash(*args, **kwargs)

            for name in _hashes:
                _hashes[name] = HashlibWrapper(_hashes[name])

    except ImportError:
        import md5, sha
        _hashes['MD5'] =  md5
        _hashes['SHA1'] = sha
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def _setup():
    global _hashes
    _hashes = {}
    try:
        import hashlib
        _hashes['MD5'] = hashlib.md5
        _hashes['SHA1'] = hashlib.sha1
        _hashes['SHA224'] = hashlib.sha224
        _hashes['SHA256'] = hashlib.sha256
        if sys.hexversion >= 0x02050200:
            _hashes['SHA384'] = hashlib.sha384
            _hashes['SHA512'] = hashlib.sha512
        else:
            _hashes['SHA384'] = _need_later_python('SHA384')
            _hashes['SHA512'] = _need_later_python('SHA512')

        if sys.hexversion < 0x02050000:
            # hashlib doesn't conform to PEP 247: API for
            # Cryptographic Hash Functions, which hmac before python
            # 2.5 requires, so add the necessary items.
            class HashlibWrapper:
                def __init__(self, basehash):
                    self.basehash = basehash
                    self.digest_size = self.basehash().digest_size

                def new(self, *args, **kwargs):
                    return self.basehash(*args, **kwargs)

            for name in _hashes:
                _hashes[name] = HashlibWrapper(_hashes[name])

    except ImportError:
        import md5, sha
        _hashes['MD5'] =  md5
        _hashes['SHA1'] = sha
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def _commoncrypto_hashlib_to_crypto_map_get(hashfunc):
    hashlib_to_crypto_map = {hashlib.sha1: 1,
                             hashlib.sha224: 2,
                             hashlib.sha256: 3,
                             hashlib.sha384: 4,
                             hashlib.sha512: 5}
    crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc)
    if crypto_hashfunc is None:
        raise ValueError('Unkwnown digest %s' % hashfunc)
    return crypto_hashfunc
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def _openssl_hashlib_to_crypto_map_get(hashfunc):
    hashlib_to_crypto_map = {hashlib.md5: crypto.EVP_md5,
                                 hashlib.sha1: crypto.EVP_sha1,
                                 hashlib.sha256: crypto.EVP_sha256,
                                 hashlib.sha224: crypto.EVP_sha224,
                                 hashlib.sha384: crypto.EVP_sha384,
                                 hashlib.sha512: crypto.EVP_sha512}
    crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc)
    if crypto_hashfunc is None:
        raise ValueError('Unkwnown digest %s' % hashfunc)
    crypto_hashfunc.restype = ctypes.c_void_p
    return crypto_hashfunc()
项目:CVE-2016-6366    作者:RiskSense-Ops    | 项目源码 | 文件源码
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]
项目:CVE-2016-6366    作者:RiskSense-Ops    | 项目源码 | 文件源码
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.
项目:CVE-2016-6366    作者:RiskSense-Ops    | 项目源码 | 文件源码
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)
项目:storj-python-sdk    作者:Storj    | 项目源码 | 文件源码
def _calculate_hmac(self, base_string, key):
        """HMAC hash calculation and returning
        the results in dictionary collection.

        Args:
            base_string (): .
            key (): .
        """
        hmacs = dict()
        # --- MD5 ---
        hashed = hmac.new(key, base_string, hashlib.md5)
        hmac_md5 = hashed.digest().encode('base64').rstrip('\n')
        hmacs['MD5'] = hmac_md5
        # --- SHA-1 ---
        hashed = hmac.new(key, base_string, hashlib.sha1)
        hmac_sha1 = hashed.digest().encode('base64').rstrip('\n')
        hmacs['SHA-1'] = hmac_sha1
        # --- SHA-224 ---
        hashed = hmac.new(key, base_string, hashlib.sha224)
        hmac_sha224 = hashed.digest().encode('base64').rstrip('\n')
        hmacs['SHA-224'] = hmac_sha224
        # --- SHA-256 ---
        hashed = hmac.new(key, base_string, hashlib.sha256)
        hmac_sha256 = hashed.digest().encode('base64').rstrip('\n')
        hmacs['SHA-256'] = hmac_sha256
        # --- SHA-384 ---
        hashed = hmac.new(key, base_string, hashlib.sha384)
        hmac_sha384 = hashed.digest().encode('base64').rstrip('\n')
        hmacs['SHA-384'] = hmac_sha384
        # --- SHA-512 ---
        hashed = hmac.new(key, base_string, hashlib.sha512)
        hmac_sha512 = hashed.digest().encode('base64').rstrip('\n')
        hmacs['SHA-512'] = hmac_sha512
        return hmacs
项目:Bitcoin-Crypto-python-charts    作者:Whalepool    | 项目源码 | 文件源码
def _sign_payload(self, payload):
        j = json.dumps(payload)
        data = base64.standard_b64encode(j.encode('utf8'))

        h = hmac.new(self.SECRET.encode('utf8'), data, hashlib.sha384)
        signature = h.hexdigest()
        return {
            "X-BFX-APIKEY": self.KEY,
            "X-BFX-SIGNATURE": signature,
            "X-BFX-PAYLOAD": data
        }
项目:Bitcoin-Crypto-python-charts    作者:Whalepool    | 项目源码 | 文件源码
def _headers(self, path, nonce, body):

        signature = "/api/" + path + nonce + body
        pprint("Signing: " + signature)
        h = hmac.new(self.SECRET.encode('utf8'), signature.encode('utf8'), hashlib.sha384)
        signature = h.hexdigest()

        return {
            "content-type": "application/json",
            "bfx-nonce": nonce,
            "bfx-apikey": self.KEY,
            "bfx-signature": signature,
        }
项目:public_drown_scanner    作者:nimia    | 项目源码 | 文件源码
def calculate_digest(data, alg):    
    '''
    Calculates digest according to algorithm
    '''
    digest_alg = None
    if (alg == SHA1_NAME):
        digest_alg = hashlib.sha1() 

    if (alg == SHA256_NAME):
        digest_alg = hashlib.sha256()

    if (alg == SHA384_NAME):
        digest_alg = hashlib.sha384()

    if (alg == SHA512_NAME):
        digest_alg = hashlib.sha512()

    if digest_alg is None:
        logger.error("Unknown digest algorithm : %s" % alg)
        return None

    digest_alg.update(data)   
    dg = digest_alg.digest()       

    logger.debug("Calculated hash from input data: %s" % base64.b64encode(dg))    
    return dg
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
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 h in _hashFuncParams:
        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]
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
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.
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def _commoncrypto_hashlib_to_crypto_map_get(hashfunc):
    hashlib_to_crypto_map = {hashlib.sha1: 1,
                             hashlib.sha224: 2,
                             hashlib.sha256: 3,
                             hashlib.sha384: 4,
                             hashlib.sha512: 5}
    crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc)
    if crypto_hashfunc is None:
        raise ValueError('Unkwnown digest %s' % hashfunc)
    return crypto_hashfunc
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def _openssl_hashlib_to_crypto_map_get(hashfunc):
    hashlib_to_crypto_map = {hashlib.md5: crypto.EVP_md5,
                                 hashlib.sha1: crypto.EVP_sha1,
                                 hashlib.sha256: crypto.EVP_sha256,
                                 hashlib.sha224: crypto.EVP_sha224,
                                 hashlib.sha384: crypto.EVP_sha384,
                                 hashlib.sha512: crypto.EVP_sha512}
    crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc)
    if crypto_hashfunc is None:
        raise ValueError('Unkwnown digest %s' % hashfunc)
    crypto_hashfunc.restype = ctypes.c_void_p
    return crypto_hashfunc()
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def test_simple_hash(self):
        """ Tests the simple_hash function """

        # no key, no salt, md5
        data_md5 = simple_hash('web2py rocks!', key='', salt='', digest_alg='md5')
        self.assertEqual(data_md5, '37d95defba6c8834cb8cae86ee888568')

        # no key, no salt, sha1
        data_sha1 = simple_hash('web2py rocks!', key='', salt='', digest_alg='sha1')
        self.assertEqual(data_sha1, '00489a46753d8db260c71542611cdef80652c4b7')

        # no key, no salt, sha224
        data_sha224 = simple_hash('web2py rocks!', key='', salt='', digest_alg='sha224')
        self.assertEqual(data_sha224, '84d7054271842c2c17983baa2b1447e0289d101140a8c002d49d60da')

        # no key, no salt, sha256
        data_sha256 = simple_hash('web2py rocks!', key='', salt='', digest_alg='sha256')
        self.assertEqual(data_sha256, '0849f224d8deb267e4598702aaec1bd749e6caec90832469891012a4be24af08')

        # no key, no salt, sha384
        data_sha384 = simple_hash('web2py rocks!', key='', salt='', digest_alg='sha384')
        self.assertEqual(data_sha384,
            '3cffaf39371adbe84eb10f588d2718207d8e965e9172a27a278321b86977351376ae79f92e91d8c58cad86c491282d5f')

        # no key, no salt, sha512
        data_sha512 = simple_hash('web2py rocks!', key='', salt='', digest_alg='sha512')
        self.assertEqual(data_sha512, 'fa3237f594743e1d7b6c800bb134b3255cf4a98ab8b01e2ec23256328c9f8059'
                                      '64fdef25a038d6cc3fda1b2fb45d66461eeed5c4669e506ec8bdfee71348db7e')
项目:autoreg    作者:pbeyssac    | 项目源码 | 文件源码
def compute_ds(domain, flags, protocol, algorithm, key, digesttypelist=[1, 2, 4]):
  """Compute DS/DLV records from DNSKEY data"""
  domain = str(domain.lower())
  if domain[-1] != b'.':
    domain += b'.'
  wire = b''
  for d in domain.split(b'.'):
    wire += struct.pack('B', len(d)) + d
  tag, wirekey = compute_keytag_wirekey(flags, protocol, algorithm, key)
  wire += wirekey

  dslist = []
  for digesttype in digesttypelist:
    if digesttype == 1:
      dslist.append((tag, algorithm, 1, hashlib.sha1(wire).hexdigest()))
    elif digesttype == 2:
      dslist.append((tag, algorithm, 2, hashlib.sha256(wire).hexdigest()))
    elif digesttype == 3:
      try:
        from pygost.gost341194 import GOST341194
      except ImportError:
        pass
      else:
        dslist.append((tag, algorithm, 3, GOST341194(wire).hexdigest()))
    else:
      dslist.append((tag, algorithm, 4, hashlib.sha384(wire).hexdigest()))
  return dslist
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def _commoncrypto_hashlib_to_crypto_map_get(hashfunc):
    hashlib_to_crypto_map = {hashlib.sha1: 1,
                             hashlib.sha224: 2,
                             hashlib.sha256: 3,
                             hashlib.sha384: 4,
                             hashlib.sha512: 5}
    crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc)
    if crypto_hashfunc is None:
        raise ValueError('Unkwnown digest %s' % hashfunc)
    return crypto_hashfunc