Migration From V4
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Uma melhoria significativa do Google Safe Browsing v5 em relação à v4 (especificamente, a API Update v4) é a atualização e a cobertura dos dados. Como a proteção depende muito do banco de dados local mantido pelo cliente, o atraso e o tamanho da atualização do banco de dados local são os principais fatores que contribuem para a proteção perdida. Na v4, o cliente típico leva de 20 a 50 minutos para receber a versão mais atualizada das listas de ameaças. Infelizmente, os ataques de phishing se espalham rapidamente: em 2021, 60% dos sites que realizam ataques ficam ativos por menos de 10 minutos. Nossa análise mostra que cerca de 25 a 30% da proteção contra phishing ausente se deve a essa defasagem de dados. Além disso, alguns dispositivos não estão equipados para gerenciar todas as listas de ameaças da Navegação Segura do Google, que continuam crescendo com o tempo.
Se você estiver usando a API Update v4, há um caminho de migração simples da v4 para a v5 sem precisar redefinir ou apagar o banco de dados local. Esta seção explica como fazer isso.
Atualizações de lista de conversão
Ao contrário da V4, em que as listas são identificadas pela tupla de tipo de ameaça, tipo de plataforma e tipo de entrada de ameaça, na V5, elas são identificadas apenas pelo nome. Isso oferece flexibilidade quando várias listas da v5 podem compartilhar o mesmo tipo de ameaça. Os tipos de plataforma e de entrada de ameaça foram removidos na v5.
Na v4, é usado o método threatListUpdates.fetch para fazer o download de listas. Na v5, é possível mudar para o método hashLists.batchGet.
As seguintes mudanças precisam ser feitas na solicitação:
- Remova o objeto
ClientInfo
v4 por completo. Em vez de fornecer a identificação de um cliente usando um campo dedicado, use o cabeçalho User-Agent conhecido. Embora não haja um formato prescrito para fornecer a identificação do cliente nesse cabeçalho, sugerimos incluir o ID do cliente e a versão do cliente originais separados por um espaço ou uma barra.
- Para cada objeto
ListUpdateRequest
v4:
- Procure o nome da lista v5 correspondente em Listas disponíveis e forneça esse nome na solicitação v5.
- Remova campos desnecessários, como
threat_entry_type
ou platform_type
.
- O campo
state
na v4 é diretamente compatível com o campo versions
na v5. A mesma string de bytes que seria enviada ao servidor usando o campo state
na v4 pode ser enviada na v5 usando o campo versions
.
- Para as restrições da v4, a v5 usa uma versão simplificada chamada
SizeConstraints
. Campos adicionais, como region
, precisam ser descartados.
Faça as seguintes mudanças na resposta:
- A enum
ResponseType
da v4 foi substituída por um campo booleano chamado partial_update
.
- O campo
minimum_wait_duration
agora pode ser zero ou omitido. Se for, o cliente vai precisar fazer outra solicitação imediatamente. Isso só acontece quando o cliente especifica em SizeConstraints
uma restrição menor no tamanho máximo da atualização do que o tamanho máximo do banco de dados.
- O algoritmo de decodificação de Rice para números inteiros de 32 bits precisará ser ajustado. A diferença é que os dados codificados têm uma endianness diferente. Nas versões 4 e 5, os prefixos de hash de 32 bits são classificados lexicograficamente. No entanto, na v4, esses prefixos são tratados como little endian quando classificados, enquanto na v5 eles são tratados como big endian. Isso significa que o cliente não precisa fazer nenhuma classificação, já que a classificação lexicográfica é idêntica à numérica com big endian. Um exemplo dessa classificação na implementação do v4 no Chromium pode ser encontrado aqui. Essa classificação pode ser removida.
- O algoritmo de decodificação de Rice também precisa ser implementado para outros tamanhos de hash.
Pesquisas de hash de conversão
Na v4, é possível usar o método fullHashes.find para receber hashes completos. O método equivalente na v5 é hashes.search.
As seguintes mudanças precisam ser feitas na solicitação:
- Estruture o código para enviar apenas prefixos de hash com exatamente 4 bytes de comprimento.
- Remova todos os objetos
ClientInfo
da v4. Em vez de fornecer a identificação de um cliente usando um campo dedicado, use o cabeçalho User-Agent conhecido. Embora não haja um formato prescrito para fornecer a identificação do cliente nesse cabeçalho, sugerimos incluir o ID do cliente e a versão do cliente originais separados por um espaço ou uma barra.
- Remova o campo
client_states
. Ela não é mais necessária.
- Não é mais necessário incluir
threat_types
e campos semelhantes.
Faça as seguintes mudanças na resposta:
- O campo
minimum_wait_duration
foi removido. O cliente pode sempre emitir uma nova solicitação conforme necessário.
- O objeto
ThreatMatch
v4 foi simplificado no objeto FullHash
.
- O armazenamento em cache foi simplificado em uma única duração. Consulte os procedimentos acima para interagir com o cache.
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-08-10 UTC.
[null,null,["Última atualização 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."]]