python类sha384()的实例源码

cert.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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.
cert.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
hash.py 文件源码 项目:llk 作者: Tycx2ry 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
hash.py 文件源码 项目:spiderfoot 作者: wi-fi-analyzer 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
pbkdf2_ctypes.py 文件源码 项目:touch-pay-client 作者: HackPucBemobi 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
pbkdf2_ctypes.py 文件源码 项目:touch-pay-client 作者: HackPucBemobi 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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()
cert.py 文件源码 项目:CVE-2016-6366 作者: RiskSense-Ops 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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]
cert.py 文件源码 项目:CVE-2016-6366 作者: RiskSense-Ops 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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.
cert.py 文件源码 项目:CVE-2016-6366 作者: RiskSense-Ops 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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)
uploader.py 文件源码 项目:storj-python-sdk 作者: Storj 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
client.py 文件源码 项目:Bitcoin-Crypto-python-charts 作者: Whalepool 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
        }
client.py 文件源码 项目:Bitcoin-Crypto-python-charts 作者: Whalepool 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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,
        }
digest.py 文件源码 项目:public_drown_scanner 作者: nimia 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
cert.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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]
cert.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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.
pbkdf2_ctypes.py 文件源码 项目:true_review_web2py 作者: lucadealfaro 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
pbkdf2_ctypes.py 文件源码 项目:true_review_web2py 作者: lucadealfaro 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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()
test_utils.py 文件源码 项目:true_review_web2py 作者: lucadealfaro 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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')
dnssec.py 文件源码 项目:autoreg 作者: pbeyssac 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
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
pbkdf2_ctypes.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号