当前位置: 首页>>代码示例>>Python>>正文


Python Hash.HMAC类代码示例

本文整理汇总了Python中Cryptodome.Hash.HMAC的典型用法代码示例。如果您正苦于以下问题:Python HMAC类的具体用法?Python HMAC怎么用?Python HMAC使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了HMAC类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: GSS_GetMIC

    def GSS_GetMIC(self, sessionKey, data, sequenceNumber, direction = 'init'):
        GSS_GETMIC_HEADER = '\x60\x23\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02'
        token = self.MIC()

        # Let's pad the data
        pad = (4 - (len(data) % 4)) & 0x3
        padStr = chr(pad) * pad
        data += padStr
 
        token['SGN_ALG'] = GSS_HMAC
        if direction == 'init':
            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\x00'*4
        else:
            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\xff'*4

        Ksign = HMAC.new(sessionKey.contents, 'signaturekey\0', MD5).digest()
        Sgn_Cksum = MD5.new( struct.pack('<L',15) + str(token)[:8] + data).digest()
        Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest()
        token['SGN_CKSUM'] = Sgn_Cksum[:8]

        Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()
        Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest()
        token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ'])
        finalData = GSS_GETMIC_HEADER + token.getData()
        return finalData
开发者ID:awesome-security,项目名称:impacket,代码行数:25,代码来源:gssapi.py

示例2: decrypt

    def decrypt(self, key):
        if self['HashAlgo'] == ALGORITHMS.CALG_HMAC.value:
            hashModule = SHA1
        else:
            hashModule = ALGORITHMS_DATA[self['HashAlgo']][1]

        prf = lambda p, s: HMAC.new(p, s, hashModule).digest()
        derivedBlob = self.deriveKey(key, self['Salt'],
                                    ALGORITHMS_DATA[self['CryptAlgo']][0] + ALGORITHMS_DATA[self['CryptAlgo']][3],
                                    count=self['MasterKeyIterationCount'], hashFunction=prf)

        cryptKey = derivedBlob[:ALGORITHMS_DATA[self['CryptAlgo']][0]]
        iv = derivedBlob[ALGORITHMS_DATA[self['CryptAlgo']][0]:][:ALGORITHMS_DATA[self['CryptAlgo']][3]]

        cipher = ALGORITHMS_DATA[self['CryptAlgo']][1].new(cryptKey, mode = ALGORITHMS_DATA[self['CryptAlgo']][2], iv = iv)
        cleartext = cipher.decrypt(self['data'])

        decryptedKey = cleartext[-64:]
        hmacSalt = cleartext[:16]
        hmac = cleartext[16:][:ALGORITHMS_DATA[self['HashAlgo']][0]]

        hmacKey = HMAC.new(key, hmacSalt, hashModule).digest()

        hmacCalculated = HMAC.new(hmacKey, decryptedKey, hashModule ).digest()

        if hmacCalculated[:ALGORITHMS_DATA[self['HashAlgo']][0]] == hmac:
            self.decryptedKey = decryptedKey
            return decryptedKey
        else:
            return None
开发者ID:CoreSecurity,项目名称:impacket,代码行数:30,代码来源:dpapi.py

示例3: runTest

    def runTest(self):

        key = b"0" * 16
        data = b"\x00\x01\x02"

        def get_mv_ro(data):
            return memoryview(data)

        def get_mv_rw(data):
            return memoryview(bytearray(data))

        for get_mv in (get_mv_ro, get_mv_rw):

            # Data and key can be a memoryview (during initialization)
            key_mv = get_mv(key)
            data_mv = get_mv(data)

            h1 = HMAC.new(key, data)
            h2 = HMAC.new(key_mv, data_mv)
            if not data_mv.readonly:
                key_mv[:1] = b'\xFF'
                data_mv[:1] = b'\xFF'
            self.assertEqual(h1.digest(), h2.digest())

            # Data can be a memoryview (during operation)
            data_mv = get_mv(data)

            h1 = HMAC.new(key)
            h2 = HMAC.new(key)
            h1.update(data)
            h2.update(data_mv)
            if not data_mv.readonly:
                data_mv[:1] = b'\xFF'
            self.assertEqual(h1.digest(), h2.digest())
