コード例 #1
0
ファイル: protocol.py プロジェクト: NetSPI/ike
    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)
コード例 #2
0
ファイル: vault.py プロジェクト: nerdynick/loxodo
    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()
コード例 #3
0
ファイル: vaultver4.py プロジェクト: haad/loxodo
  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'}]
コード例 #4
0
 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
コード例 #5
0
ファイル: models.py プロジェクト: HearthSim/HSReplay.net
	def generate_signature(self):
		from hmac import HMAC
		from hashlib import sha256

		key = self.webhook.secret.encode("utf-8")
		msg = self.payload.encode("utf-8")
		mac = HMAC(key, msg, digestmod=sha256)

		return "sha256=" + mac.hexdigest()
コード例 #6
0
ファイル: CryptoHandler.py プロジェクト: Anarchid/uberserver
	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)
コード例 #7
0
ファイル: hashTest.py プロジェクト: lightsec/pyNist800-108
 def test_crypto_package_str(self):
     from Crypto.Hash import HMAC
     
     hmac = HMAC.new("", digestmod=SHA1Hash())
     self.assertEquals(hmac.hexdigest(), self.result['empty'])
     
     #hex_string = binascii.hexlify(self.not_empty)
     hmac = HMAC.new("key", digestmod=SHA1Hash())
     hmac.update("The quick brown fox jumps over the lazy dog")
     self.assertEquals(hmac.hexdigest(), self.result['not_empty'])
コード例 #8
0
ファイル: bitce.py プロジェクト: potterzot/bit-trader
 def _make_request(self, data):
     bsecret = self._secret.encode('ascii')
     sign = HMAC(bsecret, digestmod=sha512)
     sign.update(data.encode('ascii'))
 
     header = {
         'Content-type': self.content_type,
         'Key': self._key,
         'Sign': sign.hexdigest()
     }
     
     return Request(self.base, data, header)
コード例 #9
0
ファイル: ck-helper.py プロジェクト: Bithome/coinkite-python
def make_signature(endpoint, force_ts=None):
    #
    # Pick a timestamp and perform the signature required.
    #
    assert endpoint[0] == '/' and 'api.coinkite.com' not in endpoint, \
                "Expecting abs url, got: %s" % endpoint
     
    ts = force_ts or datetime.datetime.utcnow().isoformat()
    data = endpoint + "|" + ts
    hm = HMAC(API_SECRET, msg=data, digestmod=sha256)

    return hm.hexdigest(), ts
コード例 #10
0
ファイル: sas.py プロジェクト: cswiger/azureSbQueue
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)
コード例 #11
0
ファイル: test_hmac.py プロジェクト: bynds/micropython-lib
    def shatest(key, data, digest):
        h = HMAC(key, data, digestmod=_hashlib.sha1)
        assertEqual(h.hexdigest().upper(), digest.upper())
        assertEqual(h.name, "hmac-sha1")
        assertEqual(h.digest_size, 20)
        assertEqual(h.block_size, 64)

        h = HMAC(key, data, digestmod='sha1')
        assertEqual(h.hexdigest().upper(), digest.upper())
        assertEqual(h.name, "hmac-sha1")
        assertEqual(h.digest_size, 20)
        assertEqual(h.block_size, 64)
コード例 #12
0
ファイル: s3.py プロジェクト: aytsai/ricebowl
    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())
コード例 #13
0
ファイル: sign.py プロジェクト: pyarnold/ipython
    def compute_signature(self, nb):
        """Compute a notebook's signature

        by hashing the entire contents of the notebook via HMAC digest.
        """
        hmac = HMAC(self.secret, digestmod=self.digestmod)
        # don't include the previous hash in the content to hash
        with signature_removed(nb):
            # sign the whole thing
            for b in yield_everything(nb):
                hmac.update(b)

        return hmac.hexdigest()
コード例 #14
0
ファイル: protocol.py プロジェクト: NetSPI/ike
    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')
コード例 #15
0
ファイル: crypto_handler.py プロジェクト: TurBoss/JauriaLobby
    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 ""
コード例 #16
0
ファイル: hashTest.py プロジェクト: lightsec/pyNist800-108
 def test_crypto_package_hex(self):
     from Crypto.Hash import HMAC
     
     k_hex = binascii.hexlify("")
     hmac = HMAC.new(k_hex, digestmod=SHA1Hash())
     self.assertEquals(hmac.hexdigest(), self.result['empty'])
             
     # binascii.hexlify(ki)
     k_hex = bytearray( b'\x6b\x65\x79' )
     # binascii.hexlify("The quick brown fox jumps over the lazy dog")
     d_hex = bytearray( b'\x54\x68\x65\x20\x71\x75\x69\x63\x6b\x20\x62\x72\x6f\x77\x6e\x20\x66\x6f\x78\x20\x6a\x75\x6d\x70\x73\x20\x6f\x76\x65\x72\x20\x74\x68\x65\x20\x6c\x61\x7a\x79\x20\x64\x6f\x67' ) 
     
     hmac = HMAC.new(str(k_hex.decode("utf-8")), msg=str(d_hex.decode("utf-8")), digestmod=SHA1Hash())
     # hmac.update(d_hex) # or without "msg" param and with this call
     self.assertEquals(hmac.hexdigest(), self.result['not_empty'])
