def verify_signature(self, signature, data): # for some reason, highest byte in padding is 0 that disappears in # the encryption roundtrip, so we need to add zeroes to be able to # compare. decrypted = self.decrypt(signature) if len(decrypted) < self.mod_size: decrypted = ("\x00" * (self.mod_size - len(decrypted))) + decrypted padded_digest = (_make_padding(self.mod_size) + hashlib.sha1(data).digest()) return constant_time_compare(padded_digest, decrypted)
def deserialize_authenticated(cls, serialized, hmac_secret): """ Deserialises instances of this class, validating the HMAC appended at the end using the provided hmac_secret """ instance, unpacker = cls._do_deserialize(serialized) # the extra 2 bytes taken off is the serialization overhead of byte # strings shorter than 256 bytes. calculated_mac = hmac.new(hmac_secret, serialized[:-HMAC_SIZE - 2], HMAC_HASH_ALGORITHM).digest() stored_mac = unpacker.unpack() if not constant_time_compare(calculated_mac, stored_mac): # TODO better exception, perhaps? raise exceptions.BadResponse("Invalid authentication code") return instance
def deserialize_authenticated(cls, serialized, hmac_secret): """ Deserialises instances of this class, validating the HMAC appended at the end using the provided hmac_secret """ instance, unpacker = cls._do_deserialize(serialized) # the extra 2 bytes taken off is the serialization overhead of byte # strings shorter than 256 bytes. calculated_mac = hmac.new(hmac_secret, serialized[:-HMAC_SIZE-2], HMAC_HASH_ALGORITHM).digest() stored_mac = unpacker.unpack() if not constant_time_compare(calculated_mac, stored_mac): # TODO better exception, perhaps? raise exceptions.BadResponse("Invalid authentication code") return instance
def verify(self, digest_f): return constant_time_compare(self.digest, digest_f(self.payload))