當前位置: 首頁>>代碼示例>>Python>>正文


Python HMAC.new方法代碼示例

本文整理匯總了Python中Crypto.Hash.HMAC.new方法的典型用法代碼示例。如果您正苦於以下問題:Python HMAC.new方法的具體用法?Python HMAC.new怎麽用?Python HMAC.new使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Crypto.Hash.HMAC的用法示例。


在下文中一共展示了HMAC.new方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: getHBootKey

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def getHBootKey(self):
        LOG.debug('Calculating HashedBootKey from SAM')
        QWERTY = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\0"
        DIGITS = "0123456789012345678901234567890123456789\0"

        F = self.getValue(ntpath.join('SAM\Domains\Account','F'))[1]

        domainData = DOMAIN_ACCOUNT_F(F)

        rc4Key = self.MD5(domainData['Key0']['Salt'] + QWERTY + self.__bootKey + DIGITS)

        rc4 = ARC4.new(rc4Key)
        self.__hashedBootKey = rc4.encrypt(domainData['Key0']['Key']+domainData['Key0']['CheckSum'])

        # Verify key with checksum
        checkSum = self.MD5( self.__hashedBootKey[:16] + DIGITS + self.__hashedBootKey[:16] + QWERTY)

        if checkSum != self.__hashedBootKey[16:]:
            raise Exception('hashedBootKey CheckSum failed, Syskey startup password probably in use! :(') 
開發者ID:joxeankoret,項目名稱:CVE-2017-7494,代碼行數:21,代碼來源:secretsdump.py

示例2: __decryptSecret

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def __decryptSecret(self, key, value):
        # [MS-LSAD] Section 5.1.2
        plainText = ''

        encryptedSecretSize = unpack('<I', value[:4])[0]
        value = value[len(value)-encryptedSecretSize:]

        key0 = key
        for i in range(0, len(value), 8):
            cipherText = value[:8]
            tmpStrKey = key0[:7]
            tmpKey = self.__cryptoCommon.transformKey(tmpStrKey)
            Crypt1 = DES.new(tmpKey, DES.MODE_ECB)
            plainText += Crypt1.decrypt(cipherText)
            key0 = key0[7:]
            value = value[8:]
            # AdvanceKey
            if len(key0) < 7:
                key0 = key[len(key0):]

        secret = LSA_SECRET_XP(plainText)
        return secret['Secret'] 
開發者ID:joxeankoret,項目名稱:CVE-2017-7494,代碼行數:24,代碼來源:secretsdump.py

示例3: __decryptLSA

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def __decryptLSA(self, value):
        if self.__vistaStyle is True:
            # ToDo: There could be more than one LSA Keys
            record = LSA_SECRET(value)
            tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32])
            plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])
            record = LSA_SECRET_BLOB(plainText)
            self.__LSAKey = record['Secret'][52:][:32]

        else:
            md5 = hashlib.new('md5')
            md5.update(self.__bootKey)
            for i in range(1000):
                md5.update(value[60:76])
            tmpKey = md5.digest()
            rc4 = ARC4.new(tmpKey)
            plainText = rc4.decrypt(value[12:60])
            self.__LSAKey = plainText[0x10:0x20] 
開發者ID:joxeankoret,項目名稱:CVE-2017-7494,代碼行數:20,代碼來源:secretsdump.py

示例4: decrypt

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def decrypt(cls, key, keyusage, ciphertext):
        if len(ciphertext) < 24:
            raise ValueError('ciphertext too short')
        cksum, basic_ctext = ciphertext[:16], ciphertext[16:]
        ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
        ke = HMAC.new(ki, cksum, MD5).digest()
        basic_plaintext = ARC4.new(ke).decrypt(basic_ctext)
        exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
        ok = _mac_equal(cksum, exp_cksum)
        if not ok and keyusage == 9:
            # Try again with usage 8, due to RFC 4757 errata.
            ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()
            exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
            ok = _mac_equal(cksum, exp_cksum)
        if not ok:
            raise InvalidChecksum('ciphertext integrity failure')
        # Discard the confounder.
        return basic_plaintext[8:] 
開發者ID:joxeankoret,項目名稱:CVE-2017-7494,代碼行數:20,代碼來源:crypto.py

示例5: GSS_GetMIC

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
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:joxeankoret,項目名稱:CVE-2017-7494,代碼行數:27,代碼來源:gssapi.py

示例6: decrypt_hash

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def decrypt_hash(edata, nlkm, ch, xp = True):
    if xp:
        hmac_md5 = HMAC.new(nlkm, ch)
        rc4key = hmac_md5.digest()

        rc4 = ARC4.new(rc4key)
        data = rc4.encrypt(edata)
    else:
        # based on  Based on code from http://lab.mediaservice.net/code/cachedump.rb
        aes = AES.new(nlkm[16:32], AES.MODE_CBC, ch)
        data = ""
        for i in range(0, len(edata), 16):
            buf = edata[i : i + 16]
            if len(buf) < 16:
                buf += (16 - len(buf)) * "\00"
            data += aes.decrypt(buf)
    return data 