コード例 #17
0
ファイル: CryptoHandler.py プロジェクト: Anarchid/uberserver
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))
コード例 #18
0
ファイル: password.py プロジェクト: AnishShah/roundup
 def _pbkdf2(password, salt, rounds, keylen):
     digest_size = 20 # sha1 generates 20-byte blocks
     total_blocks = int((keylen+digest_size-1)/digest_size)
     hmac_template = HMAC(password, None, sha1)
     out = _bempty
     for i in xrange(1, total_blocks+1):
         hmac = hmac_template.copy()
         hmac.update(salt + pack(">L",i))
         block = tmp = hmac.digest()
         for j in xrange(rounds-1):
             hmac = hmac_template.copy()
             hmac.update(tmp)
             tmp = hmac.digest()
             #TODO: need to speed up this call
             block = xor_bytes(block, tmp)
         out += block
     return out[:keylen]
コード例 #19
0
def send_status(session,msg_type='doorspush'):
	if not msg_type in ['doorspush','doorsbeat']:
		raise ValueError('msg_type must be "doorspush" or "doorsbeat" not "{}"'.format(msg_type))
	stat=get_status(session)
	is_open=None
	if stat.req_type=='open':
		is_open=True
	if stat.req_type=='close':
		is_open=False
	changed_on=stat.date.isoformat()
	payload={'type':msg_type,'open':is_open,'changed_on':changed_on}
	data=json.dumps({'client_id':config.fablab_client_id,'created_on':datetime.now(utc).isoformat(),'payload':payload}).encode('UTF-8')
	hmac=HMAC(msg=data,key=config.fablab_client_key.encode('UTF-8'))
	postdata=json.dumps({'hmac':hmac.hexdigest(),'data':data.decode('UTF-8')})
	try:
		req=urlopen(config.api_addr,data=postdata.encode('UTF-8'))
	except HTTPError as e:
		return (e)
	return req
コード例 #20
0
ファイル: scram.py プロジェクト: ChugR/qpid-python
  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)
コード例 #21
0
ファイル: vaultver3.py プロジェクト: haad/loxodo
  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()
コード例 #22
0
ファイル: gauth.py プロジェクト: vvoody/crap
def hotp(key, counter):
    """
  http://tools.ietf.org/html/rfc4226
  """
    # convert counter to raw bytes
    b = pack(">q", counter)

    # generate HMAC-SHA1 from timestamp based on secret key
    hm = HMAC(key, b, sha1).digest()

    # extract 4 bytes from digest based on LSB
    offset = ord(hm[-1]) & 0x0F
    truncatedHash = hm[offset:offset + 4]

    # get the code from it
    code = ((unpack(">L", truncatedHash)[0]) & 0x7FFFFFFF) % 1000000

    return "0" * (6 - len(str(code))) + str(code)
コード例 #23
0
def encrypt_password(password, salt=None):
    """Hash password on the fly."""
    if salt is None:
        salt = os.urandom(8)  # 64 bits.

    assert 8 == len(salt)
    assert isinstance(salt, str)

    if isinstance(password, unicode):
        password = password.encode('UTF-8')

    assert isinstance(password, str)

    result = password
    for i in xrange(10):
        result = HMAC(result, salt, sha256).digest()

    return salt + result
コード例 #24
0
def _generate_sas_token(uri, policy, key, expiry=None):
    """Create a shared access signiture token as a string literal.
    :returns: SAS token as string literal.
    :rtype: str
    """
    if not expiry:
        expiry = time.time() + 3600  # Default to 1 hour.
    encoded_uri = quote_plus(uri)
    ttl = int(expiry)
    sign_key = '{}\n{}'.format(encoded_uri, ttl)
    signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())
    result = {
        'sr': uri,
        'sig': signature,
        'se': str(ttl)}
    if policy:
        result['skn'] = policy
    return 'SharedAccessSignature ' + urlencode(result)
コード例 #25
0
ファイル: 0021.py プロジェクト: Magicwangs/show-me-the-code
def encrypt_password(password, salt=None):
    if salt is None:
        salt = os.urandom(8)  ##随机生成8个字节的字符串,用作随机加密的Key

    assert 8 == len(salt)  ##断言,如果不为真就出现异常
    assert isinstance(salt, str)

    if isinstance(password, unicode):
        password = password.encode('UTF-8')

    assert isinstance(password, str)

    result = password
    for i in xrange(10):
        ##选择 SHA-256 算法使用 HMAC 对密码和 salt 进行 10 次叠代混淆
        result = HMAC(result, salt, sha256).digest()

    return salt + result
