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


Python HMAC.digest方法代码示例

本文整理汇总了Python中hmac.HMAC.digest方法的典型用法代码示例。如果您正苦于以下问题:Python HMAC.digest方法的具体用法?Python HMAC.digest怎么用?Python HMAC.digest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在hmac.HMAC的用法示例。


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

示例1: verify_message_auth_code

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
def verify_message_auth_code(our_mac, msg_mac, ses_key):
	## two rounds closes a timing side-channel
	msg_mac = HMAC_FUNC(ses_key, msg_mac, HMAC_HASH)
	our_mac = HMAC_FUNC(ses_key, our_mac, HMAC_HASH)
	msg_mac = msg_mac.digest()
	our_mac = our_mac.digest()
	num_val = 0

	if (len(msg_mac) != len(our_mac)):
		return False

	## fixed linear-time comparison closes another
	for i in xrange(len(our_mac)):
		num_val += (our_mac[i] == msg_mac[i])

	return (num_val == len(our_mac))
开发者ID:Anarchid,项目名称:uberserver,代码行数:18,代码来源:CryptoHandler.py

示例2: encrypt_and_hmac

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
    def encrypt_and_hmac(self, packet):
        """
        Encrypts and signs a Packet() using self.SK_ei and self.SK_ai

        :param packet: Unecrypted Packet() with one or more payloads.
        :return: Encrypted and signed Packet() with a single payloads.SK
        """
        final = Packet(exchange_type=packet.exchange_type, iSPI=packet.iSPI, rSPI=packet.rSPI, message_id=1)
        # Set up crypto
        iv = os.urandom(16)
        ikecrypto = Camellia(self.SK_ei, iv)
        ikehash = HMAC(self.SK_ai, digestmod=sha256)
        logger.debug('IV: {}'.format(dump(iv)))

        # Encrypt
        plain = bytes(packet)[const.IKE_HEADER.size:]
        ciphertext = ikecrypto.encrypt(plain)
        sk = payloads.SK(next_payload=packet.payloads[0]._type, iv=iv, ciphertext=ciphertext)
        final.add_payload(sk)
        logger.debug(dump(bytes(final)))

        # Sign
        ikehash.update(bytes(final)[:-MACLEN])
        mac = ikehash.digest()[:MACLEN]
        sk.mac(mac)

        logger.debug(dump(bytes(final)))
        return bytes(final)
开发者ID:NetSPI,项目名称:ike,代码行数:30,代码来源:protocol.py

示例3: _create_empty

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
    def _create_empty(self, password):

        assert type(password) != unicode

        self.f_tag = "PWS3"
        self.f_salt = Vault._urandom(32)
        self.f_iter = 2048
        stretched_password = self._stretch_password(password, self.f_salt, self.f_iter)
        self.f_sha_ps = hashlib.sha256(stretched_password).digest()

        cipher = TwofishECB(stretched_password)
        self.f_b1 = cipher.encrypt(Vault._urandom(16))
        self.f_b2 = cipher.encrypt(Vault._urandom(16))
        self.f_b3 = cipher.encrypt(Vault._urandom(16))
        self.f_b4 = cipher.encrypt(Vault._urandom(16))
        key_k = cipher.decrypt(self.f_b1) + cipher.decrypt(self.f_b2)
        key_l = cipher.decrypt(self.f_b3) + cipher.decrypt(self.f_b4)

        self.f_iv = Vault._urandom(16)

        hmac_checker = HMAC(key_l, "", hashlib.sha256)
        cipher = TwofishCBC(key_k, self.f_iv)

        # No records yet

        self.f_hmac = hmac_checker.digest()
开发者ID:nerdynick,项目名称:loxodo,代码行数:28,代码来源:vault.py