開發者ID:virtualrealitysystems,項目名稱:aumfor,代碼行數:19,代碼來源:domcachedump.py

示例7: encrypt

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def encrypt(self, plaintext, esn):
        """
        Encrypt the given Plaintext with the encryption key
        :param plaintext:
        :return: Serialized JSON String of the encryption Envelope
        """
        init_vector = get_random_bytes(16)
        cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)
        ciphertext = base64.standard_b64encode(
            cipher.encrypt(Padding.pad(plaintext.encode('utf-8'), 16))).decode('utf-8')
        encryption_envelope = {
            'ciphertext': ciphertext,
            'keyid': '_'.join((esn, str(self.sequence_number))),
            'sha256': 'AA==',
            'iv': base64.standard_b64encode(init_vector).decode('utf-8')
        }
        return json.dumps(encryption_envelope) 
開發者ID:CastagnaIT,項目名稱:plugin.video.netflix,代碼行數:19,代碼來源:default_crypto.py

示例8: __decryptHash

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def __decryptHash(self, rid, cryptedHash, constant, newStyle = False):
        # Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key
        # plus hashedBootKey stuff
        Key1,Key2 = self.__cryptoCommon.deriveKey(rid)

        Crypt1 = DES.new(Key1, DES.MODE_ECB)
        Crypt2 = DES.new(Key2, DES.MODE_ECB)

        if newStyle is False:
            rc4Key = self.MD5( self.__hashedBootKey[:0x10] + pack("<L",rid) + constant )
            rc4 = ARC4.new(rc4Key)
            key = rc4.encrypt(cryptedHash['Hash'])
        else:
            key = self.__cryptoCommon.decryptAES(self.__hashedBootKey[:0x10], cryptedHash['Hash'], cryptedHash['Salt'])[:16]

        decryptedHash = Crypt1.decrypt(key[:8]) + Crypt2.decrypt(key[8:])

        return decryptedHash 
開發者ID:eth0izzle,項目名稱:cracke-dit,代碼行數:20,代碼來源:secretsdump.py

示例9: decrypt_hash

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def decrypt_hash(edata, nlkm, ch):
    hmac_md5 = HMAC.new(nlkm,ch)
    rc4key = hmac_md5.digest()

    rc4 = ARC4.new(rc4key)
    data = rc4.encrypt(edata)
    return data 
開發者ID:HarmJ0y,項目名稱:ImpDump,代碼行數:9,代碼來源:domcachedump.py

示例10: create_signature

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def create_signature(self, secret_key, to_sign):
        sign = HMAC.new(secret_key, to_sign, SHA)
        return str(b64encode(sign.hexdigest().encode()))

    # creates device spec JSON 
開發者ID:eslavnov,項目名稱:pylips,代碼行數:7,代碼來源:pylips.py

示例11: _randnum

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def _randnum(self, size):
        from Crypto import Random
        return Random.new().read(size) 
開發者ID:mortcanty,項目名稱:earthengine,代碼行數:5,代碼來源:Chaffing.py

示例12: PBKDF1

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
    """Derive one key from a password (or passphrase).

    This function performs key derivation according an old version of
    the PKCS#5 standard (v1.5).
    
    This algorithm is called ``PBKDF1``. Even though it is still described
    in the latest version of the PKCS#5 standard (version 2, or RFC2898),
    newer applications should use the more secure and versatile `PBKDF2` instead.

    :Parameters:
     password : string
        The secret password or pass phrase to generate the key from.
     salt : byte string
        An 8 byte string to use for better protection from dictionary attacks.
        This value does not need to be kept secret, but it should be randomly
        chosen for each derivation.
     dkLen : integer
        The length of the desired key. Default is 16 bytes, suitable for instance for `Crypto.Cipher.AES`.
     count : integer
        The number of iterations to carry out. It's recommended to use at least 1000.
     hashAlgo : module
        The hash algorithm to use, as a module or an object from the `Crypto.Hash` package.
        The digest length must be no shorter than ``dkLen``.
        The default algorithm is `SHA1`.

    :Return: A byte string of length `dkLen` that can be used as key.
    """
    if not hashAlgo:
        hashAlgo = SHA1
    password = tobytes(password)
    pHash = hashAlgo.new(password+salt)
    digest = pHash.digest_size
    if dkLen>digest:
        raise ValueError("Selected hash algorithm has a too short digest (%d bytes)." % digest)
    if len(salt)!=8:
        raise ValueError("Salt is not 8 bytes long.")
    for i in xrange(count-1):
        pHash = pHash.new(pHash.digest())
    return pHash.digest()[:dkLen] 