コード例 #26
0
    def encrypt(self, salt=None):
        if salt is None:
            salt = os.urandom(8)

        assert len(salt) == 8
        assert isinstance(salt, bytes)

        if isinstance(self.password, str):
            password = self.password.encode('UTF-8')
        else:
            password = self.password
        assert isinstance(password, bytes)

        result = password
        for i in range(10):
            result = HMAC(result, salt, sha256).digest()

        return salt + result
コード例 #27
0
def encrypt_password(password, salt=None):
    if salt is None:
        salt = os.urandom(8)

    assert 8 == len(salt)
    #    assert isinstance(salt, str)

    if isinstance(password, str):
        password = password.encode('utf-8')


#    assert isinstance(password, str)

    result = password
    for i in range(10):
        result = HMAC(result, salt, sha256).digest()

    return salt + result
コード例 #28
0
def bip32_master_prvkey_from_seed(bip32_seed, version):
    """Derive the master extended private key from the seed"""
    if type(bip32_seed) == str:
        bip32_seed = bytes.fromhex(bip32_seed)
    assert version in PRIVATE, "wrong version, master key must be private"

    "First derive the master private key"
    hashValue = HMAC(b"Bitcoin seed", bip32_seed, sha512).digest()
    mprv = int.from_bytes(hashValue[:32], 'big') % ec.order

    "Then derive the extended master private key"
    xmprv = version  # version
    xmprv += b'\x00'  # depth
    xmprv += b'\x00\x00\x00\x00'  # parent pubkey fingerprint
    xmprv += b'\x00\x00\x00\x00'  # child index
    xmprv += hashValue[32:]  # chain code
    xmprv += b'\x00' + mprv.to_bytes(32, 'big')  # private key
    return b58encode_check(xmprv)
コード例 #29
0
 def child(self, index):
     if index >= 0x80000000:
         raise ValueError('child number should always be less than 2^31')
     sec = self.point.sec()
     data = sec + index.to_bytes(4, 'big')
     raw = HMAC(key=self.chain_code, msg=data, digestmod=sha512).digest()
     point = PrivateKey(int.from_bytes(raw[:32], 'big')).point + self.point
     chain_code = raw[32:]
     depth = self.depth + 1
     fingerprint = hash160(sec)[:4]
     child_number = index
     return HDPublicKey(
         point=point,
         chain_code=chain_code,
         depth=depth,
         fingerprint=fingerprint,
         child_number=child_number,
     )
コード例 #30
0
ファイル: test_hsm.py プロジェクト: vmalarcon/firmware
        def __call__(self, username, garbage=False, do_replay=False):
            # calc right values!
            from base64 import b32decode

            mode, secret, _ = TEST_USERS[username]

            if garbage:
                pw = b'\x12'*32 if mode == USER_AUTH_HMAC else b'123x23'
                cnt = (self.tt if mode == USER_AUTH_TOTP else 0)
            elif mode == USER_AUTH_HMAC:
                assert len(self.psbt_hash) == 32
                assert username == 'pw'
                cnt = 0

                from hmac import HMAC

                key = calc_hmac_key(dev.serial) 
                pw = HMAC(key, self.psbt_hash, sha256).digest()

                #print("\n  pw=%s\n key=%s\npsbt=%s\nsalt=%s\n" % (
                #    b2a_hex(pw),
                #    b2a_hex(key),
                #    b2a_hex(self.psbt_hash),
                #    b2a_hex(salt)))

                assert not do_replay
            else:
                if do_replay:
                    if mode == USER_AUTH_TOTP:
                        cnt = self.tt-1
                    elif mode == USER_AUTH_HOTP:
                        cnt = self.ht-1
                else:
                    if mode == USER_AUTH_TOTP:
                        cnt = self.tt; self.tt += 1
                    elif mode == USER_AUTH_HOTP:
                        cnt = self.ht; self.ht += 1

                pw = b'%06d' % get_hotp(secret, cnt)

            assert len(pw) in {6, 32}

            # no feedback from device at this point.
            dev.send_recv(CCProtocolPacker. user_auth(username.encode('ascii'), pw, totp_time=cnt))
コード例 #31
0
 def unpack_and_verify_manifest(self, data, force_tam_not_required=False):
     """Unpack msgpacked *data* and return (object, did_verify)."""
     if data.startswith(b'\xc1' * 4):
         # This is a manifest from the future, we can't read it.
         raise UnsupportedManifestError()
     tam_required = self.tam_required
     if force_tam_not_required and tam_required:
         logger.warning('Manifest authentication DISABLED.')
         tam_required = False
     data = bytearray(data)
     unpacker = get_limited_unpacker('manifest')
     unpacker.feed(data)
     unpacked = unpacker.unpack()
     if b'tam' not in unpacked:
         if tam_required:
             raise TAMRequiredError(
                 self.repository._location.canonical_path())
         else:
             logger.debug('TAM not found and not required')
             return unpacked, False
     tam = unpacked.pop(b'tam', None)
     if not isinstance(tam, dict):
         raise TAMInvalid()
     tam_type = tam.get(b'type', b'<none>').decode('ascii', 'replace')
     if tam_type != 'HKDF_HMAC_SHA512':
         if tam_required:
             raise TAMUnsupportedSuiteError(repr(tam_type))
         else:
             logger.debug(
                 'Ignoring TAM made with unsupported suite, since TAM is not required: %r',
                 tam_type)
             return unpacked, False
     tam_hmac = tam.get(b'hmac')
     tam_salt = tam.get(b'salt')
     if not isinstance(tam_salt, bytes) or not isinstance(tam_hmac, bytes):
         raise TAMInvalid()
     offset = data.index(tam_hmac)
     data[offset:offset + 64] = bytes(64)
     tam_key = self._tam_key(tam_salt, context=b'manifest')
     calculated_hmac = HMAC(tam_key, data, sha512).digest()
     if not compare_digest(calculated_hmac, tam_hmac):
         raise TAMInvalid()
     logger.debug('TAM-verified manifest')
     return unpacked, True