示例4: db_create_header

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
  def db_create_header(self, password, vault):
    vault.f_tag = self.db_version_tag
    vault.f_salt = vault.urandom(32)
    vault.f_iter = 2048

    # Database version 4 uses one master password which is random generated
    # and secondary passwords to encrypt them.
    # XXX What about master normal password ?
    rand_p = random_password()
    rand_p.password_length = 32
    master_passwd = rand_p.generate_password()

    stretched_master_password = vault._stretch_password(master_passwd, vault.f_salt, vault.f_iter)
    vault.f_sha_ps = hashlib.sha256(stretched_master_password).digest()

    cipher = TwofishECB(stretched_master_password)
    vault.f_b1 = cipher.encrypt(vault.urandom(16))
    vault.f_b2 = cipher.encrypt(vault.urandom(16))
    vault.f_b3 = cipher.encrypt(vault.urandom(16))
    vault.f_b4 = cipher.encrypt(vault.urandom(16))
    key_k = cipher.decrypt(vault.f_b1) + cipher.decrypt(vault.f_b2)
    key_l = cipher.decrypt(vault.f_b3) + cipher.decrypt(vault.f_b4)

    vault.f_iv = vault.urandom(16)

    hmac_checker = HMAC(key_l, "", hashlib.sha256)

    # No records yet
    vault.f_hmac = hmac_checker.digest()

    # Encrypt master password with user one
    stretched_user_pass = vault._stretch_password(password, vault.f_salt, vault.f_iter)
    user_cipher = TwofishECB(stretched_user_pass)
    self.db_v4_passwds = [{'auth': self.db_ptag[0], 'passwd': user_cipher.encrypt(stretched_master_password), 'orig': '1'}]
开发者ID:haad,项目名称:loxodo,代码行数:36,代码来源:vaultver4.py

示例5: __findHashedHostname

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
 def __findHashedHostname(self,hostname):
     for (key,salt,res) in self.hashes:
         hmac = HMAC(salt, None, sha1)
         hmac.update(hostname)
         ours = hmac.digest()
         if ours == res:
             return self.hosts.get(key)
     return None
开发者ID:maxtaco,项目名称:python-framed-msgpack-rpc,代码行数:10,代码来源:ssh_known_hosts.py

示例6: response

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
  def response(self, challenge):
    if(self.server_signature):
      self.evaluateOutcome(challenge)
      return ""
    else:
      serverChallenge, salt, iterations = challenge.split(",")
      self.server_nonce = serverChallenge[2:]
      if self.server_nonce.find(self.client_nonce) != 0:
        raise SaslException("Server nonce does not start with client nonce")
      self.salt = base64.b64decode(salt[2:])

      iterations = int(iterations[2:])

      hmac = HMAC(key=self.password.replace("=","=3D").replace(",","=2C"),digestmod=self.algorithm)

      hmac.update(self.salt)
      hmac.update("\x00\x00\x00\x01")

      saltedPassword = hmac.digest()
      previous = saltedPassword

      for i in range(1,iterations):
        hmac = HMAC(key=self.password.replace("=","=3D").replace(",","=2C"),digestmod=self.algorithm)
        hmac.update(previous)
        previous = hmac.digest()
        saltedPassword = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(saltedPassword,previous))

      clientFinalMessageWithoutProof = "c=" + base64.b64encode("n,,") + ",r=" + self.server_nonce
      authMessage = self.client_first_message + "," + challenge + "," + clientFinalMessageWithoutProof

      clientKey = HMAC(key=saltedPassword,msg="Client Key",digestmod=self.algorithm).digest()
      hashFunc = self.algorithm()
      hashFunc.update(clientKey)
      storedKey = hashFunc.digest()

      clientSignature = HMAC(key=storedKey, msg=authMessage, digestmod=self.algorithm).digest()

      clientProof = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(clientKey,clientSignature))

      serverKey = HMAC(key=saltedPassword,msg="Server Key",digestmod=self.algorithm).digest()

      self.server_signature = HMAC(key=serverKey,msg=authMessage,digestmod=self.algorithm).digest()
      return clientFinalMessageWithoutProof + ",p=" + base64.b64encode(clientProof)
开发者ID:ChugR,项目名称:qpid-python,代码行数:45,代码来源:scram.py

示例7: encrypt_sign_bytes

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
	def encrypt_sign_bytes(self, raw_msg, encode_func = base64.b64encode):
		assert(type(raw_msg) == str)

		## encrypt, then sign (HMAC = H((K ^ O) | H((K ^ I) | M)))
		enc_msg = self.encrypt_encode_bytes(raw_msg, null_encode)
		msg_mac = HMAC_FUNC(self.get_key(), enc_msg, HMAC_HASH)
		msg_mac = encode_func(msg_mac.digest())
		enc_msg = encode_func(enc_msg)

		return (enc_msg, msg_mac)
开发者ID:Anarchid,项目名称:uberserver,代码行数:12,代码来源:CryptoHandler.py