开发者ID:2216288075,项目名称:meiduo_project,代码行数:34,代码来源:test_HMAC.py

示例4: ComputeResponsev2

def ComputeResponsev2(NegFlg, ResponseKeyNT, ResponseKeyLM, ServerChallenge,
                      ClientChallenge, Time=None, ServerName=None, av_pairs=None):
    if Time is None:
        Time = nttime.NtTime(nttime.datetime.now())
    if ServerName is None:
        ServerName = "SERVER"
    ServerName = ServerName.encode("utf-16-le")

    TimeBuf = array.array("B")
    cur = core.Cursor(TimeBuf,0)
    cur.encode_uint64le(Time)

    Responseversion = "\x01"
    HiResponseversion = "\x01"

    ntlmv2_client_challenge = NTLMv2ClientChallenge()
    ntlmv2_client_challenge.time_stamp = Time
    ntlmv2_client_challenge.challenge_from_client = ClientChallenge
    if av_pairs is not None:
        ntlmv2_client_challenge.av_pairs = av_pairs
    temp = encode_frame(ntlmv2_client_challenge).tostring()
    NTProofStr = HMAC.new(ResponseKeyNT,
                          ServerChallenge + temp,
                          MD5).digest()
    NtChallengeResponse = NTProofStr + temp
    LmChallengeResponse = HMAC.new(ResponseKeyLM,
                                   ServerChallenge + ClientChallenge,
                                   MD5).digest() +\
                          ClientChallenge
    SessionBaseKey = HMAC.new(ResponseKeyNT, NTProofStr, MD5).digest()
    return NtChallengeResponse, LmChallengeResponse, SessionBaseKey
开发者ID:emc-isilon,项目名称:pike,代码行数:31,代码来源:ntlm.py

示例5: encrypt

 def encrypt(cls, key, keyusage, plaintext, confounder):
     if confounder is None:
         confounder = get_random_bytes(8)
     ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
     cksum = HMAC.new(ki, confounder + plaintext, MD5).digest()
     ke = HMAC.new(ki, cksum, MD5).digest()
     return cksum + ARC4.new(ke).encrypt(bytes(confounder + plaintext))
开发者ID:CoreSecurity,项目名称:impacket,代码行数:7,代码来源:crypto.py