コード例 #32
0
    def hmactest(key, data, hexdigests):
        hmac_name = "hmac-" + hash_name
        h = HMAC(key, data, digestmod=hashfunc)
        assertEqual(h.hexdigest().lower(), hexdigests[hashfunc])
        assertEqual(h.name, hmac_name)
        assertEqual(h.digest_size, digest_size)
        assertEqual(h.block_size, block_size)

        h = HMAC(key, data, digestmod=hash_name)
        assertEqual(h.hexdigest().lower(), hexdigests[hashfunc])
        assertEqual(h.name, hmac_name)
        assertEqual(h.digest_size, digest_size)
        assertEqual(h.block_size, block_size)
コード例 #33
0
ファイル: daraz_connector.py プロジェクト: zamzamintl/daraz
    def doConnection(self, action=None, req=None):
        url = self.api_url
        key = self.api_key
        action = action if action else "GetBrands"
        format = "json"
        userId = self.userId
        method = req if req else 'GET'
        self.state = 'connected'
        super(DarazConnector, self).write({"state": "connected"})
        now = datetime.now().timestamp()
        test = datetime.fromtimestamp(
            now, tz=timezone.utc).replace(microsecond=0).isoformat()
        parameters = {
            'UserID': userId,
            'Version': "1.0",
            'Action': action,
            'Format': format,
            'Timestamp': test
        }

        concatenated = urllib.parse.urlencode(sorted(parameters.items()))
        data = concatenated.encode('utf-8')
        parameters['Signature'] = HMAC(key.encode('utf-8'), data,
                                       sha256).hexdigest()

        headers = {
            'Content-Type': "application/x-www-form-urlencoded",
            'Accept': "*/*",
            'Connection': "keep-alive",
            'cache-control': "no-cache"
        }
        try:
            response = requests.request(method,
                                        url,
                                        headers=headers,
                                        params=parameters)
        except Exception as e:
            raise Warning(_(response.text))

        if response.status_code == 200:
            self.state = 'connected'
            self.env.cr.commit()
            raise Warning(_("Successfully Connected"))
        return response.text
コード例 #34
0
ファイル: __init__.py プロジェクト: ulif/pulp
    def _pbkdf_sha256(self, password, salt, iterations):
        """
        Apply the salt to the password some number of times to increase randomness.

        :param password: plaintext password
        :type  password: str
        :param salt: random set of characters to encode the password
        :type  salt: str
        :param iterations: number of times to apply the salt
        :type  iterations: int

        :return: hashed password
        :rtype:  str
        """
        result = password
        for i in xrange(iterations):
            result = HMAC(result, salt,
                          digestmod).digest()  # use HMAC to apply the salt
        return result
コード例 #35
0
def encypt_password(password, salt=None):
    if salt is None:
        salt = os.urandom(8)  #64bit

    if isinstance(salt, str):
        salt = salt.encode(encoding='utf-8')
        print('salt=', salt)

    #assert 8==len(salt)  #assert 断言
    #assert isinstance(salt,str)

    #password=password.decode()

    result = password.encode(encoding='utf-8')
    print('result=', result)
    for i in range(10):
        result = HMAC(result, salt, sha256).digest()

    return salt + result
コード例 #36
0
 def _sign_for_blobs(self,
                     verb: str,
                     canonicalized: str,
                     headers={},
                     payload='') -> dict:
     """Compute SharedKeyLite authorization header and add standard headers"""
     headers = self._headers(headers)
     signing_headers = sorted(filter(lambda x: 'x-ms' in x, headers.keys()))
     canon_headers = "\n".join("{}:{}".format(k, headers[k])
                               for k in signing_headers)
     sign = "\n".join([
         verb, '', headers['Content-Type'], '', canon_headers, canonicalized
     ]).encode('utf-8')
     return {
         'Authorization': 'SharedKeyLite {}:{}'.format(self.account, \
             b64encode(HMAC(self.auth, sign, sha256).digest()).decode('utf-8')),
         'Content-Length': str(len(payload)),
         **headers
     }
