Введение
Блок-шифр Blowfish — это симметричный блочный шифр, разработанный в 1993 году Брюсом Шнайером и включенный во многие наборы шифров и продукты шифрования. Blowfish обеспечивает высокую скорость шифрования в программном обеспечении, и на сегодняшний день не обнаружено эффективных методов его криптоанализа. Однако в настоящее время больше внимания уделяется стандарту Advanced Encryption Standard (AES), и Шнайер рекомендует Twofish для современных приложений. Это 16-раундовый шифр Фейстеля, использующий большие S-блоки, зависящие от ключа. По структуре он напоминает CAST 128, который использует фиксированные S-блоки. На прилагаемой диаграмме показана процедура шифрования Blowfish. Каждая строка представляет 32 бита. Существует пять подмассивов ключей: один массив P из 18 элементов (обозначен как K на диаграмме, чтобы избежать путаницы с открытым текстом) и четыре S-блока из 256 элементов (S0, S1, S2 и S3). Каждый раунд r состоит из 4 действий:
Действие 1: XOR левой половины (L) данных с r-м элементом массива P.
Действие 2: Использование результата XOR в качестве входных данных для F-функции Blowfish.
Действие 3: XOR выхода F-функции с правой половиной (R) данных.
Действие 4: Обмен местами L и R.
Blowfish is a symmetric key block cipher, designed in 1993 by Bruce Schneier and included in many cipher suites and encryption products. Blowfish provides a good encryption rate in software, and no effective cryptanalysis of it has been found to date. However, the Advanced Encryption Standard (AES) now receives more attention, and Schneier recommends Twofish for modern applications. It is a 16 round Feistel cipher and uses large key dependent S boxes. In structure it resembles CAST 128, which uses fixed S boxes. The adjacent diagram shows Blowfish's encryption routine. Each line represents 32 bits. There are five subkey arrays: one 18 entry P array (denoted as K in the diagram, to avoid confusion with the Plaintext) and four 256 entry S boxes (S0, S1, S2 and S3). Every round r consists of 4 actions:
Action 1XOR the left half (L) of the data with the r th P array entryAction 2Use the XORed data as input for Blowfish's F functionAction 3XOR the F function's output with the right half (R) of the dataAction 4Swap L and R
The F function splits the 32 bit input into four 8 bit quarters and uses the quarters as input to the S boxes. The S boxes accept 8 bit input and produce 32 bit output. The outputs are added modulo 232 and XORed to produce the final 32 bit output (see image in the upper right corner). After the 16th round, undo the last swap, and XOR L with K18 and R with K17 (output whitening). Decryption is exactly the same as encryption, except that P1, P2, , P18 are used in the reverse order. This is not so obvious because xor is commutative and associative. A common misconception is to use inverse order of encryption as decryption algorithm (i. e. first XORing P17 and P18 to the ciphertext block, then using the P entries in reverse order). Blowfish's key schedule starts by initializing the P array and S boxes with values derived from the hexadecimal digits of pi, which contain no obvious pattern (see nothing up my sleeve number). The secret key is then, byte by byte, cycling the key if necessary, XORed with all the P entries in order. A 64 bit all zero block is then encrypted with the algorithm as it stands. The resultant ciphertext replaces P1 and P2. The same ciphertext is then encrypted again with the new subkeys, and the new ciphertext replaces P3 and P4. This continues, replacing the entire P array and all the S box entries. In all, the Blowfish encryption algorithm will run 521 times to generate all the subkeys about 4 KB of data is processed. Because the P array is 576 bits long, and the key bytes are XORed through all these 576 bits during the initialization, many implementations support key sizes up to 576 bits. The reason for that is a discrepancy between the original Blowfish description, which uses 448 bit keys, and its reference implementation, which uses 576 bit keys. The test vectors for verifying third party implementations were also produced with 576 bit keys. When asked which Blowfish version is the correct one, Bruce Schneier answered: "The test vectors should be used to determine the one true Blowfish". Another opinion is that the 448 bits limit is present to ensure that every bit of every subkey depends on every bit of the key,
F-функция разделяет 32-битный вход на четыре 8-битных квартала и использует эти кварталы в качестве входных данных для S-блоков. S-блоки принимают 8-битный вход и выдают 32-битный выход. Результаты складываются по модулю 232 и XORятся для получения окончательного 32-битного выхода (см. изображение в правом верхнем углу). После 16-го раунда выполняется отмена последнего обмена, и L XORится с K18, а R — с K17 (отбеливание выхода). Расшифровка выполняется точно так же, как шифрование, за исключением того, что P1, P2, …, P18 используются в обратном порядке. Это не всегда очевидно, поскольку операция XOR коммутативна и ассоциативна. Распространенное заблуждение заключается в использовании обратного порядка шифрования в качестве алгоритма расшифровки (т.е. сначала XOR с P17 и P18 шифротекстового блока, а затем использование элементов P в обратном порядке). Ключевое расписание Blowfish начинается с инициализации массива P и S-блоков значениями, полученными из шестнадцатеричных цифр числа пи, которые не содержат очевидных закономерностей (см. "Nothing up my sleeve number"). Затем секретный ключ, байт за байтом (при необходимости циклически повторяя ключ), XORится со всеми элементами массива P по порядку. Затем 64-битный блок, заполненный нулями, шифруется с использованием текущего алгоритма. Полученный шифротекст заменяет P1 и P2. Затем тот же шифротекст снова шифруется с новыми подключами, и новый шифротекст заменяет P3 и P4. Этот процесс продолжается, заменяя весь массив P и все элементы S-блоков. В общей сложности алгоритм шифрования Blowfish выполняется 521 раз для генерации всех подключей, обрабатывается около 4 КБ данных. Поскольку массив P имеет длину 576 бит, а ключевые байты XORятся со всеми этими 576 битами во время инициализации, многие реализации поддерживают размеры ключей до 576 бит. Это связано с расхождением между оригинальным описанием Blowfish, использующим 448-битные ключи, и его эталонной реализацией, использующей 576-битные ключи. Тестовые векторы для проверки сторонних реализаций также были созданы с использованием 576-битных ключей. На вопрос о том, какая версия Blowfish является правильной, Брюс Шнайер ответил: "Для определения единственного истинного Blowfish следует использовать тестовые векторы". Другое мнение заключается в том, что ограничение в 448 бит необходимо для обеспечения зависимости каждого бита каждого подключаемого ключа от каждого бита исходного ключа.
Blowfish is a symmetric key block cipher, designed in 1993 by Bruce Schneier and included in many cipher suites and encryption products. Blowfish provides a good encryption rate in software, and no effective cryptanalysis of it has been found to date. However, the Advanced Encryption Standard (AES) now receives more attention, and Schneier recommends Twofish for modern applications. It is a 16 round Feistel cipher and uses large key dependent S boxes. In structure it resembles CAST 128, which uses fixed S boxes. The adjacent diagram shows Blowfish's encryption routine. Each line represents 32 bits. There are five subkey arrays: one 18 entry P array (denoted as K in the diagram, to avoid confusion with the Plaintext) and four 256 entry S boxes (S0, S1, S2 and S3). Every round r consists of 4 actions:
Action 1XOR the left half (L) of the data with the r th P array entryAction 2Use the XORed data as input for Blowfish's F functionAction 3XOR the F function's output with the right half (R) of the dataAction 4Swap L and R
The F function splits the 32 bit input into four 8 bit quarters and uses the quarters as input to the S boxes. The S boxes accept 8 bit input and produce 32 bit output. The outputs are added modulo 232 and XORed to produce the final 32 bit output (see image in the upper right corner). After the 16th round, undo the last swap, and XOR L with K18 and R with K17 (output whitening). Decryption is exactly the same as encryption, except that P1, P2, , P18 are used in the reverse order. This is not so obvious because xor is commutative and associative. A common misconception is to use inverse order of encryption as decryption algorithm (i. e. first XORing P17 and P18 to the ciphertext block, then using the P entries in reverse order). Blowfish's key schedule starts by initializing the P array and S boxes with values derived from the hexadecimal digits of pi, which contain no obvious pattern (see nothing up my sleeve number). The secret key is then, byte by byte, cycling the key if necessary, XORed with all the P entries in order. A 64 bit all zero block is then encrypted with the algorithm as it stands. The resultant ciphertext replaces P1 and P2. The same ciphertext is then encrypted again with the new subkeys, and the new ciphertext replaces P3 and P4. This continues, replacing the entire P array and all the S box entries. In all, the Blowfish encryption algorithm will run 521 times to generate all the subkeys about 4 KB of data is processed. Because the P array is 576 bits long, and the key bytes are XORed through all these 576 bits during the initialization, many implementations support key sizes up to 576 bits. The reason for that is a discrepancy between the original Blowfish description, which uses 448 bit keys, and its reference implementation, which uses 576 bit keys. The test vectors for verifying third party implementations were also produced with 576 bit keys. When asked which Blowfish version is the correct one, Bruce Schneier answered: "The test vectors should be used to determine the one true Blowfish". Another opinion is that the 448 bits limit is present to ensure that every bit of every subkey depends on every bit of the key,
Слабость и преемники
Использование Blowfish с 64-битным размером блока (в отличие, например, от 128-битного размера блока AES) делает его уязвимым к атакам «дней рождения», особенно в таких контекстах, как HTTPS. В 2016 году атака SWEET32 продемонстрировала, как использовать атаки «дней рождения» для восстановления открытого текста (то есть расшифровки зашифрованного текста) для шифров с 64-битным размером блока. Проект GnuPG рекомендует не использовать Blowfish для шифрования файлов размером более 4 ГБ из-за его небольшого размера блока. Известно, что упрощенные варианты Blowfish уязвимы для атак с использованием известного открытого текста на отражательно слабых ключах. Реализации Blowfish используют 16 раундов шифрования и не подвержены этой атаке. Брюс Шнайер рекомендовал перейти на его преемника Blowfish, Twofish.