示例6: deriveKeysFromUser

    def deriveKeysFromUser(self, sid, password):
        # Will generate two keys, one with SHA1 and another with MD4
        key1 = HMAC.new(SHA1.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
        key2 = HMAC.new(MD4.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
        # For Protected users
        tmpKey = pbkdf2_hmac('sha256', MD4.new(password.encode('utf-16le')).digest(), sid.encode('utf-16le'), 10000)
        tmpKey2 = pbkdf2_hmac('sha256', tmpKey, sid.encode('utf-16le'), 1)[:16]
        key3 = HMAC.new(tmpKey2, (sid + '\0').encode('utf-16le'), SHA1).digest()[:20]

        return key1, key2, key3
开发者ID:awesome-security,项目名称:impacket,代码行数:10,代码来源:dpapi.py

示例7: runTest

    def runTest(self):
        key = b("\x90\x91\x92\x93") * 4
        payload = b("\x00") * 100

        for hashname, hashmod in self.hashmods.items():
            if hashmod is None:
                continue
            self.description = "Test HMAC in combination with " + hashname
            one = HMAC.new(key, payload, hashmod).digest()
            two = HMAC.new(key, payload, hashmod.new()).digest()
            self.assertEqual(one, two)
开发者ID:FndNur1Labs,项目名称:PokemonGo-DesktopMap,代码行数:11,代码来源:test_HMAC.py

示例8: verfiyMessageSignature

    def verfiyMessageSignature(self, message, hex_mac, method=None,
                               slot_id=DEFAULT_KEY):
        """
        verify the hex mac is same for the message -
           the comparison is done in a constant time comparison

        :param message: the original message
        :param hex_mac: the to compared mac in hex
        :param method: the hash method - we use by default sha256
        :param slot_id: which key should be used

        :return: boolean
        """
        sign_key = None
        result = True

        if method is None:
            method = SHA256

        try:
            sign_key = self.getSecret(slot_id)
            hmac = HMAC.new(sign_key, message, method)
            sign_mac = HMAC.new(sign_key, message, method).hexdigest()

            res = 0
            # as we compare on hex, we have to multiply by 2
            digest_size = hmac.digest_size * 2

            for x, y in zip(hex_mac, sign_mac):
                res |= ord(x) ^ ord(y)

            if len(sign_mac) != digest_size:
                result = False

            if res:
                result = False

        except ValueError as err:
            log.error("Mac Comparison failed! %r", err)

        except Exception as exx:
            pass

        finally:
            if sign_key:
                zerome(sign_key)
                del sign_key

        return result
开发者ID:gsnbng,项目名称:LinOTP,代码行数:49,代码来源:default.py

示例9: NTOWFv2

def NTOWFv2(password, user, userdom):
    nt_passwd = password.encode("utf-16-le")
    nt_hash_passwd = MD4.new(nt_passwd).digest()
    nt_userdom = (user.upper() + userdom).encode("utf-16-le")
    return HMAC.new(nt_hash_passwd,
                    nt_userdom,
                    MD5).digest()
开发者ID:emc-isilon,项目名称:pike,代码行数:7,代码来源:ntlm.py

示例10: signMessage

    def signMessage(self, message, method=None, slot_id=DEFAULT_KEY):
        """
        create the hex mac for the message -

        :param message: the original message
        :param method: the hash method - we use by default sha256
        :param slot_id: which key should be used

        :return: hex mac
        """

        sign_key = None

        if method is None:
            method = SHA256

        try:
            sign_key = self.getSecret(slot_id)
            hex_mac = HMAC.new(sign_key, message, method).hexdigest()
        finally:
            if sign_key:
                zerome(sign_key)
                del sign_key

        return hex_mac
开发者ID:gsnbng,项目名称:LinOTP,代码行数:25,代码来源:default.py

示例11: encrypt

def encrypt(plaintext):
    iv = urandom(16)
    salt = urandom(8)
    iterations = 1000
    ks = 128
    ts = 64

    hash_func = lambda k, s: HMAC.new(k, s, SHA256).digest()
    password = b64encode(urandom(32))
    key = PBKDF2(password, salt=salt, count=iterations, prf=hash_func)

    smalliv = trunc_iv(iv, plaintext, 0)

    cipher = AES.new(key, mode=AES.MODE_CCM, nonce=smalliv, mac_len=ts // 8)
    ciphertext = b''.join(cipher.encrypt_and_digest(plaintext))

    # OrderedDict because 0bin is a piece of shit requiring "iv" as the first key
    return password.decode('ascii'), OrderedDict([
        ('iv', b64encode(iv).decode('ascii')),
        ('v', 1),
        ('iter', iterations),
        ('ks', ks),
        ('ts', ts),
        ('mode', 'ccm'),
        ('adata', ''),
        ('cipher', 'aes'),
        ('salt', b64encode(salt).decode('ascii')),
        ('ct', b64encode(ciphertext).decode('ascii')),
    ])
开发者ID:P4ncake,项目名称:weboob,代码行数:29,代码来源:crypto.py

示例12: aes_cbc_hmac_decrypt

def aes_cbc_hmac_decrypt(key, iv, aad, ct, tag):
    """
    Perform authenticated decryption with the combined AES-CBC
    and HMAC algorithm.

    :param key  : Key; length MUST be 32, 48, or 64 octets
    :param iv : Initialization vector; length MUST be 16 octets
    :param aad: Additional authenticated data
    :param ct : Cipher text
    :param tag: Authentication tag
    :return: (plaintext, result) tuple, with plaintext as bytes
      and result as boolean
    """

    ka, ke, seclen, dgst = get_keys_seclen_dgst(key, iv)

    # Verify A || IV || E || AL
    al = pack("!Q", 8*len(aad))
    if isinstance(aad, str):
        aad = aad.encode("utf-8")
    mac_input = aad + iv + ct + al
    h = HMAC.new(ka, digestmod=dgst)
    h.update(mac_input)
    candidate = h.digest()[:seclen]

    # Decrypt if verified
    if candidate == tag:
        cipher = AES.new(ke, AES.MODE_CBC, iv)
        pt = pkcs5trim(cipher.decrypt(ct))
        return pt
    else:
        raise VerificationFailure('AES-CBC HMAC')
开发者ID:rohe,项目名称:pyjwkest,代码行数:32,代码来源:extra.py

示例13: deriveKey

    def deriveKey(self, sessionKey):
        def fixparity(deskey):
            from six import indexbytes, b
            temp = b''
            for i in range(len(deskey)):
                t = (bin(indexbytes(deskey,i))[2:]).rjust(8,'0')
                if t[:7].count('1') %2 == 0:
                    temp+= b(chr(int(t[:7]+'1',2)))
                else:
                    temp+= b(chr(int(t[:7]+'0',2)))
            return temp

        if len(sessionKey) > ALGORITHMS_DATA[self['HashAlgo']][4]:
            derivedKey = HMAC.new(sessionKey,  digestmod = ALGORITHMS_DATA[self['HashAlgo']][1]).digest()
        else:
            derivedKey = sessionKey


        if len(derivedKey) < ALGORITHMS_DATA[self['CryptAlgo']][0]:
            # Extend the key
            derivedKey += b'\x00'*ALGORITHMS_DATA[self['HashAlgo']][4]
            ipad = bytearray([ i ^ 0x36 for i in bytearray(derivedKey)][:ALGORITHMS_DATA[self['HashAlgo']][4]])
            opad = bytearray([ i ^ 0x5c for i in bytearray(derivedKey)][:ALGORITHMS_DATA[self['HashAlgo']][4]])
            derivedKey = ALGORITHMS_DATA[self['HashAlgo']][1].new(ipad).digest() + \
                ALGORITHMS_DATA[self['HashAlgo']][1].new(opad).digest()
            derivedKey = fixparity(derivedKey)

        return derivedKey
开发者ID:CoreSecurity,项目名称:impacket,代码行数:28,代码来源:dpapi.py

示例14: decrypt

def decrypt(secretkey, params):
    iv = b64decode(params['iv'])
    salt = b64decode(params['salt'])
    #~ keylen = params.get('ks', 128) // 8 # FIXME use somewhere?
    taglen = params.get('ts', 64) // 8
    iterations = params.get('iter', 1000)
    data = b64decode(params['ct'])
    ciphertext = data[:-taglen]
    tag = data[-taglen:]

    if params.get('adata'):
        raise NotImplementedError('authenticated data support is not implemented')

    iv = trunc_iv(iv, ciphertext, taglen)

    hash_func = lambda k, s: HMAC.new(k, s, SHA256).digest()
    key = PBKDF2(secretkey, salt=salt, count=iterations, prf=hash_func)

    mode_str = params.get('mode', 'ccm')
    mode = dict(ccm=AES.MODE_CCM)[mode_str]
    if mode_str == 'ccm':
        cipher = AES.new(key, mode=AES.MODE_CCM, nonce=iv, mac_len=taglen)
    else:
        cipher = AES.new(key, mode=mode, iv=iv)
    decrypted = cipher.decrypt_and_verify(ciphertext, tag)
    return decrypted
开发者ID:P4ncake,项目名称:weboob,代码行数:26,代码来源:crypto.py

示例15: aes_cbc_hmac_encrypt

def aes_cbc_hmac_encrypt(key, iv, aad, pt):
    """
    Perform authenticated encryption with the combined AES-CBC
    and HMAC algorithm.

    :param key: key; length MUST be 32, 48, or 64 octets
    :param iv: Initialization vector; length MUST be 16 octets
    :param aad: Additional authenticated data
    :param pt: Plaintext
    :return: (ciphertext, tag) tuple, with each as bytes
    """

    ka, ke, seclen, dgst = get_keys_seclen_dgst(key, iv)

    # Encrypt
    cipher = AES.new(ke, AES.MODE_CBC, iv)
    ct = cipher.encrypt(pkcs5pad(pt))

    # MAC A || IV || E || AL
    al = pack("!Q", 8*len(aad))
    mac_input = aad + iv + ct + al
    h = HMAC.new(ka, digestmod=dgst)
    h.update(mac_input)
    tag = h.digest()[:seclen]
    return ct, tag
开发者ID:rohe,项目名称:pyjwkest,代码行数:25,代码来源:extra.py


注:本文中的Cryptodome.Hash.HMAC类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。