コード例 #37
0
def encrypt_pwd(password, salt=None):
    """Hash password on the fly."""
    if salt is None:
        # hexlify函数返回 二进制bytes类型数据的十六进制bytes类型,
        # 两位十六进制表示一个字节,所以长度是原来数据的两倍
        salt = os.urandom(8)  # 64 bits.

    assert 8 == len(salt)
    assert isinstance(salt, bytes)

    if isinstance(password, str):
        password = password.encode('UTF-8')
    result = password
    # 这里先随机生成 64 bits 的 salt,再选择 SHA-256 算法使用 HMAC 对密码和 salt 进行 10 次叠代混淆
    # 最后将 salt 和 hash 结果一起返回。
    for i in range(10):
        result = HMAC(result, salt, sha256).digest()

    return salt + result
コード例 #38
0
ファイル: [test]hashlogin.py プロジェクト: SIGESI/PythonTP3
def encrypt_password(password, salt=None):
    """Hash password on the fly."""
    if salt is None:
        salt = os.urandom(8)  # 64 bits.  #ajouter salage

    assert 8 == len(salt)
    assert isinstance(salt, bytes)
    assert isinstance(password, str)

    if isinstance(password, str):
        password = password.encode('UTF-8')

    assert isinstance(password, bytes)

    result = password
    for i in range(10):
        result = HMAC(result, salt, hashlib.sha256).digest()

    return str(salt + result)
コード例 #39
0
ファイル: vkAuth.py プロジェクト: nickyfoster/ybsapi2
def vk_auth(url: str, client_secret: str) -> bool:
    """
    Checks VK App signature
    :param url: str
    :param client_secret: str
    :return: bool
    """
    query = dict(parse_qsl(urlparse(url).query, keep_blank_values=True))
    vk_subset = OrderedDict(
        sorted(x for x in query.items() if x[0][:3] == "vk_"))

    hash_code = b64encode(
        HMAC(client_secret.encode(),
             urlencode(vk_subset, doseq=True).encode(), sha256).digest())
    decoded_hash_code = hash_code.decode('utf-8')[:-1].replace('+',
                                                               '-').replace(
                                                                   '/', '_')

    return query["sign"] == decoded_hash_code
コード例 #40
0
def bip32_master_prvkey_from_seed(bip32_seed: Union[str, bytes], version: bytes) -> bytes:
    """derive the master extended private key from the seed"""
    if type(bip32_seed) == str: # hex string
        bip32_seed = bytes.fromhex(bip32_seed)
    assert version in PRIVATE, "wrong version, master key must be private"

    # serialization data
    xmprv = version                             # version
    xmprv += b'\x00'                            # depth
    xmprv += b'\x00\x00\x00\x00'                # parent pubkey fingerprint
    xmprv += b'\x00\x00\x00\x00'                # child index

    # actual extended key (key + chain code) derivation
    hashValue = HMAC(b"Bitcoin seed", bip32_seed, sha512).digest()
    mprv = int_from_Scalar(ec, hashValue[:32])
    xmprv += hashValue[32:]                     # chain code
    xmprv += b'\x00' + mprv.to_bytes(32, 'big') # private key

    return b58encode_check(xmprv)
コード例 #41
0
    def hash_host(hostname, salt=None):
        """
        Return a "hashed" form of the hostname, as used by OpenSSH when storing
        hashed hostnames in the known_hosts file.

        :param str hostname: the hostname to hash
        :param str salt: optional salt to use when hashing (must be 20 bytes long)
        :return: the hashed hostname as a `str`
        """
        if salt is None:
            salt = os.urandom(sha1().digest_size)
        else:
            if salt.startswith('|1|'):
                salt = salt.split('|')[2]
            salt = decodebytes(b(salt))
        assert len(salt) == sha1().digest_size
        hmac = HMAC(salt, b(hostname), sha1).digest()
        hostkey = '|1|%s|%s' % (u(encodebytes(salt)), u(encodebytes(hmac)))
        return hostkey.replace('\n', '')
コード例 #42
0
ファイル: hashTest.py プロジェクト: lightsec/pyNist800-108
 def test_hmac_package(self):
     from hmac import HMAC
     import hashlib
     
     k_hex = binascii.hexlify("")
     hmac = HMAC(k_hex, digestmod=hashlib.sha1)
     self.assertEquals(hmac.hexdigest(), self.result['empty'])
     
     k_hex = binascii.hexlify("key")
     d_hex = binascii.hexlify("The quick brown fox jumps over the lazy dog")
             
     hmac1 = HMAC(k_hex, digestmod=hashlib.sha1)
     hmac1.update(d_hex)
     self.assertEquals(hmac.hexdigest(), self.result['empty'])
