COMPUTERSECURITY COMPUTERSECURITY
Recommendation for Block Рекомендация для блока
Cipher Modes of Operation: Cipher Режимы работы:
The CMAC Mode for Режим CMAC для
Authentication Аутентификация
Morris Dworkin Моррис Дворкин
NIST Special Publication 800-38B NIST Special 800-38B публикации
Computer Security Division Отдел компьютерной безопасности
Information Technology Laboratory Лаборатория информационных технологий
National Institute of Standards and Technology Национальный институт стандартов и технологий
Gaithersburg, MD 20899-8930 Gaithersburg, MD 20899-8930
May 2005 Май 2005
US Department of Commerce Министерство торговли США
Carlos M. Gutierrez, Secretary Карлос Гутьеррес, секретарь
Technology Administration Технология Администрация
Phillip J. Bond, Under Secretary of Commerce for Technology Филипп J. Bond, заместитель министра торговли по технологии
National Institute of Standards and Technology Национальный институт стандартов и технологий
Hratch G. Semerjian, Acting Director Грач Г. Семерджян, исполняющий обязанности директора
NIST Special Publication 800-38B NIST Special 800-38B публикации
Recommendation for Block Рекомендация для блока
Cipher Modes of Operation: Cipher Режимы работы:
The CMAC Mode for Режим CMAC для
Authentication Аутентификация
Morris Dworkin Моррис Дворкин
COMPUTERSECURITY COMPUTERSECURITY
Reports on Information Security Technology Отчеты о безопасности информационных технологий
The Information Technology Laboratory (ITL) at the National Institute of Standards and Technology Техническая лаборатория Информация (ITL) в Национальном институте стандартов и технологий
(NIST) promotes the US economy and public welfare by providing technical leadership for the Nation's (NIST) способствует американскую экономику и общественное благосостояние путем предоставления технической лидерство для страны
measurement and standards infrastructure. инфраструктура измерения и стандартов. ITL develops tests, test methods, reference data, proof of ITL разрабатывает тесты, методы испытаний, справочные данные, доказательство
concept implementations, and technical analyses to advance the development and productive use of Концепция реализации, и технический анализ для продвижения развития и продуктивного использования
information technology. информационные технологии. ITL's responsibilities include the development of technical, physical, Обязанности ITL включают разработку технической, физической,
administrative, and management standards and guidelines for the cost-effective security and privacy of административные и управленческие стандарты и руководящие принципы для рентабельной безопасности и конфиденциальности
sensitive unclassified information in Federal computer systems. чувствительны несекретные сведения в федеральных компьютерных систем. This Special Publication 800-series Это Special Publication 800-серия
reports on ITL's research, guidance, and outreach efforts in computer security, and its collaborative отчеты о научно-исследовательских, руководство, и информационно-пропагандистской деятельности ITL в области компьютерной безопасности, и его совместная
activities with industry, government, and academic organizations. деятельность с промышленностью, правительством и научными организациями.
Certain commercial entities, equipment, or materials may be identified in this document in order Некоторые коммерческие организации, оборудование или материалы могут быть идентифицированы в данном документе для того,
to describe an experimental procedure or concept adequately. описать экспериментальный порядок или понятие адекватно. Such identification is not intended Такая идентификация не предназначен
to imply recommendation or endorsement by the National Institute of Standards and Technology, подразумевает рекомендацию или одобрение со стороны Национального института стандартов и технологий,
nor is it intended to imply that the entities, materials, or equipment are necessarily the best а также не подразумевает, что лица, материалы или оборудование обязательно лучшим
available for the purpose. средства для этой цели.
National Institute of Standards and Technology Special Publication 800-38B Национальный институт стандартов и технологии Специальный 800-38B публикации
Natl. Natl. Inst. Ин-т. Stand. Стенд. Technol. Technol. Spec. Spec. Publ. Изд. 800-38B, 23 pages (May 2005) 800-38B, 23 страницы (май 2005)
CODEN: NSPUE2 CODEN: NSPUE2
iii III
Abstract Аннотация
This Recommendation specifies a message authentication code (MAC) algorithm based on a В настоящей Рекомендации определяется кода аутентификации сообщения (МАС) алгоритм, основанный на
symmetric key block cipher. симметричный ключ блочный шифр. This block cipher-based MAC algorithm, called CMAC, may be Это блочный шифр на основе алгоритма MAC, называется CMAC, может быть
used to provide assurance of the authenticity and, hence, the integrity of binary data. используется для обеспечения уверенности в подлинности и, следовательно, целостность двоичных данных.
KEY WORDS: authentication; КЛЮЧЕВЫЕ СЛОВА: аутентификации; block cipher; блочный шифр; cryptography; криптография; information security; информационная безопасность; integrity; целостности;
message authentication code; код аутентификации сообщения; mode of operation. режим работы.
iv IV
Table of Contents Содержание
1 1
PURPOSE...........................................................................................................................................................1
2 2
AUTHORITY.....................................................................................................................................................1
3 3
INTRODUCTION..............................................................................................................................................1
4 4
DEFINITIONS, ABBREVIATIONS, AND SYMBOLS.................................................................................2 ОПРЕДЕЛЕНИЯ, СОКРАЩЕНИЯ, И СИМВОЛЫ ............................................ ..................................... 2
4.1 4.1
D D
EFINITIONS AND ПРЕДЕЛЕНИЯ И
A
BBREVIATIONS BBREVIATIONS
.............................................................................................................2
4.2 4.2
S S
YMBOLS YMBOLS
....................................................................................................................................................4
4.2.1 4.2.1
Variables................................................................................................................................................4
4.2.2 4.2.2
Operations and Functions Операции и функции .....................................................................................................................4
5 5
PRELIMINARIES.............................................................................................................................................5
5.1 5.1
E E
XAMPLES OF XAMPLES OF
O O
PERATIONS AND PERATIONS И
F F
UNCTIONS УНКЦИИ
..............................................................................................5 .................................................. ............................................ 5
5.2 5.2
B B
LOCK ЗАМОК
C C
IPHER IPHER
............................................................................................................................................5
5.3 5.3
S S
UBKEYS UBKEYS
.....................................................................................................................................................6
5.4 5.4
MAC G MAC G
ENERATION AND ENERATION И
V V
ERIFICATION ERIFICATION
......................................................................................................6
5.5 5.5
I Я
NPUT AND NPUT И
O O
UTPUT UTPUT
D D
ATA ATA
...........................................................................................................................7
6 6
CMAC CMAC SPECIFICATION.................................................................................................................................7
6.1 6.1
S S
UBKEY UBKEY
G G
ENERATION ENERATION
.................................................................................................................................7
6.2 6.2
MAC G MAC G
ENERATION ENERATION
.....................................................................................................................................8
6.3 6.3
MAC V MAC V
ERIFICATION ERIFICATION
.................................................................................................................................10
APPENDIX A: LENGTH OF THE ПРИЛОЖЕНИЕ: длина MAC..............................................................................................................11
A.1 A.1
A
SSURANCE SSURANCE
A
GAINST Активизируем
G G
UESSING UESSING
A
TTACKS TTACKS
..............................................................................................11 .................................................. ............................................ 11
A.2 А.2
S S
ELECTION OF THE Выборы
MAC L MAC L
ENGTH ENGTH
.............................................................................................................11
APPENDIX B: MESSAGE SPAN OF THE KEY .................................................................................................13 ПРИЛОЖЕНИЕ B: СООБЩЕНИЕ SPAN из ключевых .......................................... .................................................. ..... 13
APPENDIX C: PROTECTION AGAINST REPLAY OF MESSAGES.............................................................14 ПРИЛОЖЕНИЕ C: ЗАЩИТА ОТ REPLAY сообщений .......................................... ................... 14
APPENDIX D: EXAMPLES ПРИЛОЖЕНИЕ D: Примеры ...................................................................................................................................15
D.1 D.1
AES-128...................................................................................................................................................15
D.2 Г.2
AES-192...................................................................................................................................................16
D.3 D.3
AES-256...................................................................................................................................................16
D.4 D.4
T Т
HREE HREE
K K
EY EY
TDEA....................................................................................................................................17
D.5 Г.5
T Т
WO WO
K K
EY EY
TDEA.......................................................................................................................................18
APPENDIX E: ПРИЛОЖЕНИЕ E: BIBLIOGRAPHY..........................................................................................................................19
Figures Цифры
Figure 1: Illustration of the two cases of MAC Generation........................................................... 9 Рисунок 1: Иллюстрация из двух случаев MAC поколения ....................................... .................... 9
1 1
1 Purpose 1 Цель
This publication is the second Part in a series of Recommendations regarding modes of operation Эта публикация является второй частью в серии Рекомендаций о режимах работы
of symmetric key block ciphers. симметричных ключевых блочных шифров.
2 Authority 2 Орган
This document has been developed by the National Institute of Standards and Technology Этот документ был разработан Национальным институтом стандартов и технологии
(NIST) in furtherance of its statutory responsibilities under the Federal Information Security (NIST) в реализации его уставных обязанностей в соответствии с Федеральным информационной безопасности
Management Act (FISMA) of 2002, Public Law 107-347. Закон об управлении (FISMA) 2002, Public Law 107-347.
NIST is responsible for developing standards and guidelines, including minimum requirements, NIST отвечает за разработку стандартов и руководящих принципов, включая минимальные требования,
for providing adequate information security for all agency operations and assets, but such для обеспечения надлежащей информационной безопасности для всех операций агентств и средств, но такие
standards and guidelines shall not apply to national security systems. стандарты и руководящие принципы не применяются к системам национальной безопасности. This guideline is consistent Это руководство согласуется
with the requirements of the Office of Management and Budget (OMB) Circular A-130, Section с требованиями Управления и бюджета (OMB) циркуляр-130, раздел
8b(3), Securing Agency Information Systems, as analyzed in A-130, Appendix IV: Analysis of 8b (3), Обеспечение Агентство информационных систем, как было проанализировано в A-130, Приложение IV: Анализ
Key Sections. Основные разделы. Supplemental information is provided in A-130, Appendix III. Справочная информация предоставляется в A-130, Приложение III.
This guideline has been prepared for use by federal agencies. Это руководство было подготовлено для использования федеральными органами. It may be used by Это может быть использовано
nongovernmental organizations on a voluntary basis and is not subject to copyright. неправительственные организации на добровольной основе и не охраняется авторским правом. (Attribution (Attribution
would be appreciated by NIST.) будет понятно NIST.)
Nothing in this document should be taken to contradict standards and guidelines made Ничто в этом документе не должны быть приняты, чтобы противоречить стандартов и руководящих принципов, сделанные
mandatory and binding on federal agencies by the Secretary of Commerce under statutory обязательный для исполнения на федеральных агентств секретарем Торгово под законом
authority. орган. Nor should these guidelines be interpreted as altering or superseding the existing Не следует эти руководящие принципы можно интерпретировать как изменение или заменяющий существующий
authorities of the Secretary of Commerce, Director of the OMB, or any other federal official. Власти министра торговли, директор Административно-бюджетное управление, или любой другой федеральный чиновник.
Conformance testing for implementations of the mode of operation that is specified in this Part Аттестационного тестирования для реализаций режима работы, указанного в настоящей части
of the Recommendation will be conducted within the framework of the Cryptographic Module Рекомендации будут проводиться в рамках криптографического модуля
Validation Program (CMVP), a joint effort of NIST and the Communications Security Проверка программы (CMVP), совместными усилиями NIST и безопасности коммуникаций
Establishment of the Government of Canada. Создание правительства Канады. An implementation of a mode of operation must Реализация режима работы должны
adhere to the requirements in this Recommendation in order to be validated under the CMVP. придерживаться требований в данной Рекомендации для того, чтобы быть подтверждено под CMVP.
The requirements of this Recommendation are indicated by the word “shall.” Требования данной Рекомендации обозначается словом «должны».
3 Introduction 3 Введение
This Recommendation specifies a message authentication code (MAC) algorithm that is based on В настоящей Рекомендации определяется код аутентификации сообщения (MAC) алгоритм, основанный на
a symmetric key block cipher. симметричный ключ блочный шифр. This cipher-based MAC is abbreviated CMAC, analogous to the Этот шифр на основе MAC сокращенно CMAC, аналогично
abbreviation for the hash function-based MAC, HMAC, that is standardized in FIPS Pub. сокращение для хэш-функции MAC, HMAC, что является стандартным в FIPS PUB. 198 198
[4]. [4]. CMAC may be appropriate for information systems in which an approved block cipher is CMAC может не подходить для информационных систем, в которых утверждены блочный шифр
more readily available than an approved hash function. более доступны, чем утвержденной хэш-функции.
The basic Cipher Block Chaining MAC algorithm (CBC-MAC) has security deficiencies [9]. Основная Cipher Block Chaining MAC алгоритм (CBC-MAC) имеет недостатки в системе защиты [9].
The core of the CMAC algorithm is a variation of CBC-MAC that Black and Rogaway proposed Ядром алгоритма CMAC является вариацией CBC-MAC, что черный и Rogaway предложил
and analyzed under the name XCBC in Ref. и анализировали под названием XCBC в работе. [2] and submitted to NIST in Ref. [2] и представлены в NIST в работе. [1]. [1]. The XCBC XCBC
2 2
algorithm efficiently addresses the security deficiencies of CBC-MAC. Алгоритм эффективно устраняет недостатки безопасности CBC-MAC. Iwata and Kurosawa Ивата и Куросава
proposed an improvement of XCBC and named the resulting algorithm One-Key CBC-MAC предложил улучшение XCBC и назвал получающийся алгоритм One-Key CBC-MAC
(OMAC) in Ref. (OMAC) в работе. [6] and in Ref. [6] и в работе. [5], their initial submission to NIST; [5], их первоначальное представление в NIST; they later submitted позже они представили
OMAC1 [7], a refinement of OMAC, and additional security analysis [8]. OMAC1 [7], уточнение OMAC, и дополнительный анализ безопасности [8]. The OMAC1 OMAC1
variation efficiently reduces the key size of XCBC. изменение эффективно уменьшает размер ключа XCBC. CMAC is equivalent to OMAC1. CMAC эквивалентно OMAC1.
Because CMAC is based on an approved symmetric key block cipher, such as the Advanced Потому CMAC основан на утвержденной симметричным ключом блочного шифра, например, Advanced
Encryption Standard (AES) algorithm that is specified in Federal Information Processing Encryption Standard (AES) алгоритм, который указан в Federal Information Processing
Standard (FIPS) Pub. Стандартный (ФИПС) Паб. 197 [3], CMAC can be considered a mode of operation of the block cipher. 197 [3], КЦР можно рассматривать режим работы блочного шифра.
CMAC is also an approved mode of the Triple Data Encryption Algorithm (TDEA) [10]; CMAC также утвержден режим тройного шифрования данных алгоритма (TDEA) [10];
however, as discussed in Appendix B, the recommended default message span for TDEA is Однако, как описано в Приложении B, рекомендуется продолжительность сообщения по умолчанию для TDEA является
much more restrictive than for the AES algorithm, due to the smaller block size of TDEA. гораздо более ограничительный характер, чем для алгоритма AES, за счет меньшего размера блока TDEA.
CMAC, like any well-designed MAC algorithm, provides stronger assurance of data integrity CMAC, как и любой хорошо разработанной алгоритма MAC, предоставляет надежные гарантии целостности данных
than a checksum or an error detecting code. чем контрольная сумма или ошибки обнаружения кода. The verification of a checksum or an error detecting Проверка контрольной суммы или об ошибке обнаружения
code is designed to detect only accidental modifications of the data, while CMAC is designed to Код предназначен для обнаружения только случайные модификации данных, в то время как CMAC предназначен для
detect intentional, unauthorized modifications of the data, as well as accidental modifications. обнаружить преднамеренные, несанкционированных модификаций данных, а также случайные изменения.
4 Definitions, Abbreviations, and Symbols 4 Определения, аббревиатуры и символы
4.1 Definitions and Abbreviations 4.1 Определения и сокращения
AES AES
Advanced Encryption Standard. Advanced Encryption Standard.
Approved Утверждено
FIPS approved or NIST recommended: an algorithm or technique that FIPS утверждены или NIST рекомендуется: алгоритм или метод, который
is either 1) specified in a FIPS or a NIST Recommendation, or 2) либо 1), указанных в ФИПС или рекомендацией NIST, или 2)
adopted in a FIPS or a NIST Recommendation. принят в ФИПС или рекомендацией NIST.
Authenticity Подлинность
The property that data originated from its purported source. Имущество, что данные собраны с его предполагаемой источника.
Bit Бит
A binary digit: 0 or 1. Двоичная цифра: 0 или 1.
Bit String Бит Строка
A finite, ordered sequence of bits. Конечное, упорядоченная последовательность битов.
Block Блок
For a given block cipher, a bit string whose length is the block size of Для данного блочного шифра, битовая строка, длина которой является размер блока
the block cipher. блочный шифр.
Block Cipher Блочный шифр
An algorithm for a parameterized family of permutations on bit Алгоритм параметризованным семье перестановок бит
strings of a fixed length. Строки фиксированной длины.
Block Size Размер блока
For a given block cipher, the fixed length of the input (or output) bit Для данного блочного шифра, фиксированная длина входа (или выхода) немного
strings. струны.
CBC CBC
Cipher Block Chaining. Cipher Block Chaining.
3 3
Collision Столкновение
For a given function, a pair of distinct input values that yield the same Для данной функции, пары различных значений входных, которые дают то же самое
output value. выходное значение.
Exclusive-OR Исключающее ИЛИ
The bitwise addition, modulo 2, of two bit strings of equal length. Побитовое сложение по модулю 2, из двух битовых строк равной длины.
FIPS FIPS
Federal Information Processing Standard. Федеральный стандарт обработки информации.
Forward Cipher Форвард Cipher
Function Функция
A permutation on blocks that is determined by the choice of a key for Перестановка на блоки, которые определяется выбора ключа для
a given block cipher. учитывая блочный шифр.
Integrity Честность
The property that received data has not been altered. Имущество, что полученные данные не были изменены.
Inverse Cipher Function The inverse function of the forward cipher function for a given block Обратная Cipher Функция обратную функцию переднего шифра функции для данного блока
cipher key. ключ шифрования.
Key Ключ
(Block Cipher Key) (Блочный шифр-ключ)
The parameter of the block cipher that determines the selection of the Параметр блочного шифра, который определяет выбор
forward cipher function from the family of permutations. направить шифрования функцию из семейства перестановок.
Least Significant Bit(s) Младший значащий бит (ы)
The right-most bit(s) of a bit string. Самый правый бит (ы) битовой строки.
Message Сообщение
Authentication Code Код аутентификации
(MAC) (MAC)
A bit string of fixed length, computed by a MAC generation Битовую строку фиксированной длины, вычисляется поколения MAC
algorithm, that is used to establish the authenticity and, hence, the Алгоритм, который используется для установления подлинности и, следовательно,
integrity of a message. целостности сообщения.
MAC Generation MAC поколение
(Generation) (Поколение)
An algorithm that computes a MAC from a message and a key. Алгоритм, который вычисляет MAC из сообщения и ключа.
MAC Verification MAC Проверка
(Verification) (Проверка)
An algorithm that verifies if a purported MAC is valid for a given Алгоритм, который проверяет, если предполагаемая MAC действительна для данного
message and key. сообщение и ключ.
Mode of Operation Режим работы
(Mode) (Режим)
An algorithm for the cryptographic transformation of data that Алгоритм криптографического преобразования данных, что
features a symmetric key block cipher. имеется симметричный ключ блочного шифра.
Most Significant Bit(s) Наиболее значащий бит (ы)
The left-most bit(s) of a bit string. Левый бит (ы) битовой строки.
NIST NIST
National Institute of Standards and Technology. Национальный институт стандартов и технологий.
Permutation Перестановка
An invertible function. Обратимая функция.
Subkey Подраздел
A secret string that is derived from the key. Секрет строка, которая выводится из ключа.
Subkey Generation Подраздел поколение
An algorithm that derives subkeys from a key. Алгоритм, который происходит подразделы из ключа.
TDEA TDEA
Triple Data Encryption Algorithm. Тройного шифрования данных Алгоритм.
4 4
4.2 Symbols 4.2 Символы
4.2.1 4.2.1
Variables Переменные
b б
The bit length of a block. Немного длина блока.
R R
b б
The constant string for subkey generation for a cipher with block size b . Постоянная строка для генерации подключа для шифра с размером блока б.
K K
The block cipher key. Ключ блочный шифр.
K1 K1
The first subkey. Первый подраздел.
K2 K2
The second subkey. Второй подраздел.
Key1 Key1
The first component of a TDEA key. Первый компонент ключа TDEA.
Key2 Key2
The second component of a TDEA key. Второй компонент ключа TDEA.
Key3 Key3
The third component of a TDEA key. Третий компонент ключа TDEA.
M М
The message. Сообщение.
M М
i я
The i th block of the formatted message. Я й блок форматированного сообщения.
M М
n н
* *
The final block, possibly a partial block, of the formatted message. Последний блок, возможно, частичный блок, в форматированное сообщение.
Mlen Mlen
The bit length of the message. Немного длина сообщения.
n н
The number of blocks in the formatted message. Число блоков в отформатированный сообщения.
T Т
The MAC. MAC.
Tlen Tlen
The bit length of the MAC. Немного длина MAC.
4.2.2 4.2.2
Operations and Functions Операции и функции
⎡ ⎤ ⎡ ⎤
x х
The least integer that is not less than the real number x . Наименьшее целое, что является не менее реальной числа х.
X || Y X || Y
The concatenation of two bit strings X and Y . Объединение двух битовых строк X и Y.
X ⊕ Y X ⊕ Y
The bitwise exclusive-OR of two bit strings X and Y of the same length. Побитовое исключающее ИЛИ двух битовых строк х и у той же длины.
CIPH CIPH
K K
( X ) (Х)
The output of the forward cipher function of the block cipher under the key K Выход вперед шифра функции блочного шифра в соответствии с ключевой K
applied to the block X . применяется к блок-X.
LSB LSB
s с
( X ) (Х)
The bit string consisting of the s right-most bits of the bit string X . Битовая строка, состоящая из с самых правых битов битовой строки X.
5 5
MSB MSB
s с
( X ) (Х)
The bit string consisting of the s left-most bits of the bit string X . Битовая строка, состоящая из с левой большинство биты битовой строки X.
X << 1 X << 1
The bit string that results from discarding the leftmost bit of the bit string X and Немного Строка, являющаяся результатом отбрасывая левый бит битовой строки X и
appending a '0' bit on the right. добавление '0' немного справа.
lg( x ) LG (х)
The base 2 logarithm of the positive real number x . Основание 2 логарифм положительного действительного числа х.
0 0
s с
The bit string that consists of s '0' bits. Битовая строка, которая состоит из S '0 "бит.
5 Preliminaries 5 Предварительные
The elements of CMAC and the associated notation are introduced in the five sections below. Элементы CMAC и ассоциированной нотации вводятся в пяти разделах.
Examples of operations and functions are given in Sec. Примеры операций и функций приведены в гл. 5.1. 5.1. The underlying block cipher and Лежащая в основе блочный шифр и
key are discussed in Sec. Ключ обсуждаются в разделе. 5.2. 5.2. The two subkeys that are derived from the key are discussed in Два подразделы, которые являются производными от ключа обсуждаются в
Sec. Sec. 5.3. 5.3. MAC generation and verification are discussed in Sec. Генерация и проверка MAC обсуждаются в разделе. 5.4. 5.4. The input and output data Входные и выходные данные
for MAC generation are discussed in Sec. для генерации MAC обсуждаются в разделе. 5.5. 5.5.
5.1 Examples of Operations and Functions 5.1 Примеры операций и функций
Given a positive integer s , 0 Учитывая положительное целое число с, 0
s с
denotes the string that consists of s '0' bits. обозначает строку, состоящую из S '0 "бит. For example, 0 Например, 0
8 8
= =
00000000. 00000000.
Given a real number x , the ceiling function, denoted ⎡x⎤, is the least integer that is not less than x . Учитывая действительное число х, функцию потолка, обозначаемый ⎡x⎤, является наименее целое число, которое не меньше, чем х.
For example, ⎡2.1⎤ = 3, and ⎡4⎤ = 4. Например, ⎡2.1⎤ = 3, и ⎡4⎤ = 4.
The concatenation operation on bit strings is denoted ||; Операция конгатенации битовых строк обозначается ||; for example, 001 || 10111 = 00110111. например, 001 || 10111 = 00110111.
Given bit strings of equal length, the exclusive-OR operation, denoted ⊕, specifies the addition, Учитывая битовые строки равной длины, исключающее ИЛИ операция, обозначается ⊕, указывает добавление,
modulo 2, of the bits in each bit position, ie, without carries. по модулю 2, из битов в позиции каждого бита, то есть, без переносов. For example, 10011 ⊕ 10101 = Например, 10011 10101 ⊕ =
00110. 00110.
Given a bit string X , the functions LSB Учитывая битовая строка X, функции LSB
s с
( X ) and MSB (Х) и MSB
s с
( X ) return the s least significant (ie, right- (X) возвращаются с младшим (т.е. правой
most) bits and the s most significant (ie, left-most) bits, respectively, of X . Наиболее) бит и самых значимых (т.е. самый левый) бит, соответственно, X. For example, Например,
LSB LSB
3 3
(111011010) = 010, and MSB (111011010) = 010, и MSB
4 4
(111011010) = 1110. (111011010) = 1110.
Given a bit string X that consists of Xlen bits, the (single) left-shift function, denoted X << 1, is Учитывая битовую строку X, которая состоит из Xlen бит, (одноместный) функция сдвига влево, обозначается X << 1, является
LSB LSB
Xlen Xlen
( X || 0). (X || 0). For example, 1101110 << 1 = 1011100. Например, 1101110 << 1 = 1011100.
Given a positive real number x , its base 2 logarithm is denoted lg( x ). Учитывая положительное действительное число х, его основание 2 логарифм обозначается LG (х). For example, lg(2 Например, LG (2
10 10
) = 10. ) = 10.
5.2 Block Cipher 5.2 блочный шифр
The CMAC algorithm depends on the choice of an underlying symmetric key block cipher. Алгоритм CMAC зависит от выбора базового симметричного ключа блочного шифра. The
CMAC algorithm is thus a mode of operation (a mode, for short) of the block cipher. Алгоритм КЦР Таким образом, режим работы (режим, для краткости) блочного шифра. The
CMAC key is the block cipher key (the key, for short). Ключ CMAC является ключевым блочный шифр (ключ, для краткости).
6 6
For any given key, the underlying block cipher of the mode consists of two functions that are Для любого данного ключа, лежащий в основе блочного шифра в режиме состоит из двух функций, которые
inverses of each other. обратными друг другу. The choice of the block cipher includes the designation of one of the two Выбор блочного шифра включает в себя назначение одного из двух
functions of the block cipher as the forward function/transformation, and the other as the inverse Функции блочного шифра, как вперед функции / трансформации, а другой в качестве обратного
function, as in the specifications of the AES algorithm and TDEA in Ref. Функция, как в спецификациях алгоритма AES и TDEA в работе. [3] and Ref. [3], и в. [10], [10],
respectively. соответственно. The CMAC mode does not employ the inverse function. Режим КЦР не использует обратную функцию.
The forward cipher function is a permutation on bit strings of a fixed length; Вперед шифр функция является перестановкой на битовых строк фиксированной длины; the strings are струны
called blocks. называемые блоки. The bit length of a block is denoted b , and the length of a block is called the block Немного длина блока обозначается B, и длина блока называется блок
size. Размер. For the AES algorithm, b = 128; Для алгоритма AES, б = 128; for TDEA, b = 64. The key is denoted K , and the Для TDEA, B = 64 Ключ обозначается K, и
resulting forward cipher function of the block cipher is denoted CIPH в результате вперед шифр функции блочного шифра обозначается CIPH
K K
. .
The underlying block cipher shall be approved, and the key shall be generated uniformly at Лежащая в основе блочный шифр должен быть утвержден, и ключ должен быть сгенерирован равномерно на
random, or close to uniformly at random, ie, so that each possible key is (nearly) equally likely случайной, или близко к равномерно случайным образом, то есть, так что каждый ключ можно (почти) с равной вероятностью
to be generated. , которые будут созданы. The key shall be secret and shall be used exclusively for the CMAC mode of Ключ является тайным и должны использоваться исключительно для режима CMAC из
the chosen block cipher. выбранная блочный шифр. The message span of the key is discussed in Appendix B. To fulfill the Пролет сообщение ключа обсуждается в Приложении B. Для выполнения
requirements on the key, the key should be established among the parties to the information требования к ключу, должны быть установлены ключ между сторонами информации
within an approved key management structure; в рамках утвержденной ключевой структуры управления; the details of the establishment and management подробности создания и управления
of keys are outside the scope of this Recommendation. ключей выходят за рамки настоящей Рекомендации.
5.3 Subkeys 5.3 Подключи
The block cipher key is used to derive two additional secret values, called the subkeys, denoted Ключ блочный шифр используется для получения двух дополнительных секретных значения, называется подразделы, обозначается
K1 and K2 . K1 и K2. The length of each subkey is the block size. Длина каждого подраздела является размер блока. The subkeys are fixed for any Подключи фиксируются для любого
invocation of CMAC with the given key. вызов CMAC с данным ключом. Consequently, the subkeys may be precomputed and Следовательно, подключи могут быть предварительно вычислены и
stored with the key for repeated use; сохраняются с ключом для многократного использования; alternatively, the subkeys may be computed anew for each С другой стороны, подразделы могут быть вычислены для каждого вновь
invocation. Вызов.
Any intermediate value in the computation of the subkey, in particular, CIPH Любое промежуточное значение в вычислении подраздела, в частности, CIPH
K K
(0 (0
b б
), shall also be ), Также должны быть
secret. Секрет. This requirement precludes the system in which CMAC is implemented from using this Это требование исключает систему, в которой реализован КЦР от использования этого
intermediate value publicly for some other purpose, for example, as an unpredictable value or as промежуточное значение публично для других целей, например, в качестве непредсказуемого значения или
an integrity check value on the key. Значение проверки целостности на ключ.
One of the elements of the subkey generation process is a bit string, denoted R Одним из элементов процесса генерации подраздел битовая строка, обозначается R
b б
, that is , То есть
completely determined by the number of bits in a block. полностью определяется количеством битов в блоке. In particular, for the two block sizes of В частности, для двух размерах блока
the currently approved block ciphers, R утвержденные в настоящее время блочные шифры, R
128 128
= 0 = 0
120 120
10000111, and R 10000111, и R
64 64
= 0 = 0
59 59
11011. 11011.
In general, R В общем, R
b б
is a representation of a certain irreducible binary polynomial of degree b , namely, это представление некоторого неприводимого двоичного полинома степени B, а именно,
the lexicographically first among all such polynomials with the minimum possible number of лексикографически первое место среди всех таких многочленов с минимальной возможного числа
nonzero terms. ненулевые члены. If this polynomial is expressed as u Если этот многочлен выражается в виде U
b б
+ c + C
b -1 б -1
u у
b -1 б -1
+...+ c + ... + C
2 2
u у
2 2
+ c + C
1 1
u + c и + с
0 0
, where the , Где
coefficients c коэффициенты с
b -1 б -1
, c , С
b -2 б -2
, ... , c , ..., С
2 2
, c , С
1 1
, c , С
0 0
are either 0 or 1, then R либо 0, либо 1, то R
b б
is the bit string c является битовая строка C
b -1 б -1
c с
b -2 б -2
...c ... с
2 2
c с
1 1
c с
0 0
. .
5.4 MAC Generation and Verification 5.4 MAC формирования и проверки
As for any MAC algorithm, an authorized party applies the MAC generation process to the data Как и для любого алгоритма MAC, уполномоченная сторона применяет процесс генерации MAC к данным
to be authenticated to produce a MAC for the data. , чтобы пройти проверку подлинности для получения MAC для данных. Subsequently, any authorized party can Впоследствии, любая уполномоченная сторона может
apply the verification process to the received data and the received MAC. применить процесс проверки на полученных данных и принятого MAC. Successful Успешная
verification provides assurance of data authenticity, as discussed in Appendix A, and, hence, of проверка дает гарантию подлинности данных, как описано в Приложении А, и, следовательно, из
7 7
integrity. целостность.
5.5 Input and Output Data 5.5 Ввод и вывод данных
For a given block cipher and key, the input to the MAC generation function is a bit string called Для данного блочного шифра и ключа, вход в функцию генерации MAC является битовая строка называется
the message, denoted M . сообщение, обозначается М. The bit length of M is denoted Mlen . Битовая длина M обозначается Mlen. The value of Mlen is not an Значение Mlen не
essential input for the MAC generation algorithm if the implementation has some other means of существенный вклад в алгоритме генерации MAC, если реализация имеет некоторые другие средства
identifying the last block in the partition of the message, as discussed in Sec. выявления последний блок в разделе сообщения, как описано в гл. 6.2. 6.2. Thus, in such a Таким образом, в таком
case, the computation of the MAC may begin “on-line” before the entire message is available. случай, вычисление MAC может начаться "он-лайн", прежде чем все сообщение доступно. In В
principle, there is no restriction on the lengths of messages. Принцип, нет никаких ограничений на длины сообщений. In practice, however, the system in На практике, однако, система в
which CMAC is implemented may restrict the length of the input messages to the MAC которые CMAC программы, может ограничить длину входных сообщений на MAC
generation function. Функция генерации.
The output of the MAC generation function is a bit string called the MAC, denoted T . Выход функции генерации MAC является битовая строка называется MAC-, обозначается T. The
length of T , denoted Tlen , is a parameter that shall be fixed for all invocations of CMAC with the Длина T, обозначается Tlen, это параметр, который устанавливается для всех вызовов CMAC с
given key. учитывая ключ. The requirements for the selection of Tlen are given in Appendix A. Требования к отбору Tlen приведены в Приложении А.
6 CMAC Specification 6 CMAC Спецификация
Subkey generation, MAC generation, and MAC verification are specified in Sections 6.1, 6.2, Подраздел поколение, поколение MAC, и MAC проверка указаны в разделах 6.1, 6.2,
and 6.3 below. и 6.3 ниже. The specifications include the inputs, the outputs, a suggested notation for the Спецификации включают входы, выходы, предложил использовать для обозначения
function, the steps, and a summary; Функция, шаги, и резюме; for MAC generation, a diagram is also given. для генерации MAC, схема которого также приведены. The inputs Входы
that are typically fixed across many invocations of CMAC are called the prerequisites. что, как правило, фиксируется через многие вызовы CMAC называются предпосылки. The
prerequisites and the other inputs shall meet the requirements in Sec. предпосылки и другие входы должны соответствовать требованиям абз. 5. The suggested notation 5 предложил обозначения
does not include the block cipher. не включает в себя блочный шифр.
6.1 Subkey Generation 6.1 Подраздел поколение
The following is a specification of the subkey generation process of CMAC: Ниже приводится спецификация процесса генерации подраздела CMAC:
Prerequisites : Необходимые условия:
block cipher CIPH with block size b ; блочный шифр CIPH с размером блока б;
key K . ключ К.
Output : Выход:
subkeys K1 , K2. подключи К1, К2.
Suggested Notation : Предлагаемые Обозначения:
SUBK( K ). SUBK (К).
Steps : Шаги:
1. 1.
Let L = CIPH Пусть L = CIPH
K K
(0 (0
b б
). ).
2. 2.
If MSB Если MSB
1 1
( L ) = 0, then K1 = L << 1; (L) = 0, то K1 = L << 1;
Else K1 = ( L << 1) ⊕ R Остальное K1 = (L << 1) ⊕ R
b б
; ; see Sec. см. 5.3 for the definition of R 5.3 для определения R
b б
. .
3. 3.
If MSB Если MSB
1 1
( K1 ) = 0, then K2 = K1 << 1; (К1) = 0, то К2 = К1 << 1;
Else K2 = ( K1 << 1) ⊕ R Остальное К2 = (K1 << 1) ⊕ R
b б
. .
8 8
4. 4.
Return K1 , K2 . Вернуться K1, K2.
In Step 1, the block cipher is applied to the block that consists entirely of '0' bits. На шаге 1, блочный шифр применяется к блоку, который полностью состоит из "0" бит. In Step 2, the На шаге 2,
first subkey is derived from the resulting string by a left shift of one bit, and, conditionally, by первый подраздел является производным от полученной строки путем сдвига влево на один бит, и, условно, путем
XORing a constant that depends on the block size. XORing постоянная, зависящая от размера блока. In Step 3, the second subkey is derived in На шаге 3, второй подраздел происходит в
the same manner from the first subkey. таким же образом с первого подключа.
1 1
As discussed in Sec. Как уже говорилось в гл. 5.3, any intermediate value in the 5.3, любое промежуточное значение в
computation of the subkey, in particular, CIPH вычисление подключа, в частности, CIPH
K K
(0 (0
b б
), shall be secret. ), Является тайным.
6.2 MAC Generation 6.2 MAC поколение
The following is a specification of the MAC generation process of CMAC: Ниже приводится спецификация процесса генерации MAC из CMAC:
Prerequisites : Необходимые условия:
block cipher CIPH with block size b ; блочный шифр CIPH с размером блока б;
key K ; ключ К;
MAC length parameter Tlen . Параметр длины MAC Tlen.
Input : Вход:
message M of bit length Mlen. сообщение M длины немного Mlen.
Output : Выход:
MAC T of bit length Tlen. MAC T длины немного Tlen.
Suggested Notation : Предлагаемые Обозначения:
CMAC( K , M , Tlen ) or, if Tlen is understood from the context, CMAC( K , M ). CMAC (K, M, Tlen) или, если Tlen понимается из контекста, CMAC (K, M).
Steps : Шаги:
1. 1.
Apply the subkey generation process in Sec. Применить процесс генерации подраздела в гл. 6.1 to K to produce K1 and K2 . 6.1 на К произвести K1 и K2.
2. 2.
If Mlen = 0, let n = 1; Если Mlen = 0, пусть п = 1; else, let n = ⎡ Mlen / b ⎤. еще, пусть п = ⎡ Mlen / B ⎤.
3. 3.
Let M Пусть M
1 1
, M , M
2 2
, ... , M , ..., M
n -1 П -1
, M , M
n н
* *
denote the unique sequence of bit strings such that M = обозначать уникальную последовательность битовых строк такое, что M =
M М
1 1
|| M || M
2 2
|| ... || M || ... || M
n -1 П -1
|| M || M
n н
* *
, where M , Где М
1 1
, M , M
2 2
,..., M , ..., M
n -1 П -1
are complete blocks. полные блоки.
2 2
4. 4.
If M Если M
n н
* *
is a complete block, let M является полная блокада, пусть M
n н
= K1 ⊕ M = K1 ⊕ M
n н
* *
; ; else, let M еще, пусть M
n н
= K2 ⊕ ( M = К2 ⊕ (M
n н
* *
||10 || 10
j J
), ),
where j = nb - Mlen -1. где J = NB - Mlen -1.
5. 5.
Let C Пусть C
0 0
= 0 = 0
b б
. .
6. 6.
For i = 1 to n , let C Для я = 1 до п, пусть C
i я
= CIPH = CIPH
K K
( C (С
i -1 я -1
⊕ M ⊕ M
i я
). ).
7. 7.
Let T = MSB Пусть T = MSB
Tlen Tlen
( C (С
n н
). ).
8. 8.
Return T. Вернуться Т.
In Step 1, the subkeys are generated from the key. На шаге 1, подключи генерируются из ключа. In Steps 2–4, the input message is formatted На этапах 2-4, входное сообщение отформатировать
into a sequence of complete blocks in which the final block has been masked by a subkey. в последовательность полных блоков, в которых конечный блок был замаскирован с помощью подключа. There Там
are two cases: два случая:
1 1
As detailed in Ref. Как подробно в работе. [5], the generation of K1 and K2 is essentially equivalent to multiplication by u and u [5], генерация К1 и К2 по существу эквивалентно умножения на и и и
2 2
, ,
respectively, within the Galois field that is determined by the irreducible polynomial that is represented by R соответственно, в поле Галуа, что определяется неприводимым многочленом, представленного R
b б
, which , Которые
is discussed in Sec. обсуждается в гл. 5.3. 5.3.
2 2
Consequently, if Mlen ≤ b , then M = M Следовательно, если Mlen ≤ б, то М = М
1 1
* *
. .
9 9
• If the message length is a positive multiple of the block size, then the message is • Если длина сообщения является положительным кратным размеру блока, то сообщение является
partitioned into complete blocks. разбивается на полных блоков. The final block is masked with the first subkey; Последний блок маскируется с первого подключа; in в
other words, the final block in the partition is replaced with the exclusive-OR of the final Другими словами, окончательный блок в разделе заменяется ИСКЛЮЧАЮЩЕЕ ИЛИ конечный
block with the first subkey. блокировать с первого подраздела. The resulting sequence of blocks is the formatted message. Полученная последовательность блоков является отформатирован сообщение.
• If the message length is not a positive multiple of the block size, then the message is • Если длина сообщения не является положительным кратным размеру блока, то сообщение является
partitioned into complete blocks to the greatest extent possible, ie, into a sequence of разбивается на полных блоков в максимально возможной степени, то есть, в последовательность
complete blocks followed by a final bit string whose length is less than the block size. полные блоки с последующей конечной битовой строки, длина которой меньше размера блока. A
padding string is appended to this final bit string, in particular, a single '1' bit followed обивка строка добавляется к этой заключительной строки битов, в частности, немного одной '1' с последующим
by the minimum number of '0' bits, possibly none, that are necessary to form a complete минимальным количеством битов «0», возможно, ни один, которые необходимы, чтобы сформировать полный
block. блок. The complete final block is masked, as described in the previous bullet, with the Полный Последний блок маскируется, как описано в предыдущем пункте, с
second subkey. Второй подраздел. The resulting sequence of blocks is the formatted message. Полученная последовательность блоков является отформатирован сообщение.
In Steps 5 and 6, the cipher block chaining (CBC) technique, with the zero block as the В шагах 5 и 6, шифр цепь блоков (CBC) техники, с нулевой блок в качестве
initialization vector, is applied to the formatted message. вектор инициализации, применяется к форматированное сообщение. In Steps 7 and 8, the final CBC output В шаги 7 и 8, окончательного вывода CBC
block is truncated according to the MAC length parameter that is associated with the key, and the Блок усекается в соответствии с параметром длины MAC, который связан с ключом, и
result is returned as the MAC. Результат возвращается как MAC.
Equivalent sets of steps, ie, procedures that yield the correct output from the same input, are Эквивалентные набора шагов, т.е. процедуры, которые дают правильный результат из одного входа, которые
permitted. допускается. For example, it is not necessary to complete the formatting of the entire message Например, нет необходимости, чтобы завершить форматирование всего сообщения
(Steps 3 and 4) prior to the cipher block chaining (Steps 5 and 6). (пункты 3 и 4) до блока шифрования цепочки (пункты 5 и 6). Instead, the iterations of Step Вместо этого, итерации Шаг
5 may be executed “on the fly,” ie, on each successive block of the message as soon as it is 5 может быть выполнен «на лету», то есть, на каждом последующем блоке сообщения, как только это
available for processing. доступны для обработки. Step 4 may be delayed until the final bit string in the partition is Шаг 4 может быть отложено до окончательного битовую строку в раздел не является
available; доступны; the appropriate case, and value of j , if necessary, can be determined from the length of соответствующий корпус, и значение J, в случае необходимости, может быть определена по длине
the final bit string. Окончательный битовая строка. In such an implementation, the determination in Step 2 of the total number of В такой реализации, определение на стадии 2 общего количества
blocks in the formatted message may be omitted, assuming that the implementation has another блоки в форматированное сообщение может быть опущен, если предположить, что осуществление имеет другое
way to identify the final string in the partition. способ определить окончательный строку в разделе.
Similarly, the subkeys need not be computed anew for each invocation of CMAC with a given Аналогично, подключи должны быть не вычисляется заново для каждого вызова CMAC с учетом
key; ключ; instead, they may be precomputed and stored along with the key as algorithm inputs. вместо этого, они могут быть предварительно вычислены и сохранены вместе с ключом в качестве входов алгоритма.
Figure 1: Illustration of the two cases of MAC Generation. Рисунок 1: Иллюстрация из двух случаев MAC поколения.
… ...
K 1 К 1
MSB MSB
Tlen Tlen
T Т
CIPH CIPH
K K
CIPH CIPH
K K
M М
1 1
M М
2 2
⊕ ⊕
CIPH CIPH
K K
M М
n н
* *
⊕ ⊕
… ...
K 2 К 2
MSB MSB
Tlen Tlen
T Т
CIPH CIPH
K K
CIPH CIPH
K K
M М
1 1
M М
2 2
⊕ ⊕
CIPH CIPH
K K
M М
n н
* *
⊕ ⊕
10…0 10 ... 0
… ...
K 1 К 1
MSB MSB
Tlen Tlen
T Т
CIPH CIPH
K K
CIPH CIPH
K K
M М
1 1
M М
2 2
⊕ ⊕
CIPH CIPH
K K
M М
n н
* *
⊕ ⊕
… ...
K 2 К 2
MSB MSB
Tlen Tlen
T Т
CIPH CIPH
K K
CIPH CIPH
K K
M М
1 1
M М
2 2
⊕ ⊕
CIPH CIPH
K K
M М
n н
* *
⊕ ⊕
10…0 10 ... 0
10 10
The two cases of MAC Generation are illustrated in Figure 1 above. Два случая из MAC поколения представлены на рисунке 1 выше. On the left is the case С левой стороны и в случае
where the message length is a positive multiple of the block size; где длина сообщения является положительным кратным размера блока; on the right is the case where по праву является случай, когда
the message length is not a positive multiple of the block length. длина сообщения не является положительным кратным длине блока.
6.3 MAC Verification 6.3 MAC Проверка
The following is a specification of the MAC verification process of CMAC: Ниже приводится спецификация процесса проверки MAC из CMAC:
Prerequisites : Необходимые условия:
block cipher CIPH with block size b ; блочный шифр CIPH с размером блока б;
key K ; ключ К;
subkeys K1 , K2 ; подключи К1, К2;
MAC length Tlen . Длина MAC Tlen.
Input : Вход:
message M of bit length Mlen ; сообщение M длины немного Mlen;
received MAC T'. получил MAC T '.
Output : Выход:
VALID or INVALID . Действительным или недействительным.
Suggested Notation : Предлагаемые Обозначения:
VER( K , M , T' ). VER (K, M, T ').
Steps : Шаги:
1. 1.
Apply the MAC generation process in Sec. Применить процесс генерации MAC в гл. 6.2 to M to produce T . 6.2 М производить T.
2. 2.
If T = T' , return VALID; Если Т = Т ', вернуться ДЕЙСТВИТЕЛЬНО; else, return INVALID. еще, вернуться недействительными.
In Step 1, the MAC generation process in Sec. На шаге 1, процесс генерации MAC в гл. 6.2 is applied to the message, and, in Step 2, the 6,2 применяется к сообщению, и, на шаге 2,
resulting MAC is compared with the received MAC to determine its validity. Полученный MAC сравнивается с полученным MAC, чтобы определить его достоверность.
11 11
Appendix A: Length of the MAC Приложение: Длина MAC
The length, Tlen , of the MAC is an important security parameter. Длина, Tlen, из MAC является важным параметром безопасности. The role of this parameter in Роль этого параметра в
resisting guessing attacks is outlined in Sec. сопротивление гадать атак, изложены в гл. A.1, and guidance in the selection of Tlen is given in А.1, и руководство в выборе Tlen приводится в
Sec. Sec. A.2. А.2.
A.1 A.1
Assurance Against Guessing Attacks Обеспечение от подбора атак
The verification process determines whether the purported MAC on a message is the valid output Процесс проверки определяет, является ли предполагаемый MAC на сообщения является действительным выход
of the MAC generation process applied to the message. из процесса генерации MAC применяется к сообщению. The output of the MAC verification Выходной сигнал проверки MAC
determines the assurance that the receiver of the message obtains: определяет гарантии, что получатель сообщения получает:
• If the output is INVALID, then the message is definitely not authentic, ie, it did not • Если выход является недействительным, то сообщение, безусловно, не является подлинным, то есть, это не так
originate from a source that executed the generation process on the message to produce происходят из источника, который выполняется процесс генерации на сообщения для получения
the purported MAC. предполагаемый MAC.
• If the output is VALID, then the design of the mode provides assurance that the message • Если выход действителен, то конструкция режиме обеспечивает гарантию того, что сообщения
is authentic and, hence, was not corrupted in transit; является подлинным и, следовательно, не был поврежден при транспортировке; however, this assurance, as for any Тем не менее, эта уверенность, как и для любого
MAC algorithm, is not absolute. Алгоритм MAC, не является абсолютным.
In the second case, an attacker, ie, a party without access to the key or to the MAC generation Во втором случае, злоумышленник, то есть, партии, не имеющих доступа к ключу или к поколению MAC
process, may have simply guessed the correct MAC for the message. Процесс, может просто предположили правильный MAC для сообщения. In particular, if the attacker В частности, если взломщик
selects a MAC at random from the set of strings of length Tlen bits, then the probability is 1 in выбирает MAC случайным образом из множества строк длиной TLEN бит, то вероятность составляет 1 к
2 2
Tlen Tlen
that the MAC will be valid. что MAC будет действителен. Consequently, larger values of Tlen provide greater protection Следовательно, большие значения Tlen обеспечить более надежную защиту
against such an event. против такого события. Of course, an attacker may attempt to systematically guess many different Конечно, злоумышленник может попытаться систематически думаю много разных
MACs for a message, or for different messages, and thereby increase the probability that one (or MACS для сообщения, или для разных сообщений, и тем самым увеличить вероятность того, что один (или
more) of them will be accepted as valid. более) из них будет признаваться действительным. For this reason, a system should limit the number of По этой причине, система должна ограничить число
unsuccessful verification attempts for each key. неудачная проверка пытается для каждого ключа.
A.2 А.2
Selection of the MAC Length Выбор MAC Длина
Larger values of Tlen provide greater assurance against guessing attacks. Большие значения Tlen дает больше гарантий от подбора атак. The performance Спектакль
tradeoff is that larger values of Tlen require more bandwidth/storage for the MAC. компромисс в том, что большие значения Tlen требуют большей пропускной способности / хранилище для MAC.
For most applications, a value for Tlen that is at least 64 should provide sufficient protection Для большинства приложений достаточно значения для Tlen что, по крайней мере 64 должны обеспечить достаточную защиту
against guessing attacks. от подбора атак. A value of Tlen that is less than 64 shall only be used in conjunction Значение Tlen что меньше 64 должны использоваться только в сочетании
with a careful analysis of the risks of accepting an inauthentic message as authentic. с тщательного анализа рисков на себя имеющее недостоверную сообщение как подлинные.
In particular, a value of Tlen smaller than 64 should not be used unless the controlling protocol В частности, значение Tlen меньше, чем 64 не следует использовать, если контрольного протокола
or system sufficiently restricts the number of times that the verification process can return или система достаточно ограничивает количество раз, что процесс проверки может вернуться
INVALID, across all implementations with any given key. Недействительным, во всех реализациях с любой заданной клавиши. For example, the short duration of a Например, короткая продолжительность
session or, more generally, the low bandwidth of the communication channel may preclude many сессия или, в более общем плане, низкая пропускная способность канала связи может препятствовать многие
repeated trials. повторные испытания.
12 12
This guidance can be quantified in terms of the following two bounds: 1) the highest acceptable Это руководство может быть определена количественно в терминах следующих два прыжка: 1) высокая приемлемым
probability for an inauthentic message to pass the verification process, and 2) a limit on the Вероятность для недостоверного сообщения пройти процесс проверки, и 2) ограничение на
number of times that the output is the error message INVALID before the key is retired, across количество раз, что выход сообщение об ошибке верным до ключ на пенсию, по
all implementations of the verification process for the key. все реализации процесса проверки для клавиши. Given estimates of these quantities, Учитывая оценки этих величин,
denoted Risk and MaxInvalids , respectively, Tlen should satisfy the following inequality: обозначаемое рисками и MaxInvalids, соответственно, Tlen должны удовлетворять неравенству:
) )
/ /
lg( LG (
Risk Риск
s с
MaxInvalid MaxInvalid
Tlen ≥ Tlen ≥
. .
For example, suppose that the MAC verification process(es) within a system will not output Например, предположим, что процесс проверки MAC-(ES) в системе не будет выводить
INVALID for more than 1024 messages before the key is retired (ie, MaxInvalids = 2 INVALID для более 1024 сообщений, прежде чем ключ на пенсию (то есть, MaxInvalids = 2
10 10
), and ) И
that the users can tolerate about a one in a million chance that the system will accept an что пользователи могут терпеть около одного на миллион случайно, что система будет принимать
inauthentic message (ie, Risk = 2 недостоверной сообщение (то есть, риск = 2
-20 -20
). ). In this case, any value of Tlen that is greater than or equal В этом случае любое значение Tlen, что является большим или равным
to 30 satisfies the inequality. 30 удовлетворяет неравенству.
13 13
Appendix B: Message Span of the Key Приложение B: Сообщение Span Ключа
The message span of a key is the total number of messages for which MACs are generated across Пролет сообщение ключа является общее количество сообщений, для которых ПДК генерируются по
all implementations of CMAC with that key. все реализации CMAC с этим ключом. The message span of the key affects the security of Продолжительность сообщение ключа влияет на безопасность
the system against attacks that are based on the detection of a pair of distinct messages with the система от атак, которые основаны на обнаружении паре различных сообщений с
same MAC before its truncation же MAC до его усечения
3 3
. . Such a pair is called a collision Такая пара называется столкновения
4 4
in this appendix. в этом приложении. As with Как и в случае
other block cipher-based MAC algorithms, an attacker may be able to exploit a collision to другие MAC алгоритмы блочный шифр основе, злоумышленник может использовать столкновения в
produce the valid MAC for a new message, the content of which may be largely of the attacker's произвести действительный MAC для нового сообщения, содержание которого может быть в значительной степени из атакующего
choosing. Выбор. Such an event would be a fundamental breach of the expected authentication Такое событие было бы существенное нарушение ожидаемого аутентификации
assurance. Обеспечение.
In principle, collisions must exist because there are many more possible messages than MACs; В принципе, столкновения должны существовать, потому что есть множество других способов сообщений, чем ПДК; in в
practice, however, collisions may not occur among the messages for which MACs are actually Практика, однако, столкновения могут не встречаются среди сообщений, для которых ПДК фактически
generated during the lifetime of the key. генерируется во время жизни ключа. The probability that at least one collision will occur Вероятность того, что будет происходить, по меньшей мере одно столкновение
depends mostly on the message span of the key relative to the block size, b , of the underlying зависит в основном от продолжительности сообщений из ключевых относительно размера блока, б, базового актива
block cipher. блочный шифр. For example, a collision is expected to exist among a set of 2 Например, столкновение, как ожидается, существует среди множества 2
b /2 б / 2
arbitrary messages; произвольные сообщения;
in other words, 2 Другими словами, 2
64 64
messages for the AES algorithm, and 2 Сообщения для алгоритма AES и 2
32 32
messages for TDEA. Сообщения для TDEA. This property Это свойство
was one of the motivations to develop the AES with a block size of 128 bits. было одним из мотивов по развитию AES с размером блока 128 бит.
For any system in which CMAC is implemented, the risk that an attacker can detect and exploit a Для любой системы, в которой CMAC реализуется, риск, что злоумышленник может обнаружить и использовать
collision shall be limited to a level that is appropriate to the value of the data. Столкновение должно быть ограничено до уровня, который соответствует значению данных. A simple and Простой и
prudent method to achieve this goal is to establish and enforce an appropriate limit on the благоразумным способом для достижения этой цели является установление и соблюдение соответствующего ограничения на
message span of any CMAC key, which in turn limits the probability that a collision will even продолжительность сообщение любой клавиши CMAC, что в свою очередь ограничивает вероятность, что столкновение будет еще
occur. произойти. For general-purpose applications, the default recommendation is to limit the key to no Для приложений общего назначения, рекомендация по умолчанию является ограничение ключ к не
more than 2 более 2
48 48
messages when the block size of the underlying block cipher is 128 bits, as with Сообщения, когда размер блока блочного шифра 128 бит, как и
the AES algorithm, and 2 Алгоритм AES, и 2
21 21
messages when the block size is 64 bits, as with TDEA. Сообщения когда размер блока составляет 64 бита, а с TDEA. Within В
these limits, the probability that a collision will occur is expected to be less than one in a billion эти пределы, вероятность того, что будет происходить столкновение как ожидается, будет меньше, чем один к миллиарду
for the AES algorithm, and less than one in a million for TDEA. для алгоритма AES, и меньше, чем один на миллион для TDEA.
For applications where higher confidence in the security is required, the message span of a key Для приложений, где выше уверенность в безопасности требуется, пролета сообщения ключа
may be measured in terms of the total number of message blocks. может быть измерена с точки зрения общего количества блоков сообщений. The recommendation in this Рекомендация в этом
case is to limit the key to no more than 2 случай, чтобы ограничить ключ не более чем 2
48 48
message blocks (2 блоки сообщений (2
22 22
Gbytes) when the block size is Гбайт), когда размер блока
128 bits, and 2 128 бит, и 2
21 21
message blocks (16 Mbytes) when the block size is 64 bits. блоки сообщений (16 Мбайт), когда размер блока составляет 64 бита. Within these limits, В этих пределах,
the probability that a collision will occur is proved to be less than one in a billion for the AES вероятность того, что столкновение произойдет доказано быть менее чем один на миллиард для AES
algorithm, and less than one in a million for TDEA, assuming that the underlying block cipher Алгоритм, и меньше, чем один на миллион для TDEA, предполагая, что основной блочного шифра
has no weakness, as modeled in Ref. не имеет слабость, как образцу в работе. [6]. [6].
In some cases, a limit on the message span of a key may be established and enforced within a В некоторых случаях, ограничение на продолжительность сообщений ключа может быть создана и исполнению в течение
key management infrastructure by an appropriate constraint on the time span during which the ключ управления инфраструктурой соответствующим ограничением на период времени, в течение которого
key remains in effect, ie, its cryptoperiod. ключ остается в силу, то есть, его cryptoperiod.
3 3
The MAC before truncation is denoted C MAC до усечения обозначается C
m м
in Sec. в гл. 6.2. 6.2.
4 4
The standard definition of a collision, in Ref. Стандартное определение столкновения, в работе. [9], for example, is more general: for a given function, a collision is a [9], например, является более общим: для заданной функции, столкновение
pair of distinct input values that yield the same output value. пара различных входных значений, которые дают тот же выходное значение.
14 14
Appendix C: Protection Against Replay of Messages Приложение C: Защита от Replay из сообщения
As described in Appendix A, the successful verification of a MAC for a message gives assurance Как описано в Приложении А, успешной проверки на MAC для сообщения дает уверенность
that the source of the message executed the MAC generation algorithm to create the MAC; что источник сообщения выполняется алгоритм генерации MAC для создания MAC;
however, the party that presented the message and MAC for verification may not be the original Однако, партия, которая представила сообщение и MAC для проверки не может быть оригинал
source of the message. источник сообщения. Therefore, the CMAC algorithm does not inherently prevent an attacker Таким образом, алгоритм CMAC по своей природе не помешает взломщику
from intercepting a legitimate message and its MAC and “replaying” them for verification at a от перехвата законную сообщение и его MAC и "воспроизведение" их для проверки в
later time, for example, in an attempt to impersonate a party that has access to the key. более позднее время, например, в попытке выдать себя партию, которая имеет доступ к ключу. In some В некоторых
protocols an attacker may even be able to present to a verifier a message-MAC pair that the Протоколы злоумышленник может даже быть в состоянии представить верификатором пару сообщение-MAC, что
verifier itself generated earlier in the protocol. Verifier сама сформировалась раньше в протоколе.
The controlling protocol or application may protect against such an event by incorporating Контрольный протокол или приложение может защитить от такого события путем включения
certain identifying information into the initial bits of every message. уверен идентифицирующую информацию в начальных битов каждого сообщения. Examples of such Примерами таких
information include a sequential message number, a timestamp, or a nonce. Информация включает порядковый номер сообщение, временную метку, или случайное слово. Upon successful После успешной
verification of the message, this information may provide a means for the detection of replayed проверка сообщения, эта информация может служить средством для обнаружения переигран
messages, out-of-sequence messages, or missing messages. Сообщения, вне последовательности сообщений или отсутствующих сообщений.
15 15
Appendix D: Examples Приложение D: Примеры
In this appendix, twenty examples are provided for the MAC generation process. В этом приложении, двадцать примеры приведены для процесса генерации MAC. The underlying Лежащая в основе
block cipher is either the AES algorithm or TDEA. блочный шифр либо алгоритм AES или TDEA. A block cipher key is fixed for each of the Ключа блочного шифра фиксируется для каждого из
currently allowed key sizes, ie, AES-128, AES-192, AES-256, two key TDEA, and three key В настоящее время разрешено ключевые размеры, то есть, AES-128, AES-192, AES-256, два ключа TDEA, и три ключа
TDEA. TDEA. For each key, the generation of the associated subkeys is given, followed by four Для каждого ключа, генерирование соответствующих подразделах дается, а затем четыре
examples of MAC generation with the key. примеры поколения MAC с помощью ключа. The messages in each set of examples are derived by Сообщения в каждом наборе примеров получены путем
truncating a common fixed string of 64 bytes. усечения общую неподвижную строку из 64 байт.
All strings are represented in hexadecimal notation, with a space (or a new line) inserted every 8
symbols, for readability. As before, K1 and K2 denote the subkeys, M denotes the message, and
T denotes the MAC. For the AES algorithm examples, Tlen is 128, ie, 32 hexadecimal
symbols, and K denotes the key. For the TDEA examples, Tlen is 64, ie, 16 hexadecimal
symbols, and the key, K , is the ordered triple of strings, ( Key1 , Key2 , Key3 ), consistent with Ref.
[10]. [10]. For two key TDEA, Key1 = Key3 .
D.1 AES-128
For Examples 1–4 below, the block cipher is the AES algorithm with the following 128 bit key:
K K
2b7e1516 28aed2a6 abf71588 09cf4f3c .
Subkey Generation
CIPH
K K
(0 (0
128 128
) )
7df76b0c 1ab899b3 3e42f047 b91b546f
K1 K1
fbeed618 35713366 7c85e08f 7236a8de
K2 K2
f7ddac30 6ae266cc f90bc11e e46d513b
Example 1: Mlen 0
M М
<empty string>
T Т
bb1d6929 e9593728 7fa37d12 9b756746
Example 2: Mlen = 128
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
T Т
070a16b4 6b4d4144 f79bdd9d d04a287c
Example 3: Mlen = 320
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
30c81c46 a35ce411
T Т
dfa66747 de9ae630 30ca3261 1600c827
Example 4: Mlen = 512
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
30c81c46 a35ce411 e5fbc119 1a0a52ef
16 16
f69f2445 df4f9b17 ad2b417b e66c3710
T Т
51f0bebf 7e3b9d92 fc497417 79363cfe
D.2 AES-192
For Examples 5–8 below, the block cipher is the AES algorithm with the following 192 bit key:
K K
8e73b0f7 da0e6452 c810f32b 809079e5
62f8ead2 522c6b7b .
Subkey Generation
CIPH
K K
(0 (0
128 128
) )
22452d8e 49a8a593 9f7321ce ea6d514b
K1 K1
448a5b1c 93514b27 3ee6439d d4daa296
K2 K2
8914b639 26a2964e 7dcc873b a9b5452c
Example 5: Mlen = 0
M М
<empty string>
T Т
d17ddf46 adaacde5 31cac483 de7a9367
Example 6: Mlen = 128
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
T Т
9e99a7bf 31e71090 0662f65e 617c5184
Example 7: Mlen = 320
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
30c81c46 a35ce411
T Т
8a1de5be 2eb31aad 089a82e6 ee908b0e
Example 8: Mlen = 512
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
30c81c46 a35ce411 e5fbc119 1a0a52ef
f69f2445 df4f9b17 ad2b417b e66c3710
T Т
a1d5df0e ed790f79 4d775896 59f39a11
D.3 AES-256
For Examples 9–12 below, the block cipher is the AES algorithm with the following 256 bit key:
K K
603deb10 15ca71be 2b73aef0 857d7781
1f352c07 3b6108d7 2d9810a3 0914dff4 .
Subkey Generation
CIPH
K K
(0 (0
128 128
) )
e568f681 94cf76d6 174d4cc0 4310a854
K1 K1
cad1ed03 299eedac 2e9a9980 8621502f
K2 K2
95a3da06 533ddb58 5d353301 0c42a0d9
17 17
Example 9: Mlen = 0
M М
<empty string>
T Т
028962f6 1b7bf89e fc6b551f 4667d983
Example 10: Mlen = 128
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
T Т
28a7023f 452e8f82 bd4bf28d 8c37c35c
Example 11: Mlen = 320
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
30c81c46 a35ce411
T Т
aaf3d8f1 de5640c2 32f5b169 b9c911e6
Example 12: Mlen = 512
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
30c81c46 a35ce411 e5fbc119 1a0a52ef
f69f2445 df4f9b17 ad2b417b e66c3710
T Т
e1992190 549f6ed5 696a2c05 6c315410
D.4 Three Key TDEA
For Examples 13-16 below, the block cipher is three key TDEA with the following key:
Key1
8aa83bf8 cbda1062
Key2
0bc1bf19 fbb6cd58
Key3
bc313d4a 371ca8b5
Subkey Generation
CIPH
K K
(0 (0
64 64
) )
c8cc74e9 8a7329a2
K1 K1
9198e9d3 14e6535f
K2 K2
2331d3a6 29cca6a5
Example 13: Mlen = 0
M М
<empty string>
T Т
b7a688e1 22ffaf95
Example 14: Mlen = 64
M М
6bc1bee2 2e409f96
T Т
b7a688e1 22ffaf95
Example 15: Mlen = 160
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
18 18
ae2d8a57
T Т
d32bcebe 43d23d80
Example 16: Mlen = 256
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
T Т
33e6b109 2400eae5
D.5 Two Key TDEA
For Examples 17-20 below, the block cipher is two key TDEA with the following key:
Key1
4cf15134 a2850dd5
Key2
8a3d10ba 80570d38
Key3
4cf15134 a2850dd5
Subkey Generation
CIPH
K K
(0 (0
64 64
) )
c7679b9f 6b8d7d7a
K1 K1
8ecf373e d71afaef
K2 K2
1d9e6e7d ae35f5c5
Example 17: Mlen = 0
M М
<empty string>
T Т
bd2ebf9a 3ba00361
Example 18: Mlen = 64
M М
6bc1bee2 2e409f96
T Т
bd2ebf9a 3ba00361
Example 19: Mlen = 160
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57
T Т
8ea92435 b52660e0
Example 20: Mlen = 256
M М
6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
T Т
31b1e431 dabc4eb8
19 19
Appendix E: Bibliography
[1] [1]
J. Black, P. Rogaway, A Suggestion for Handling Arbitrary-Length Messages with the
CBC MAC, Natl. Inst. Ин-т. Stand. Technol. [Web page] , http://csrc.nist.gov/CryptoToolkit/
modes/workshop1/.
[2] [2]
J. Black, P. Rogaway, CBC MACs for arbitrary-length messages: The three-key
constructions, in Advances in Cryptology—Crypto 2000, Lecture Notes in Computer
Science, Vol. 1880, Mihir Bellare, ed., Springer-Verlag (2000), pp. 197–215.
[3] [3]
FIPS Publication 197, The Advanced Encryption Standard (AES), US DoC/NIST,
November 26, 2001.
[4] [4]
FIPS Publication 198, The Keyed-Hash Message Authentication Code, US DoC/NIST,
March 6, 2002.
[5]
T. Iwata, K. Kurosawa, OMAC: One-Key CBC MAC, Natl. Inst. Ин-т. Stand. Technol. [Web
page] , http://csrc.nist.gov/CryptoToolkit/modes/proposedmodes/.
[6] [6]
T. Iwata, K. Kurosawa, OMAC: One-Key CBC MAC, in Fast Software Encryption, 10
th й
International Workshop, FSE 2003, Lecture Notes in Computer Science, Vol. 2887,
Thomas Johansson, ed., Springer-Verlag (2003), pp 129–153.
[7]
T. Iwata, K. Kurosawa, OMAC: One-Key CBC MAC—Addendum, Natl. Inst. Ин-т. Stand.
Technol. [Web page] , http://csrc.nist.gov/CryptoToolkit/modes/proposedmodes/.
[8]
T. Iwata, K. Kurosawa, Stronger Security Bounds for OMAC, TMAC, and XCBC, Natl.
Inst. Ин-т. Stand. Technol. [Web page] , http://csrc.nist.gov/CryptoToolkit/modes/comments/.
[9]
A. Menezes, P. van Oorschot, S. Vanstone, Handbook of Applied Cryptography, CRC
Press, Inc., Boca Raton (1996).
[10] NIST Special Publication 800-67 Version 1, Recommendation for the Triple Data
Encryption Algorithm (TDEA) Block Cipher, May 2004, Natl. Inst. Ин-т. Stand. Technol.
[Web page] , http://csrc.nist.gov/publications/nistpubs/800-67/SP800-67.pdf.