Migration From V4
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Одним из существенных улучшений Google Safe Browsing v5 по сравнению с v4 (в частности, API обновления v4 ) является актуальность данных и охват. Поскольку защита в значительной степени зависит от поддерживаемой клиентом локальной базы данных, задержка и размер обновления локальной базы данных являются основными причинами отсутствия защиты. В v4 типичному клиенту требуется от 20 до 50 минут, чтобы получить самую актуальную версию списков угроз. К сожалению, фишинговые атаки распространяются быстро: по состоянию на 2021 год 60% сайтов, осуществляющих атаки, живут менее 10 минут. Наш анализ показывает, что около 25-30% случаев отсутствия защиты от фишинга связано с такой устареванием данных. Кроме того, некоторые устройства не оснащены возможностью управления всеми списками угроз Google Safe Browsing, которые продолжают расти с течением времени.
Если вы используете API обновления версии 4 , существует возможность плавной миграции с версии 4 на версию 5 без необходимости сброса или удаления локальной базы данных. В этом разделе описано, как это сделать.
Обновление списка конвертации
В отличие от версии 4, где списки идентифицируются кортежем типа угрозы, типа платформы и типа записи угрозы, в версии 5 списки идентифицируются просто по имени. Это обеспечивает гибкость, когда несколько списков версии 5 могут содержать один и тот же тип угрозы. В версии 5 типы платформ и типы записей угроз удалены.
В версии 4 для загрузки списков использовался метод threatListUpdates.fetch . В версии 5 — метод hashLists.batchGet .
В запрос необходимо внести следующие изменения:
- Полностью удалите объект
ClientInfo
версии 4. Вместо указания идентификатора клиента в отдельном поле просто используйте известный заголовок User-Agent . Хотя предписанного формата для указания идентификатора клиента в этом заголовке нет, мы рекомендуем просто указать исходный идентификатор клиента и его версию, разделив их пробелом или косой чертой. - Для каждого объекта
ListUpdateRequest
v4 :- Найдите соответствующее имя списка v5 среди доступных списков и укажите это имя в запросе v5.
- Удалите ненужные поля, такие как
threat_entry_type
или platform_type
. - Поле
state
в версии 4 напрямую совместимо с полем «Версии» versions
5. Та же строка байтов, которая была бы отправлена на сервер с помощью поля state
в версии 4, может быть отправлена в версии 5 с помощью поля versions
. - Для ограничений версии 4 в версии 5 используется упрощённая версия
SizeConstraints
. Дополнительные поля, такие как region
, следует исключить.
В ответ необходимо внести следующие изменения:
- Перечисление v4
ResponseType
просто заменяется логическим полем с именем partial_update
. - Поле
minimum_wait_duration
теперь может быть равно нулю или опущено. Если это так, клиенту предлагается немедленно выполнить другой запрос. Это происходит только в том случае, если клиент указывает в SizeConstraints
ограничение на максимальный размер обновления меньше максимального размера базы данных. - Алгоритм декодирования Райса для 32-битных целых чисел потребуется скорректировать. Разница заключается в том, что закодированные данные кодируются с разным порядком байтов. В версиях 4 и 5 32-битные хеш-префиксы сортируются лексикографически. Но в версии 4 эти префиксы обрабатываются как little endian при сортировке, тогда как в версии 5 они обрабатываются как big endian при сортировке. Это означает, что клиенту не нужно выполнять сортировку, поскольку лексикографическая сортировка идентична числовой сортировке с big endian. Пример такого рода в реализации Chromium версии 4 можно найти здесь . Такую сортировку можно удалить.
- Алгоритм декодирования Райса необходимо будет реализовать и для других длин хеша.
Конвертация хэш-поиска
В версии 4 для получения полных хешей использовался метод fullHashes.find . В версии 5 эквивалентным методом является hashes.search .
В запрос необходимо внести следующие изменения:
- Структурируйте код так, чтобы он отправлял только хеш-префиксы длиной ровно 4 байта.
- Полностью удалите объекты
ClientInfo
версии 4. Вместо указания идентификатора клиента в отдельном поле просто используйте известный заголовок User-Agent . Хотя предписанного формата для указания идентификатора клиента в этом заголовке нет, мы рекомендуем просто указать исходный идентификатор клиента и его версию, разделив их пробелом или косой чертой. - Удалите поле
client_states
. Оно больше не нужно. - Больше нет необходимости включать
threat_types
и аналогичные поля.
В ответ необходимо внести следующие изменения:
- Поле
minimum_wait_duration
удалено. Клиент всегда может отправить новый запрос по мере необходимости. - Объект
ThreatMatch
v4 был упрощен до объекта FullHash
. - Кэширование упрощено до единой продолжительности. Инструкции по взаимодействию с кэшем см. выше.
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons "С указанием авторства 4.0", а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-08-08 UTC.
[null,null,["Последнее обновление: 2025-08-08 UTC."],[],[],null,["# Migration From V4\n\nOne significant improvement of Google Safe Browsing v5 over v4 (specifically, [the v4 Update API](/safe-browsing/v4/update-api)) is data freshness and coverage. Since the protection highly depends on the client-maintained local database, the delay and size of the local database update is the main contributor of the missed protection. In v4, the typical client takes 20 to 50 minutes to obtain the most up-to-date version of threat lists. Unfortunately, phishing attacks spread fast: as of 2021, 60% of sites that deliver attacks live less than 10 minutes. Our analysis shows that around 25-30% of missing phishing protection is due to such data staleness. Further, some devices are not equipped to manage the entirety of the Google Safe Browsing threat lists, which continues to grow larger over time.\n\nIf you are currently using the [v4 Update API](/safe-browsing/v4/update-api), there is a seamless migration path from v4 to v5 without having to reset or erase the local database. This section documents how to do that.\n\n### Converting List Updates\n\nUnlike V4, where lists are identified by the tuple of threat type, platform type, threat entry type, in v5 lists are simply identified by name. This provides flexibility when multiple v5 lists could share the same threat type. Platform types and threat entry types are removed in v5.\n\nIn v4, one would use the [threatListUpdates.fetch method](/safe-browsing/reference/rest/v4/threatListUpdates/fetch) to download lists. In v5, one would switch to the [hashLists.batchGet method](/safe-browsing/reference/rest/v5/hashLists/batchGet).\n\nThe following changes should be made to the request:\n\n1. Remove the [v4 `ClientInfo` object](/safe-browsing/reference/rest/v4/ClientInfo) altogether. Instead of supplying a client's identification using a dedicated field, simply use the well-known [User-Agent header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent). While there is no prescribed format for supplying the client identification in this header, we suggest simply including the original client ID and client version separated by a space character or a slash character.\n2. For each [v4 `ListUpdateRequest` object](/safe-browsing/reference/rest/v4/threatListUpdates/fetch#listupdaterequest):\n - Look up the corresponding v5 list name from the [available lists](/safe-browsing/reference/Local.Database#available-lists) and supply that name in the v5 request.\n - Remove unneeded fields such as `threat_entry_type` or `platform_type`.\n - The `state` field in v4 is directly compatible with the v5 `versions` field. The same byte string that would be sent to the server using the `state` field in v4 can simply be sent in v5 using the `versions` field.\n - For the v4 constraints, v5 uses a simplified version called [`SizeConstraints`](/safe-browsing/reference/rest/v5/SizeConstraints). Additional fields such as `region` should be dropped.\n\nThe following changes should be made to the response:\n\n1. The v4 [enum `ResponseType`](/safe-browsing/reference/rest/v4/threatListUpdates/fetch#ResponseType) is simply replaced by a boolean field named `partial_update`.\n2. The `minimum_wait_duration` field can now be zero or omitted. If it is, the client is requested to immediately make another request. This only happens when the client specifies in `SizeConstraints` a smaller constraint on max update size than the max database size.\n3. The Rice decoding algorithm for 32-bit integers will need to be adjusted. The difference is that the encoded data are encoded with a different endianness. In both v4 and v5, 32-bit hash prefixes are sorted lexicographically. But in v4, those prefixes are treated as little endian when sorted, whereas in v5 those prefixes are treated as big endian when sorted. This means that the client does not need to do any sorting, since lexicographic sorting is identical to numeric sorting with big endian. An example of this sort in the Chromium implementation of v4 can be found [here](https://source.chromium.org/chromium/chromium/src/+/main:components/safe_browsing/core/browser/db/v4_rice.cc;l=144-146;drc=8ba1bad80dc22235693a0dd41fe55c0fd2dbdabd). Such sorting can be removed.\n4. The Rice decoding algorithm will need to be implemented for other hash lengths as well.\n\n### Converting Hash Searches\n\nIn v4, one would use the [fullHashes.find method](/safe-browsing/reference/rest/v4/fullHashes/find) to get full hashes. The equivalent method in v5 is [the hashes.search method](/safe-browsing/reference/rest/v5/hashes/search).\n\nThe following changes should be made to the request:\n\n1. Structure the code to only send hash prefixes that are exactly 4 bytes in length.\n2. Remove the [v4 `ClientInfo` objects](/safe-browsing/reference/rest/v4/ClientInfo) altogether. Instead of supplying a client's identification using a dedicated field, simply use the well-known [User-Agent header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent). While there is no prescribed format for supplying the client identification in this header, we suggest simply including the original client ID and client version separated by a space character or a slash character.\n3. Remove the `client_states` field. It is no longer necessary.\n4. It is no longer needed to include `threat_types` and similar fields.\n\nThe following changes should be made to the response:\n\n1. The `minimum_wait_duration` field has been removed. The client can always issue a new request on an as-needed basis.\n2. The [v4 `ThreatMatch` object](/safe-browsing/reference/rest/v4/ThreatMatch) has been simplified into the [`FullHash`](/safe-browsing/reference/rest/v5/hashes/search#FullHash) object.\n3. Caching has been simplified into a single cache duration. See the above procedures for interacting with the cache."]]