コード例 #43
0
ファイル: attribute.py プロジェクト: zamzamintl/daraz
    def doConnection(self,
                     action=None,
                     req=None,
                     instance_id=False,
                     categoryId=''):
        darazStore = instance_id
        url = darazStore.api_url
        key = darazStore.api_key
        action = action if action else "GetCategoryAttributes"
        format = "json"
        userId = darazStore.userId
        method = req if req else 'GET'

        now = datetime.now().timestamp()
        test = datetime.fromtimestamp(
            now, tz=timezone.utc).replace(microsecond=0).isoformat()
        parameters = {
            'UserID': userId,
            'Version': "1.0",
            'Action': action,
            'Format': format,
            'PrimaryCategory': categoryId,
            'Timestamp': test
        }
        concatenated = urllib.parse.urlencode(sorted(parameters.items()))
        data = concatenated.encode('utf-8')
        parameters['Signature'] = HMAC(key.encode('utf-8'), data,
                                       sha256).hexdigest()
        headers = {
            'Content-Type': "application/json",
            'Accept': "*/*",
            'Connection': "keep-alive",
            'cache-control': "no-cache"
        }
        try:
            response = requests.request(method,
                                        url,
                                        headers=headers,
                                        params=parameters)
        except Exception as e:
            raise Warning(_(response.text))
        return json.loads(response.text)
コード例 #44
0
ファイル: lazada_lucas.py プロジェクト: zchking/ctdata
 def _post(self, action, extra_param=None, data=None):
     url = self.__url
     parameters = {
         'UserID': self.__user_id,
         'Version': '1.0',
         'Action': action,
         'Format': 'JSON',
         'Timestamp': str(arrow.utcnow().floor('hour'))
     }
     if extra_param:
         parameters.update(extra_param)
     concatenated = urlencode(sorted(parameters.items()))
     parameters['Signature'] = HMAC(self.__api_key, concatenated.encode(),
                                    sha256).hexdigest()
     result = requests.post(url, params=parameters, data=data or {})
     result = json.loads(result.text)
     print(result)
     self.__mongodb.cb_lazada_result.insert(result)
     if result.get("SuccessResponse"):
         return result.get("SuccessResponse").get("Body")
コード例 #45
0
    def generate_sas_token(self):
        """
        Create a shared access signiture token as a string literal.

        Returns:
            result (str): SAS token as string literal.
        """
        encoded_uri = quote_plus(self.uri)
        ttl = int(self.expiry)
        sign_key = '%s\n%d' % (encoded_uri, ttl)
        signature = b64encode(
            HMAC(b64decode(self.key), sign_key.encode('utf-8'),
                 sha256).digest())

        result = {'sr': self.uri, 'sig': signature, 'se': str(ttl)}

        if self.policy:
            result['skn'] = self.policy

        return 'SharedAccessSignature ' + urlencode(result)
コード例 #46
0
def encrypt(password: str, salt: bytes = None) -> bytes:
    """

    密码加密

    :param password: 密码值
    :param salt: salt值,默认不用填写
    :return: 加密后的密码,无法逆向解析

    """
    if salt is None:
        salt = urandom(8)
    assert 8 == len(salt), "salt length is not 8"
    if isinstance(salt, str):
        salt = salt.encode('UTF-8')
    if isinstance(password, str):
        password = password.encode('UTF-8')
    for i in range(10):
        password = HMAC(password, salt, sha256).digest()
    return b2a_base64(salt + password)
コード例 #47
0
ファイル: util.py プロジェクト: eliyahusternberg/zman_alert
def verify_telesign_callback_signature(api_key, signature, json_str):
    """
    Verify that a callback was made by TeleSign and was not sent by a malicious client by verifying the signature.

    :param api_key: the TeleSign API api_key associated with your account.
    :param signature: the TeleSign Authorization header value supplied in the callback, as a string.
    :param json_str: the POST body text, that is, the JSON string sent by TeleSign describing the transaction status.
    """
    your_signature = b64encode(HMAC(b64decode(api_key), json_str.encode("utf-8"), sha256).digest()).decode("utf-8")

    if len(signature) != len(your_signature):
        return False

    # avoid timing attack with constant time equality check
    signatures_equal = True
    for x, y in zip(signature, your_signature):
        if not x == y:
            signatures_equal = False

    return signatures_equal
コード例 #48
0
ファイル: decoding.py プロジェクト: simonzhao88/myBlog
def encrypt_password(password, salt=None):
    """
    密码加密方法
    :param password: 密码
    :param salt: 自定义8位随机数
    :return:
    """
    if salt is None:
        salt = os.urandom(8)  # 64 bits.

    assert 8 == len(salt)

    if isinstance(password, str):
        password = password.encode('UTF-8')

    result = password
    for i in range(10):
        result = HMAC(result, salt, sha256).digest()
        hashed = salt + result
    return hashed
コード例 #49
0
def main():
    key = 'secretkey'

    msg = input('Enter message: ')
    hmac = HMAC(key.encode('utf-8'), msg.encode('utf-8'))

    hashed = base64.b64encode(hmac.digest())
    print('Hashed:', hashed)

    got = send_message(msg)

    check_hmac = HMAC(key.encode('utf-8'), got.encode('utf-8'))
    got_hashed = base64.b64encode(check_hmac.digest())

    print('Is not corruped:', got_hashed == hashed)