示例8: _sign

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
    def _sign(self, stringToSign):
        """
        Sign a request using the secret key. Reference: U{http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html}

        @param stringToSign: the string to sign for the request
        @type stringToSign: str
        @return: Amazon S3-required HMAC signature
        @rtype: str
        """
        h=HMAC(self.secretKey, digestmod=sha1)
        h.update(stringToSign)
        return base64.b64encode(h.digest())
开发者ID:aytsai,项目名称:ricebowl,代码行数:14,代码来源:s3.py

示例9: sas

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
def sas(sbNamespace,sbEntityPath,sharedAccessKey,sharedAccessKeyName):
   uri = "http://" + sbNamespace + ".servicebus.windows.net/" + sbEntityPath

   encodedResourceUri = quote_plus(uri)
   expireInSeconds = floor( time.time() + 300 + .5 )
   plainSignature = encodedResourceUri + "\n" + str(expireInSeconds)

   plainSignature = plainSignature.encode('utf-8')
   signed_hmac_sha256 = HMAC(sharedAccessKey,plainSignature,sha256)
   digest = signed_hmac_sha256.digest()
   encoded_digest = b64encode(digest)
   return "SharedAccessSignature sig=%s&se=%s&skn=%s&sr=%s" % (quote_plus(encoded_digest),expireInSeconds, sharedAccessKeyName, encodedResourceUri)
开发者ID:cswiger,项目名称:azureSbQueue,代码行数:14,代码来源:sas.py

示例10: verify_hmac

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
    def verify_hmac(self, data):
        """
        Verifies the HMAC signature of an encrypted (SK, 46) payload using self.SK_ar

        :param data: bytes(payloads.SK())
        :raise IkeError: if calculated signature does not match the one in the payload
        """
        hmac = HMAC(self.SK_ar, digestmod=sha256)
        hmac_theirs = data[-MACLEN:]
        hmac.update(data[:-MACLEN])
        hmac_ours = hmac.digest()[:MACLEN]
        logger.debug('HMAC verify (ours){} (theirs){}'.format(
            binascii.hexlify(hmac_ours), binascii.hexlify(hmac_theirs)))
        if hmac_ours != hmac_theirs:
            raise IkeError('HMAC verify failed')
开发者ID:NetSPI,项目名称:ike,代码行数:17,代码来源:protocol.py

示例11: auth_decrypt_bytes

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
    def auth_decrypt_bytes(self, enc_msg, msg_mac, decode_func=base64.b64decode):
        assert type(enc_msg) == str
        assert type(msg_mac) == str

        # auth, then decrypt
        msg_mac = decode_func(msg_mac)
        enc_msg = decode_func(enc_msg)
        our_mac = HMAC_FUNC(self.get_key(), enc_msg, HMAC_HASH)
        our_mac = our_mac.digest()

        if verify_message_auth_code(our_mac, msg_mac, self.get_key()):
            return self.decode_decrypt_bytes(enc_msg, null_decode)

        # counts as false
        return ""
开发者ID:TurBoss,项目名称:JauriaLobby,代码行数:17,代码来源:crypto_handler.py

示例12: db_create_header

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
  def db_create_header(self, password, vault):
    vault.f_tag = self.db_version_tag
    vault.f_salt = vault.urandom(32)
    vault.f_iter = 2048

    stretched_password = vault._stretch_password(password, vault.f_salt, vault.f_iter)
    vault.f_sha_ps = hashlib.sha256(stretched_password).digest()

    cipher = TwofishECB(stretched_password)
    vault.f_b1 = cipher.encrypt(vault.urandom(16))
    vault.f_b2 = cipher.encrypt(vault.urandom(16))
    vault.f_b3 = cipher.encrypt(vault.urandom(16))
    vault.f_b4 = cipher.encrypt(vault.urandom(16))
    key_k = cipher.decrypt(vault.f_b1) + cipher.decrypt(vault.f_b2)
    key_l = cipher.decrypt(vault.f_b3) + cipher.decrypt(vault.f_b4)

    vault.f_iv = vault.urandom(16)

    hmac_checker = HMAC(key_l, "", hashlib.sha256)

    # No records yet
    vault.f_hmac = hmac_checker.digest()
开发者ID:haad,项目名称:loxodo,代码行数:24,代码来源:vaultver3.py

示例13: hmac_sha256

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
 def hmac_sha256(secret, msg):
     hmac = HMAC(secret, msg=msg, digestmod=hashlib.sha256)
     val = hmac.digest()
     return val
开发者ID:gsnbng,项目名称:LinOTP,代码行数:6,代码来源:migrate.py

