コード例 #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
ファイル: protocol.py プロジェクト: marciopocebon/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)
コード例 #3
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
コード例 #4
0
def calculate_digest(secret, message, salt):
    """Calculate a SHA-256 HMAC digest for the given data."""
    assert isinstance(secret, bytes), "%r is not a byte string." % (secret, )
    assert isinstance(message, bytes), "%r is not byte string." % (message, )
    assert isinstance(salt, bytes), "%r is not a byte string." % (salt, )
    hmacr = HMAC(secret, digestmod=sha256)
    hmacr.update(message)
    hmacr.update(salt)
    return hmacr.digest()
コード例 #5
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())
コード例 #6
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)
コード例 #7
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()
コード例 #8
0
ファイル: sign.py プロジェクト: blink1073/nbformat
    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()
コード例 #9
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'])
コード例 #10
0
ファイル: hashTest.py プロジェクト: Braganza/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'])
コード例 #11
0
ファイル: protocol.py プロジェクト: marciopocebon/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')
コード例 #12
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')
コード例 #13
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)
コード例 #14
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)
コード例 #15
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()
コード例 #16
0
ファイル: prf.py プロジェクト: marciopocebon/ike
def prf(key, data, hash_algorithm='sha256'):
    hasher = getattr(hashlib, hash_algorithm)
    m = HMAC(key, digestmod=hasher)
    m.update(data)
    return m.digest()
コード例 #17
0
ファイル: scram.py プロジェクト: 571451370/devstack_mitaka
    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)
コード例 #18
0
ファイル: vault.py プロジェクト: PaulPrice/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()
コード例 #19
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)
コード例 #20
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()
コード例 #21
0
ファイル: vault.py プロジェクト: PaulPrice/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)