コード例 #50
0
class Signer(object):
    """
    When using an RSA algo, the secret is a PEM-encoded private key.
    When using an HMAC algo, the secret is the HMAC signing secret.
    
    Password-protected keyfiles are not supported.
    """
    def __init__(self, secret, algorithm=None):
        if algorithm is None:
            algorithm = DEFAULT_SIGN_ALGORITHM

        assert algorithm in ALGORITHMS, "Unknown algorithm"
        if isinstance(secret, six.string_types):
            secret = secret.encode("ascii")

        self._hash = None
        self.sign_algorithm, self.hash_algorithm = algorithm.split('-')

        if self.sign_algorithm == 'hmac':
            self._hash = HMAC(secret, digestmod=HASHES[self.hash_algorithm])
        else:
            raise NotImplementedError('Only hmac is supported')

    @property
    def algorithm(self):
        return '%s-%s' % (self.sign_algorithm, self.hash_algorithm)

    def _sign_hmac(self, data):
        if isinstance(data, six.string_types): data = data.encode("ascii")
        hmac = self._hash.copy()
        hmac.update(data)
        return hmac.digest()

    def _sign(self, data):
        if isinstance(data, six.string_types): data = data.encode("ascii")
        signed = None
        if self._hash:
            signed = self._sign_hmac(data)
        if not signed:
            raise SystemError('No valid encryptor found.')
        return base64.b64encode(signed).decode("ascii")
コード例 #51
0
def mbi_crypt(key, nonce, iv=None):
    wssec = "WS-SecureConversation"
    from util.cryptography import DES3

    if iv is None:
        iv = bits.getrandbytes(8)

    key1 = key.decode('base64')
    key2 = derive_key(key1, wssec + 'SESSION KEY HASH')
    key3 = derive_key(key1, wssec + 'SESSION KEY ENCRYPTION')

    hash = HMAC(key2, nonce, sha1).digest()

    des = DES3(key3, 2, iv)

    # wincrypt pads with '\x08' bytes
    pad = lambda s: s + ((8 - (len(s) % 8)) * chr(8))
    cipher = des.encrypt(pad(nonce))

    return keystruct(iv, hash,
                     cipher).pack().encode('base64').replace('\n', '')
コード例 #52
0
ファイル: __init__.py プロジェクト: voytecPL/pypwsafev3
 def current_hmac(self, cached=False):
     """Returns the current hmac of self.fulldata"""
     data = b''
     for i in self.headers:
         log.debug("Adding hmac data %r from %r" %
                   (i.hmac_data(), i.__class__.__name__))
         if cached:
             data += i.data
         else:
             data += i.hmac_data()
             # assert i.data == i.hmac_data(), "Working on %r where %r!=%r" % (i, i.data, i.hmac_data())
     for i in self.records:
         # TODO: Add caching support
         log.debug("Adding hmac data %r from %r" %
                   (i.hmac_data(), i.__class__.__name__))
         data += i.hmac_data()
     log.debug("Building hmac with key %s", repr(self.hshkey))
     hm = HMAC(self.hshkey, data, sha256_mod)
     # print hm.hexdigest()
     log.debug("HMAC %s-%s", repr(hm.hexdigest()), repr(hm.digest()))
     return hm.digest()
コード例 #53
0
ファイル: vault.py プロジェクト: nerdynick/loxodo
    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()
コード例 #54
0
ファイル: vault.py プロジェクト: nerdynick/loxodo
    def write_to_file(self, filename, password):
        """
        Store contents of this Vault into a file.
        """
        assert type(password) != unicode

        _last_save = struct.pack("<L", int(time.time()))
        self.header.raw_fields[0x04] = self.Field(0x04, len(_last_save), _last_save)
        _what_saved = "Loxodo 0.0-git".encode("utf_8", "replace")
        self.header.raw_fields[0x06] = self.Field(0x06, len(_what_saved), _what_saved)

        # write to temporary file first
        (osfilehandle, tmpfilename) = tempfile.mkstemp(
            ".part", os.path.basename(filename) + ".", os.path.dirname(filename), text=False
        )
        filehandle = os.fdopen(osfilehandle, "wb")

        # FIXME: choose new SALT, B1-B4, IV values on each file write? Conflicting Specs!

        # write boilerplate

        filehandle.write(self.f_tag)
        filehandle.write(self.f_salt)
        filehandle.write(struct.pack("<L", self.f_iter))

        stretched_password = self._stretch_password(password, self.f_salt, self.f_iter)
        self.f_sha_ps = hashlib.sha256(stretched_password).digest()
        filehandle.write(self.f_sha_ps)

        filehandle.write(self.f_b1)
        filehandle.write(self.f_b2)
        filehandle.write(self.f_b3)
        filehandle.write(self.f_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)

        filehandle.write(self.f_iv)

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

        end_of_record = self.Field(0xFF, 0, "")

        for field in self.header.raw_fields.values():
            self._write_field_tlv(filehandle, cipher, field)
            hmac_checker.update(field.raw_value)
        self._write_field_tlv(filehandle, cipher, end_of_record)
        hmac_checker.update(end_of_record.raw_value)

        for record in self.records:
            for field in record.raw_fields.values():
                self._write_field_tlv(filehandle, cipher, field)
                hmac_checker.update(field.raw_value)
            self._write_field_tlv(filehandle, cipher, end_of_record)
            hmac_checker.update(end_of_record.raw_value)

        self._write_field_tlv(filehandle, cipher, None)

        self.f_hmac = hmac_checker.digest()
        filehandle.write(self.f_hmac)
        filehandle.close()

        try:
            tmpvault = Vault(password, filename=tmpfilename)
        except RuntimeError:
            os.remove(tmpfilename)
            raise self.VaultFormatError("File integrity check failed")

        # after writing the temporary file, replace the original file with it
        try:
            os.remove(filename)
        except OSError:
            pass
        os.rename(tmpfilename, filename)