示例14: _read_from_file

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
    def _read_from_file(self, filename, password):
        """
        Initialize all class members by loading the contents of a Vault stored in the given file.
        """
        assert type(password) != unicode

        filehandle = file(filename, "rb")

        # read boilerplate

        self.f_tag = filehandle.read(4)  # TAG: magic tag
        if self.f_tag != "PWS3":
            raise self.VaultVersionError("Not a PasswordSafe V3 file")

        self.f_salt = filehandle.read(32)  # SALT: SHA-256 salt
        self.f_iter = struct.unpack("<L", filehandle.read(4))[0]  # ITER: SHA-256 keystretch iterations
        stretched_password = self._stretch_password(password, self.f_salt, self.f_iter)  # P': the stretched key
        my_sha_ps = hashlib.sha256(stretched_password).digest()

        self.f_sha_ps = filehandle.read(32)  # H(P'): SHA-256 hash of stretched passphrase
        if self.f_sha_ps != my_sha_ps:
            raise self.BadPasswordError("Wrong password")

        self.f_b1 = filehandle.read(16)  # B1
        self.f_b2 = filehandle.read(16)  # B2
        self.f_b3 = filehandle.read(16)  # B3
        self.f_b4 = filehandle.read(16)  # B4

        cipher = TwofishECB(stretched_password)
        key_k = cipher.decrypt(self.f_b1) + cipher.decrypt(self.f_b2)
        key_l = cipher.decrypt(self.f_b3) + cipher.decrypt(self.f_b4)

        self.f_iv = filehandle.read(16)  # IV: initialization vector of Twofish CBC

        hmac_checker = HMAC(key_l, "", hashlib.sha256)
        cipher = TwofishCBC(key_k, self.f_iv)

        # read header

        while True:
            field = self._read_field_tlv(filehandle, cipher)
            if not field:
                break
            if field.raw_type == 0xFF:
                break
            self.header.add_raw_field(field)
            hmac_checker.update(field.raw_value)

        # read fields

        current_record = self.Record()
        while True:
            field = self._read_field_tlv(filehandle, cipher)
            if not field:
                break
            if field.raw_type == 0xFF:
                self.records.append(current_record)
                current_record = self.Record()
            else:
                hmac_checker.update(field.raw_value)
                current_record.add_raw_field(field)

        # read HMAC

        self.f_hmac = filehandle.read(32)  # HMAC: used to verify Vault's integrity

        my_hmac = hmac_checker.digest()
        if self.f_hmac != my_hmac:
            raise self.VaultFormatError("File integrity check failed")

        self.records.sort()
        filehandle.close()
开发者ID:nerdynick,项目名称:loxodo,代码行数:74,代码来源:vault.py

示例15: auth_decrypt_bytes_utf8

# 需要导入模块: from hmac import HMAC [as 别名]
# 或者: from hmac.HMAC import digest [as 别名]
	def auth_decrypt_bytes_utf8(self, (enc_msg, msg_mac), decode_func = base64.b64decode):
		return (self.auth_decrypt_bytes((enc_msg.encode(UNICODE_ENCODING), msg_mac.encode(UNICODE_ENCODING)), decode_func))

	def encrypt_sign_bytes(self, raw_msg, encode_func = base64.b64encode):
		assert(type(raw_msg) == str)

		## encrypt, then sign (HMAC = H((K ^ O) | H((K ^ I) | M)))
		enc_msg = self.encrypt_encode_bytes(raw_msg, null_encode)
		msg_mac = HMAC_FUNC(self.get_key(), enc_msg, HMAC_HASH)
		msg_mac = encode_func(msg_mac.digest())
		enc_msg = encode_func(enc_msg)

		return (enc_msg, msg_mac)

	def auth_decrypt_bytes(self, (enc_msg, msg_mac), decode_func = base64.b64decode):
		assert(type(enc_msg) == str)
		assert(type(msg_mac) == str)

		## auth, then decrypt
		msg_mac = decode_func(msg_mac)
		enc_msg = decode_func(enc_msg)
		our_mac = HMAC_FUNC(self.get_key(), enc_msg, HMAC_HASH)
		our_mac = our_mac.digest()

		if (verify_message_auth_code(our_mac, msg_mac, self.get_key())):
			return (self.decode_decrypt_bytes(enc_msg, null_decode))

		## counts as false
		return ""

开发者ID:Anarchid,项目名称:uberserver,代码行数:31,代码来源:CryptoHandler.py


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