Потоковое шифрование с проверкой подлинности и связанными данными (Streaming AEAD)
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Примитив Streaming AEAD обеспечивает шифрование с проверкой подлинности для потоковых данных. Это полезно, когда данные, подлежащие шифрованию, слишком велики, чтобы их можно было обработать за один шаг. Типичные случаи использования включают шифрование больших файлов или потоков данных в реальном времени.
Шифрование выполняется сегментами, которые привязаны к своему местоположению в зашифрованном тексте и не могут быть удалены или переупорядочены. Сегменты одного зашифрованного текста не могут быть вставлены в другой зашифрованный текст. Чтобы изменить существующий зашифрованный текст, весь поток данных должен быть повторно зашифрован. 1
Расшифровка выполняется быстро, поскольку одновременно расшифровывается и аутентифицируется только часть зашифрованного текста. Частичные открытые тексты можно получить без обработки всего зашифрованного текста.
Секретность : об открытом тексте ничего не известно, кроме его длины.
Подлинность : невозможно изменить зашифрованный открытый текст, лежащий в основе зашифрованного текста, не будучи обнаруженным.
Симметричный : шифрование открытого текста и расшифровка зашифрованного текста выполняются одним и тем же ключом.
Рандомизация : шифрование рандомизировано. Два сообщения с одинаковым открытым текстом дают разные зашифрованные тексты. Злоумышленники не могут знать, какой зашифрованный текст соответствует данному открытому тексту.
Связанные данные
Примитив Streaming AEAD можно использовать для привязки зашифрованного текста к конкретным связанным данным . Предположим, у вас есть база данных с полями user-id и encrypted-medical-history : в этом сценарии user-id может использоваться в качестве связанных данных при шифровании encrypted-medical-history . Это не позволяет злоумышленнику передать историю болезни от одного пользователя к другому.
Выберите тип ключа
Для большинства случаев мы рекомендуем AES128_GCM_HKDF_1MB . В целом:
AES128_GCM_HKDF_1MB (или AES256_GCM_HKDF_1MB) — более быстрый вариант. Он может зашифровать 264 файла размером до 264 байт каждый. Во время процесса шифрования и дешифрования потребляется ~1 МБ памяти.
AES128_GCM_HKDF_4KB потребляет около 4 КБ памяти и является хорошим выбором, если в вашей системе мало памяти.
AES128_CTR_HMAC_SHA256_1MB (или AES256_CTR_HMAC_SHA256_1MB) — более консервативный вариант.
Гарантии безопасности
Реализации потоковой передачи AEAD предлагают:
Безопасность CCA2.
Уровень аутентификации не менее 80 бит.
Возможность шифрования не менее 2 64 сообщений 3 общей длиной 2 51 байт 2 . Ни одна атака с использованием до 232 выбранных открытых текстов или выбранных зашифрованных текстов не имеет вероятности успеха, превышающей 2-32 .
Причиной этого ограничения является использование шифра AES-GCM. Шифрование другого сегмента открытого текста в том же месте было бы эквивалентно повторному использованию IV, что нарушает гарантии безопасности AES-GCM. Другая причина заключается в том, что это предотвращает атаки отката, когда злоумышленник может попытаться восстановить предыдущую версию файла без обнаружения. ↩
2 Поддерживается 32 сегмента, каждый из которых содержит segment_size - tag_size байтов открытого текста. Для сегментов размером 1 МБ общий размер открытого текста составляет 2 32 * (2 20 -16) ~= 2 51 байт. ↩
Потоковая передача AEAD становится небезопасной, когда повторяется комбинация производного ключа (128-бит) и префикса nonce (независимое случайное 7-байтовое значение). У нас есть 184-битная устойчивость к коллизиям, что примерно соответствует 2 64 сообщениям, если мы хотим, чтобы вероятность успеха была меньше 2 -32 . ↩
[null,null,["Последнее обновление: 2025-07-25 UTC."],[[["\u003cp\u003eStreaming AEAD encrypts large data streams or files securely in segments, ensuring authenticity and confidentiality.\u003c/p\u003e\n"],["\u003cp\u003eIt offers strong security guarantees, including CCA2 security, at least 80-bit authentication strength, and resistance to common attacks.\u003c/p\u003e\n"],["\u003cp\u003eAssociated data is authenticated but not encrypted, preventing unauthorized data manipulation but not revealing its content.\u003c/p\u003e\n"],["\u003cp\u003eTink recommends AES128_GCM_HKDF_1MB for most use cases due to its speed and large data capacity, with alternative options for memory-constrained environments.\u003c/p\u003e\n"],["\u003cp\u003eModifying existing ciphertext requires re-encryption of the entire stream, maintaining data integrity and preventing rollback attacks.\u003c/p\u003e\n"]]],["Streaming AEAD encrypts large data streams in segments, ensuring authenticity and secrecy, but only the plaintext is encrypted, associated data is not. Encryption segments are bound to their location and cannot be reordered or moved. Decryption allows partial ciphertext processing. The recommended key type is AES128_GCM_HKDF_1MB. Streaming AEAD offers CCA2 security, at least 80-bit authentication strength, and can encrypt at least 2^64 messages with a total of 2^51 bytes. Re-encrypting the whole stream is needed to modify the ciphertext.\n"],null,["# Streaming Authenticated Encryption with Associated Data (Streaming AEAD)\n\nThe Streaming AEAD primitive provides authenticated encryption for streaming\ndata. It is useful when the data to be encrypted is too large to be processed in\na single step. Typical use cases include encryption of large files or live data\nstreams.\n\nEncryption is done in segments, which are bound to their location within a\nciphertext and cannot be removed or reordered. Segments from one ciphertext\ncannot be inserted into another ciphertext. To modify an existing ciphertext,\nthe entire data stream must be re-encrypted.^[1](#fn1)^\n\nDecryption is fast because only a portion of the ciphertext is decrypted and\nauthenticated at a time. Partial plaintexts are obtainable without processing\nthe entire ciphertext.\n\nStreaming AEAD implementations fulfill the [AEAD\ndefinition](https://www.cs.ucdavis.edu/%7Erogaway/papers/ad.html) and are\n[nOAE-secure](https://eprint.iacr.org/2015/189.pdf). They have the following\nproperties:\n\n- **Secrecy**: Nothing about the plaintext is known, except its length.\n- **Authenticity**: It is impossible to change the encrypted plaintext underlying the ciphertext without being detected.\n- **Symmetric**: Encrypting the plaintext and decrypting the ciphertext is done with the same key.\n- **Randomization**: Encryption is randomized. Two messages with the same plaintext yield different ciphertexts. Attackers cannot know which ciphertext corresponds to a given plaintext.\n\n### Associated data\n\n| **Caution:** Associated data is authenticated but *NOT* encrypted.\n\nThe Streaming AEAD primitive can be used to [tie ciphertext to specific\nassociated data](/tink/bind-ciphertext). Suppose you have a database with the\nfields `user-id` and `encrypted-medical-history`: In this scenario, `user-id`\ncan be used as associated data when encrypting `encrypted-medical-history`. This\nprevents an attacker from moving medical history from one user to another.\n\n### Choose a key type\n\nWe recommend **AES128_GCM_HKDF_1MB** for most uses. Generally:\n\n- [AES-GCM-HKDF](/tink/streaming-aead/aes_gcm_hkdf_streaming)\n - AES128_GCM_HKDF_1MB (or AES256_GCM_HKDF_1MB) is the faster option. It can encrypt 2^64^ files with up to 2^64^ bytes each. \\~1 MB of memory is consumed during the encryption and decryption process.\n - AES128_GCM_HKDF_4KB consumes \\~4 KB of memory and is a good choice if your system doesn't have a lot of memory.\n- [AES-CTR HMAC](/tink/streaming-aead/aes_ctr_hmac_streaming)\n - AES128_CTR_HMAC_SHA256_1MB (or AES256_CTR_HMAC_SHA256_1MB) is a more conservative option.\n\n| **Note:** For 1 MB schemes, the plaintext may have any length within 0 to 2^51^ bytes.^[2](#fn2)^\n\n### Security guarantees\n\nStreaming AEAD implementations offer:\n\n- CCA2 security.\n- At least 80-bit authentication strength.\n- The ability to encrypt at least 2^64^ messages^[3](#fn3)^ with a total of 2^51^ bytes[^2^](#fn2) . No attack with up to 2^32^ chosen plaintexts or chosen ciphertexts has a probability of success larger than 2^-32^.\n\n| **Caution:** **Streaming AEAD offers no secrecy guarantees for associated data.**\n\n### Example use case\n\nSee [I want to encrypt large files or data\nstreams](/tink/encrypt-large-files-or-data-streams). \n\n*** ** * ** ***\n\n1. A reason for this restriction is the use of the AES-GCM cipher. Encrypting a different plaintext segment at the same location would be equivalent to reusing the IV, which violates the security guarantees of AES-GCM. Another reason is that this prevents roll-back attacks, where the attacker may try to restore a previous version of the file without detection. [↩](#fnref1)\n\n2. 2^32^ segments are supported, with each segment containing `segment_size - tag_size` bytes of plaintext. For 1 MB segments, the total plaintext size is 2^32^ \\* (2^20^-16) \\~= 2^51^ bytes. [↩](#fnref2)\n\n3. Streaming AEAD becomes insecure when a derived key (128-bit) and nonce prefix (independent random 7-byte value) combination is repeated. We have 184-bit collision resistance, which roughly translates to 2^64^ messages if we want success probability to be less than 2^-32^. [↩](#fnref3)"]]