コード例 #55
0
ファイル: vault.py プロジェクト: haad/loxodo
    def write_to_file(self, filename, password):
        """
        Store contents of this Vault into a file.
        """
        assert type(password) != str

        _last_save = struct.pack("<L", int(time.time()))
        self.header.raw_fields[0x04] = self.Field(0x04, len(_last_save), _last_save)
        _what_saved = prog_name+" "+prog_version.encode("utf_8", "replace")
        self.header.raw_fields[0x06] = self.Field(0x06, len(_what_saved), _what_saved)

        # write to temporary file first
        (osfilehandle, tmpfilename) = tempfile.mkstemp('.part', os.path.basename(filename) + ".", os.path.dirname(filename), text=False)

        self.db_ver.db_open(tmpfilename, 'wb')

        # f_sha_ps should be already defined, why we want to regen it here.
        stretched_password = self.db_ver.db_get_stretched_passwd(self, password)
        self.f_sha_ps = hashlib.sha256(stretched_password).digest()

        self.db_ver.db_write_header(self, password)

        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)

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

        end_of_record = self.Field(0xff, 0, "")

        for field in list(self.header.raw_fields.values()):
            self._write_field_tlv(cipher, field)
            hmac_checker.update(field.raw_value)
        self._write_field_tlv(cipher, end_of_record)
        hmac_checker.update(end_of_record.raw_value)

        for record in self.records:
            for field in list(record.raw_fields.values()):
                self._write_field_tlv(cipher, field)
                hmac_checker.update(field.raw_value)
            self._write_field_tlv(cipher, end_of_record)
            hmac_checker.update(end_of_record.raw_value)

        self.db_ver.db_end_data()

        self.f_hmac = hmac_checker.digest()

        self.db_ver.db_write_data(self.f_hmac)
        self.db_ver.db_close()

        try:
            tmpvault = Vault(password, filename=tmpfilename, format=self.db_ver.db_format)
        except RuntimeError:
            os.remove(tmpfilename)
            raise self.VaultFormatError("File integrity check failed")

        # after writing the temporary file, replace the original file with it
        try:
            os.remove(filename)
        except OSError:
            pass
        os.rename(tmpfilename, filename)
コード例 #56
0
ファイル: models.py プロジェクト: victims/victims-web
def generate_apikey(username):
    apikey = HMAC(uuid4().hex, username).hexdigest()
    return apikey.upper()
コード例 #57
0
ファイル: migrate.py プロジェクト: gsnbng/LinOTP
 def hmac_sha256(secret, msg):
     hmac = HMAC(secret, msg=msg, digestmod=hashlib.sha256)
     val = hmac.digest()
     return val
コード例 #58
0
ファイル: vault.py プロジェクト: haad/loxodo
    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) != str

        ver3 = VaultVer3()
        ver4 = VaultVer4()

        # Read begining database tag and set db_ver db file access class
        tag = file(filename, 'rb').read(4)

        # Auto detect database type for existing vaults
        if (ver3.db_test_bg_tag(tag)):
          self.db_ver = ver3
        elif (ver4.db_test_bg_tag(tag)):
          self.db_ver = ver4
        else:
          raise self.VaultVersionError("Not a PasswordSafe V3 and V4 compatible file")

        if self.db_format != self.db_ver.db_format:
          if self.db_format == "auto":
            self.db_format = self.db_ver.db_format
          else:
            print("Database version missmatch I was asked to open database with version %s and it's a %s version" % (self.db_format, self.db_ver.db_format))
            sys.exit(1)

        # Open password database
        self.db_ver.db_open(filename)

        # Read database header to Vault class fill all required fields
        self.db_ver.db_read_header(password, self)

        # Get Stretched master password from db
        stretched_password = self.db_ver.db_get_stretched_passwd(self, password)  # P': the stretched key
        my_sha_ps = hashlib.sha256(stretched_password).digest()
        if (self.f_sha_ps != my_sha_ps):
            raise self.BadPasswordError("Wrong password")

        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)

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

        # read header
        while (True):
            field = self._read_field_tlv(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(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 = self.db_ver.db_read_data(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()

        self.db_ver.db_close()
コード例 #59
0
ファイル: CryptoHandler.py プロジェクト: Anarchid/uberserver
	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 ""