開發者ID:mortcanty,項目名稱:earthengine,代碼行數:42,代碼來源:KDF.py

示例13: PBKDF2

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def PBKDF2(password, salt, dkLen=16, count=1000, prf=None):
    """Derive one or more keys from a password (or passphrase).

    This performs key derivation according to the PKCS#5 standard (v2.0),
    by means of the ``PBKDF2`` algorithm.

    :Parameters:
     password : string
        The secret password or pass phrase to generate the key from.
     salt : string
        A string to use for better protection from dictionary attacks.
        This value does not need to be kept secret, but it should be randomly
        chosen for each derivation. It is recommended to be at least 8 bytes long.
     dkLen : integer
        The cumulative length of the desired keys. Default is 16 bytes, suitable for instance for `Crypto.Cipher.AES`.
     count : integer
        The number of iterations to carry out. It's recommended to use at least 1000.
     prf : callable
        A pseudorandom function. It must be a function that returns a pseudorandom string
        from two parameters: a secret and a salt. If not specified, HMAC-SHA1 is used.

    :Return: A byte string of length `dkLen` that can be used as key material.
        If you wanted multiple keys, just break up this string into segments of the desired length.
"""
    password = tobytes(password)
    if prf is None:
        prf = lambda p,s: HMAC.new(p,s,SHA1).digest()
    key = b('')
    i = 1
    while len(key)<dkLen:
        U = previousU = prf(password,salt+struct.pack(">I", i))
        for j in xrange(count-1):
            previousU = t = prf(password,previousU)
            U = strxor(U,t)
        key += U
        i = i + 1
    return key[:dkLen] 
開發者ID:mortcanty,項目名稱:earthengine,代碼行數:39,代碼來源:KDF.py

示例14: test1

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def test1(self):
        # Test only for HMAC-SHA1 as PRF

        def prf(p,s):
            return HMAC.new(p,s,SHA1).digest()

        for i in xrange(len(self._testData)):
            v = self._testData[i]
            res  = PBKDF2(v[0], t2b(v[1]), v[2], v[3])
            res2 = PBKDF2(v[0], t2b(v[1]), v[2], v[3], prf)
            self.assertEqual(res, t2b(v[4]))
            self.assertEqual(res, res2) 
開發者ID:mortcanty,項目名稱:earthengine,代碼行數:14,代碼來源:test_KDF.py

示例15: __restore

# 需要導入模塊: from Crypto.Hash import HMAC [as 別名]
# 或者: from Crypto.Hash.HMAC import new [as 別名]
def __restore(self):
        # First of all stop the service if it was originally stopped
        if self.__shouldStop is True:
            LOG.info('Stopping service %s' % self.__serviceName)
            scmr.hRControlService(self.__scmr, self.__serviceHandle, scmr.SERVICE_CONTROL_STOP)
        if self.__disabled is True:
            LOG.info('Restoring the disabled state for service %s' % self.__serviceName)
            scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x4)
        if self.__serviceDeleted is False:
            # Check again the service we created does not exist, starting a new connection
            # Why?.. Hitting CTRL+C might break the whole existing DCE connection
            try:
                rpc = transport.DCERPCTransportFactory(r'ncacn_np:%s[\pipe\svcctl]' % self.__smbConnection.getRemoteHost())
                if hasattr(rpc, 'set_credentials'):
                    # This method exists only for selected protocol sequences.
                    rpc.set_credentials(*self.__smbConnection.getCredentials())
                    rpc.set_kerberos(self.__doKerberos, self.__kdcHost)
                self.__scmr = rpc.get_dce_rpc()
                self.__scmr.connect()
                self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
                # Open SC Manager
                ans = scmr.hROpenSCManagerW(self.__scmr)
                self.__scManagerHandle = ans['lpScHandle']
                # Now let's open the service
                resp = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName)
                service = resp['lpServiceHandle']
                scmr.hRDeleteService(self.__scmr, service)
                scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)
                scmr.hRCloseServiceHandle(self.__scmr, service)
                scmr.hRCloseServiceHandle(self.__scmr, self.__serviceHandle)
                scmr.hRCloseServiceHandle(self.__scmr, self.__scManagerHandle)
                rpc.disconnect()
            except Exception, e:
                # If service is stopped it'll trigger an exception
                # If service does not exist it'll trigger an exception
                # So. we just wanna be sure we delete it, no need to 
                # show this exception message
                pass 
開發者ID:joxeankoret,項目名稱:CVE-2017-7494,代碼行數:40,代碼來源:secretsdump.py


注:本文中的Crypto.Hash.HMAC.new方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。