Migration From V4
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Una mejora significativa de la versión 5 de Navegación Segura de Google en comparación con la versión 4 (específicamente, la API de Update de la versión 4) es la actualización y la cobertura de los datos. Dado que la protección depende en gran medida de la base de datos local que mantiene el cliente, la demora y el tamaño de la actualización de la base de datos local son los principales factores que contribuyen a la falta de protección. En la versión 4, el cliente típico tarda entre 20 y 50 minutos en obtener la versión más actualizada de las listas de amenazas. Lamentablemente, los ataques de phishing se propagan rápidamente: en 2021, el 60% de los sitios que realizan ataques permanecieron activos durante menos de 10 minutos. Nuestro análisis muestra que entre el 25% y el 30% de la protección contra phishing faltante se debe a la obsolescencia de los datos. Además, algunos dispositivos no están equipados para administrar la totalidad de las listas de amenazas de la Navegación segura de Google, que siguen creciendo con el tiempo.
Si actualmente usas la API de Update v4, existe una ruta de migración sin problemas de la versión 4 a la 5 sin tener que restablecer ni borrar la base de datos local. En esta sección, se explica cómo hacerlo.
Actualizaciones de la conversión de listas
A diferencia de la versión 4, en la que las listas se identifican por la tupla de tipo de amenaza, tipo de plataforma y tipo de entrada de amenaza, en la versión 5, las listas se identifican simplemente por su nombre. Esto proporciona flexibilidad cuando varias listas de la versión 5 podrían compartir el mismo tipo de amenaza. En la versión 5, se quitaron los tipos de plataformas y los tipos de entradas de amenazas.
En la versión 4, se usaría el método threatListUpdates.fetch para descargar listas. En la versión 5, se cambiaría al método hashLists.batchGet.
Se deben realizar los siguientes cambios en la solicitud:
- Quita por completo el objeto
ClientInfo
de la versión 4. En lugar de proporcionar la identificación de un cliente con un campo dedicado, simplemente usa el conocido encabezado User-Agent. Si bien no hay un formato prescrito para proporcionar la identificación del cliente en este encabezado, sugerimos que simplemente incluyas el ID de cliente y la versión del cliente originales separados por un espacio o una barra.
- Para cada objeto
ListUpdateRequest
de la versión 4, haz lo siguiente:
- Busca el nombre de la lista correspondiente de la versión 5 en las listas disponibles y proporciona ese nombre en la solicitud de la versión 5.
- Quita los campos innecesarios, como
threat_entry_type
o platform_type
.
- El campo
state
de la versión 4 es directamente compatible con el campo versions
de la versión 5. La misma cadena de bytes que se enviaría al servidor con el campo state
en la versión 4 se puede enviar en la versión 5 con el campo versions
.
- Para las restricciones de la versión 4, la versión 5 usa una versión simplificada llamada
SizeConstraints
. Se deben descartar los campos adicionales, como region
.
Se deben realizar los siguientes cambios en la respuesta:
- El enum
ResponseType
de la versión 4 se reemplaza simplemente por un campo booleano llamado partial_update
.
- Ahora, el campo
minimum_wait_duration
puede ser cero o se puede omitir. Si es así, se le solicita al cliente que realice otra solicitud de inmediato. Esto solo sucede cuando el cliente especifica en SizeConstraints
una restricción menor en el tamaño máximo de actualización que el tamaño máximo de la base de datos.
- Se deberá ajustar el algoritmo de decodificación de Rice para números enteros de 32 bits. La diferencia es que los datos codificados se codifican con un orden de bytes diferente. En las versiones 4 y 5, los prefijos hash de 32 bits se ordenan de forma lexicográfica. Sin embargo, en la versión 4, esos prefijos se tratan como little endian cuando se ordenan, mientras que en la versión 5 se tratan como big endian cuando se ordenan. Esto significa que el cliente no necesita realizar ninguna ordenación, ya que la ordenación lexicográfica es idéntica a la ordenación numérica con big endian. Puedes encontrar un ejemplo de este tipo de ordenamiento en la implementación de v4 de Chromium aquí. Se puede quitar ese tipo de ordenamiento.
- El algoritmo de decodificación de Rice también deberá implementarse para otras longitudes de hash.
Cómo convertir búsquedas de hash
En la versión 4, se usaría el método fullHashes.find para obtener hashes completos. El método equivalente en la versión 5 es hashes.search.
Se deben realizar los siguientes cambios en la solicitud:
- Estructura el código para que solo envíe prefijos de hash que tengan exactamente 4 bytes de longitud.
- Quita por completo los objetos
ClientInfo
de la versión 4. En lugar de proporcionar la identificación de un cliente con un campo dedicado, simplemente usa el conocido encabezado User-Agent. Si bien no hay un formato prescrito para proporcionar la identificación del cliente en este encabezado, sugerimos que simplemente incluyas el ID de cliente y la versión del cliente originales separados por un espacio o una barra.
- Quita el campo
client_states
. Ya no es necesaria.
- Ya no es necesario incluir
threat_types
ni campos similares.
Se deben realizar los siguientes cambios en la respuesta:
- Se quitó el campo
minimum_wait_duration
. El cliente siempre puede emitir una nueva solicitud según sea necesario.
- El objeto
ThreatMatch
de la versión 4 se simplificó en el objeto FullHash
.
- El almacenamiento en caché se simplificó en una sola duración de caché. Consulta los procedimientos anteriores para interactuar con la caché.
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-08-10 (UTC)
[null,null,["Última actualización: 2025-08-10 (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."]]