Internet Engineering Task Force (IETF) D. Eastlake 3rd Request for Comments: 6234 Huawei Obsoletes: 4634 T. Hansen Updates: 3174 AT&T Labs Category: Informational May 2011 ISSN: 2070-1721
US Secure Hash Algorithms (SHA and SHA-based HMAC and HKDF)
Abstract
The United States of America has adopted a suite of Secure Hash Algorithms (SHAs), including four beyond SHA-1, as part of a Federal Information Processing Standard (FIPS), namely SHA-224, SHA-256, SHA-384, and SHA-512. This document makes open source code performing these SHA hash functions conveniently available to the Internet community. The sample code supports input strings of arbitrary bit length. Much of the text herein was adapted by the authors from FIPS 180-2.
This document replaces RFC 4634, fixing errata and adding code for an HMAC-based extract-and-expand Key Derivation Function, HKDF (RFC 5869). As with RFC 4634, code to perform SHA-based Hashed Message Authentication Codes (HMACs) is also included.
Status of This Memo
This document is not an Internet Standards Track specification; it is published for informational purposes.
This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Not all documents approved by the IESG are a candidate for any level of Internet Standard; see Section 2 of RFC 5741.
Information about the current status of this document, any errata, and how to provide feedback on it may be obtained at http://www.rfc-editor.org/info/rfc6234.
Eastlake & Hansen Informational [Page 1]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
Copyright Notice
Copyright (c) 2011 IETF Trust and the persons identified as the document authors. All rights reserved.
This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.
Eastlake & Hansen Informational [Page 2]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
Table of Contents
1. Overview of Contents ............................................4 2. Notation for Bit Strings and Integers ...........................5 3. Operations on Words .............................................6 4. Message Padding and Parsing .....................................8 4.1. SHA-224 and SHA-256 ........................................8 4.2. SHA-384 and SHA-512 ........................................9 5. Functions and Constants Used ...................................10 5.1. SHA-224 and SHA-256 .......................................10 5.2. SHA-384 and SHA-512 .......................................11 6. Computing the Message Digest ...................................12 6.1. SHA-224 and SHA-256 Initialization ........................12 6.2. SHA-224 and SHA-256 Processing ............................13 6.3. SHA-384 and SHA-512 Initialization ........................14 6.4. SHA-384 and SHA-512 Processing ............................15 7. HKDF- and SHA-Based HMACs ......................................17 7.1. SHA-Based HMACs ...........................................17 7.2. HKDF ......................................................17 8. C Code for SHAs, HMAC, and HKDF ................................17 8.1. The Header Files ..........................................21 8.1.1. The .h file ........................................21 8.1.2. stdint-example.h ...................................29 8.1.3. sha-private.h ......................................29 8.2. The SHA Code ..............................................30 8.2.1. sha1.c .............................................30 8.2.2. sha224-256.c .......................................39 8.2.3. sha384-512.c .......................................51 8.2.4. usha.c .............................................73 8.3. The HMAC Code .............................................79 8.4. The HKDF Code .............................................84 8.5. The Test Driver ...........................................91 9. Security Considerations .......................................123 10. Acknowledgements .............................................123 11. References ...................................................124 11.1. Normative References ....................................124 11.2. Informative References ..................................124 Appendix: Changes from RFC 4634...................................126
This document includes specifications for the United States of America (USA) Federal Information Processing Standard (FIPS) Secure Hash Algorithms (SHAs), code to implement the SHAs, code to implement HMAC (Hashed Message Authentication Code, [RFC2104]) based on the SHAs, and code to implement HKDF (HMAC-based Key Derivation Function, [RFC5869]) based on HMAC. Specifications for HMAC and HKDF are not included as they appear elsewhere in the RFC series [RFC2104] [RFC5869].
NOTE: Much of the text below is taken from [SHS], and the assertions of the security of the hash algorithms described therein are made by the US Government, the author of [SHS], not by the listed authors of this document. See also [RFC6194] concerning the security of SHA-1.
The text below specifies Secure Hash Algorithms, SHA-224 [RFC3874], SHA-256, SHA-384, and SHA-512, for computing a condensed representation of a message or a data file. (SHA-1 is specified in [RFC3174].) When a message of any length < 2^64 bits (for SHA-224 and SHA-256) or < 2^128 bits (for SHA-384 and SHA-512) is input to one of these algorithms, the result is an output called a message digest. The message digests range in length from 224 to 512 bits, depending on the algorithm. Secure Hash Algorithms are typically used with other cryptographic algorithms, such as digital signature algorithms and keyed-hash authentication codes, the generation of random numbers [RFC4086], or in key derivation functions.
The algorithms specified in this document are called secure because it is computationally infeasible to (1) find a message that corresponds to a given message digest, or (2) find two different messages that produce the same message digest. Any change to a message in transit will, with very high probability, result in a different message digest. This will result in a verification failure when the Secure Hash Algorithm is used with a digital signature algorithm or a keyed-hash message authentication algorithm.
The code provided herein supports input strings of arbitrary bit length. SHA-1's sample code from [RFC3174] has also been updated to handle input strings of arbitrary bit length. Permission is granted for all uses, commercial and non-commercial, of this code.
This document obsoletes [RFC4634], and the changes from that RFC are summarized in the Appendix.
Eastlake & Hansen Informational [Page 4]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
ASN.1 OIDs (Object Identifiers) for the SHA algorithms, taken from [RFC4055], are as follows:
Section 2 below defines the terminology and functions used as building blocks to form these algorithms. Section 3 describes the fundamental operations on words from which these algorithms are built. Section 4 describes how messages are padded up to an integral multiple of the required block size and then parsed into blocks. Section 5 defines the constants and the composite functions used to specify the hash algorithms. Section 6 gives the actual specification for the SHA-224, SHA-256, SHA-384, and SHA-512 functions. Section 7 provides pointers to the specification of HMAC keyed message authentication codes and to the specification of an extract-and-expand key derivation function based on HMAC.
Section 8 gives sample code for the SHA algorithms, for SHA-based HMACs, and for HMAC-based extract-and-expand key derivation function.
The following terminology related to bit strings and integers will be used:
a. A hex digit is an element of the set {0, 1, ... , 9, A, ... , F}. A hex digit is the representation of a 4-bit string. Examples: 7 = 0111, A = 1010.
b. A word equals a 32-bit or 64-bit string that may be represented as a sequence of 8 or 16 hex digits, respectively. To convert a word to hex digits, each 4-bit string is converted to its hex equivalent as described in (a) above. Example:
Throughout this document, the "big-endian" convention is used when expressing both 32-bit and 64-bit words, so that within each word the most significant bit is shown in the leftmost bit position.
c. An integer may be represented as a word or pair of words.
An integer between 0 and 2^32 - 1 inclusive may be represented as a 32-bit word. The least significant four bits of the integer are represented by the rightmost hex digit of the word representation. Example: the integer 291 = 2^8+2^5+2^1+2^0 = 256+32+2+1 is represented by the hex word 00000123.
The same holds true for an integer between 0 and 2^64-1 inclusive, which may be represented as a 64-bit word.
If Z is an integer, 0 <= z < 2^64, then z = (2^32)x + y where 0 <= x < 2^32 and 0 <= y < 2^32. Since x and y can be represented as words X and Y, respectively, z can be represented as the pair of words (X,Y).
Again, the "big-endian" convention is used and the most significant word is in the leftmost word position for values represented by multiple-words.
d. block = 512-bit or 1024-bit string. A block (e.g., B) may be represented as a sequence of 32-bit or 64-bit words.
The following logical operators will be applied to words in all four hash operations specified herein. SHA-224 and SHA-256 operate on 32-bit words while SHA-384 and SHA-512 operate on 64-bit words.
In the operations below, x<<n is obtained as follows: discard the leftmost n bits of x and then pad the result with n zeroed bits on the right (the result will still be the same number of bits). Similarly, x>>n is obtained as follows: discard the rightmost n bits of x and then prepend the result with n zeroed bits on the left (the result will still be the same number of bits).
a. Bitwise logical word operations
X AND Y = bitwise logical "and" of X and Y.
X OR Y = bitwise logical "inclusive-or" of X and Y.
Eastlake & Hansen Informational [Page 6]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
X XOR Y = bitwise logical "exclusive-or" of X and Y.
b. The operation X + Y is defined as follows: words X and Y represent w-bit integers x and y, where 0 <= x < 2^w and 0 <= y < 2^w. For positive integers n and m, let
n mod m
be the remainder upon dividing n by m. Compute
z = (x + y) mod 2^w.
Then 0 <= z < 2^w. Convert z to a word, Z, and define Z = X + Y.
c. The right shift operation SHR^n(x), where x is a w-bit word and n is an integer with 0 <= n < w, is defined by
SHR^n(x) = x>>n
d. The rotate right (circular right shift) operation ROTR^n(x), where x is a w-bit word and n is an integer with 0 <= n < w, is defined by
ROTR^n(x) = (x>>n) OR (x<<(w-n))
e. The rotate left (circular left shift) operation ROTL^n(x), where x is a w-bit word and n is an integer with 0 <= n < w, is defined by
ROTL^n(X) = (x<<n) OR (x>>(w-n))
Note the following equivalence relationships, where w is fixed in each relationship:
The hash functions specified herein are used to compute a message digest for a message or data file that is provided as input. The message or data file should be considered to be a bit string. The length of the message is the number of bits in the message (the empty message has length 0). If the number of bits in a message is a multiple of 8, for compactness we can represent the message in hex. The purpose of message padding is to make the total length of a padded message a multiple of 512 for SHA-224 and SHA-256 or a multiple of 1024 for SHA-384 and SHA-512.
The following specifies how this padding shall be performed. As a summary, a "1" followed by m "0"s followed by a 64-bit or 128-bit integer are appended to the end of the message to produce a padded message of length 512*n or 1024*n. The appended integer is the length of the original message. The padded message is then processed by the hash function as n 512-bit or 1024-bit blocks.
Suppose a message has length L < 2^64. Before it is input to the hash function, the message is padded on the right as follows:
a. "1" is appended. Example: if the original message is "01010000", this is padded to "010100001".
b. K "0"s are appended where K is the smallest, non-negative solution to the equation
( L + 1 + K ) mod 512 = 448
c. Then append the 64-bit block that is L in binary representation. After appending this block, the length of the message will be a multiple of 512 bits.
Example: Suppose the original message is the bit string
Suppose a message has length L < 2^128. Before it is input to the hash function, the message is padded on the right as follows:
a. "1" is appended. Example: if the original message is "01010000", this is padded to "010100001".
b. K "0"s are appended where K is the smallest, non-negative solution to the equation
( L + 1 + K ) mod 1024 = 896
c. Then append the 128-bit block that is L in binary representation. After appending this block, the length of the message will be a multiple of 1024 bits.
Example: Suppose the original message is the bit string
01100001 01100010 01100011 01100100 01100101
After step (a) this gives
01100001 01100010 01100011 01100100 01100101 1
Eastlake & Hansen Informational [Page 9]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
Since L = 40, the number of bits in the above is 41 and K = 855 "0"s are appended, making the total now 896. This gives the following in hex:
SHA-224 and SHA-256 use six logical functions, where each function operates on 32-bit words, which are represented as x, y, and z. The result of each function is a new 32-bit word.
CH( x, y, z) = (x AND y) XOR ( (NOT x) AND z)
MAJ( x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z)
SHA-224 and SHA-256 use the same sequence of sixty-four constant 32-bit words, K0, K1, ..., K63. These words represent the first 32 bits of the fractional parts of the cube roots of the first sixty- four prime numbers. In hex, these constant words are as follows (from left to right):
SHA-384 and SHA-512 each use six logical functions, where each function operates on 64-bit words, which are represented as x, y, and z. The result of each function is a new 64-bit word.
CH( x, y, z) = (x AND y) XOR ( (NOT x) AND z)
MAJ( x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z)
SHA-384 and SHA-512 use the same sequence of eighty constant 64-bit words, K0, K1, ... K79. These words represent the first 64 bits of the fractional parts of the cube roots of the first eighty prime numbers. In hex, these constant words are as follows (from left to right):
The output of each of the secure hash functions, after being applied to a message of N blocks, is the hash quantity H(N). For SHA-224 and SHA-256, H(i) can be considered to be eight 32-bit words, H(i)0, H(i)1, ... H(i)7. For SHA-384 and SHA-512, it can be considered to be eight 64-bit words, H(i)0, H(i)1, ..., H(i)7.
As described below, the hash words are initialized, modified as each message block is processed, and finally concatenated after processing the last block to yield the output. For SHA-256 and SHA-512, all of the H(N) variables are concatenated while the SHA-224 and SHA-384 hashes are produced by omitting some from the final concatenation.
For SHA-256, the initial hash value, H(0), consists of the following eight 32-bit words, in hex. These words were obtained by taking the first 32 bits of the fractional parts of the square roots of the first eight prime numbers.
SHA-224 and SHA-256 perform identical processing on message blocks and differ only in how H(0) is initialized and how they produce their final output. They may be used to hash a message, M, having a length of L bits, where 0 <= L < 2^64. The algorithm uses (1) a message schedule of sixty-four 32-bit words, (2) eight working variables of 32 bits each, and (3) a hash value of eight 32-bit words.
The words of the message schedule are labeled W0, W1, ..., W63. The eight working variables are labeled a, b, c, d, e, f, g, and h. The words of the hash value are labeled H(i)0, H(i)1, ..., H(i)7, which will hold the initial hash value, H(0), replaced by each successive intermediate hash value (after each message block is processed), H(i), and ending with the final hash value, H(N), after all N blocks are processed. They also use two temporary words, T1 and T2.
The input message is padded as described in Section 4.1 above, then parsed into 512-bit blocks that are considered to be composed of sixteen 32-bit words M(i)0, M(i)1, ..., M(i)15. The following computations are then performed for each of the N message blocks. All addition is performed modulo 2^32.
For i = 1 to N
1. Prepare the message schedule W: For t = 0 to 15 Wt = M(i)t For t = 16 to 63 Wt = SSIG1(W(t-2)) + W(t-7) + SSIG0(w(t-15)) + W(t-16)
Eastlake & Hansen Informational [Page 13]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
2. Initialize the working variables: a = H(i-1)0 b = H(i-1)1 c = H(i-1)2 d = H(i-1)3 e = H(i-1)4 f = H(i-1)5 g = H(i-1)6 h = H(i-1)7
3. Perform the main hash computation: For t = 0 to 63 T1 = h + BSIG1(e) + CH(e,f,g) + Kt + Wt T2 = BSIG0(a) + MAJ(a,b,c) h = g g = f f = e e = d + T1 d = c c = b b = a a = T1 + T2
4. Compute the intermediate hash value H(i) H(i)0 = a + H(i-1)0 H(i)1 = b + H(i-1)1 H(i)2 = c + H(i-1)2 H(i)3 = d + H(i-1)3 H(i)4 = e + H(i-1)4 H(i)5 = f + H(i-1)5 H(i)6 = g + H(i-1)6 H(i)7 = h + H(i-1)7
After the above computations have been sequentially performed for all of the blocks in the message, the final output is calculated. For SHA-256, this is the concatenation of all of H(N)0, H(N)1, through H(N)7. For SHA-224, this is the concatenation of H(N)0, H(N)1, through H(N)6.
For SHA-384, the initial hash value, H(0), consists of the following eight 64-bit words, in hex. These words were obtained by taking the first 64 bits of the fractional parts of the square roots of the ninth through sixteenth prime numbers.
For SHA-512, the initial hash value, H(0), consists of the following eight 64-bit words, in hex. These words were obtained by taking the first 64 bits of the fractional parts of the square roots of the first eight prime numbers.
SHA-384 and SHA-512 perform identical processing on message blocks and differ only in how H(0) is initialized and how they produce their final output. They may be used to hash a message, M, having a length of L bits, where 0 <= L < 2^128. The algorithm uses (1) a message schedule of eighty 64-bit words, (2) eight working variables of 64 bits each, and (3) a hash value of eight 64-bit words.
The words of the message schedule are labeled W0, W1, ..., W79. The eight working variables are labeled a, b, c, d, e, f, g, and h. The words of the hash value are labeled H(i)0, H(i)1, ..., H(i)7, which will hold the initial hash value, H(0), replaced by each successive intermediate hash value (after each message block is processed), H(i), and ending with the final hash value, H(N) after all N blocks are processed.
The input message is padded as described in Section 4.2 above, then parsed into 1024-bit blocks that are considered to be composed of sixteen 64-bit words M(i)0, M(i)1, ..., M(i)15. The following computations are then performed for each of the N message blocks. All addition is performed modulo 2^64.
Eastlake & Hansen Informational [Page 15]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
For i = 1 to N
1. Prepare the message schedule W: For t = 0 to 15 Wt = M(i)t For t = 16 to 79 Wt = SSIG1(W(t-2)) + W(t-7) + SSIG0(W(t-15)) + W(t-16)
2. Initialize the working variables: a = H(i-1)0 b = H(i-1)1 c = H(i-1)2 d = H(i-1)3 e = H(i-1)4 f = H(i-1)5 g = H(i-1)6 h = H(i-1)7
3. Perform the main hash computation: For t = 0 to 79 T1 = h + BSIG1(e) + CH(e,f,g) + Kt + Wt T2 = BSIG0(a) + MAJ(a,b,c) h = g g = f f = e e = d + T1 d = c c = b b = a a = T1 + T2
4. Compute the intermediate hash value H(i) H(i)0 = a + H(i-1)0 H(i)1 = b + H(i-1)1 H(i)2 = c + H(i-1)2 H(i)3 = d + H(i-1)3 H(i)4 = e + H(i-1)4 H(i)5 = f + H(i-1)5 H(i)6 = g + H(i-1)6 H(i)7 = h + H(i-1)7
After the above computations have been sequentially performed for all of the blocks in the message, the final output is calculated. For SHA-512, this is the concatenation of all of H(N)0, H(N)1, through H(N)7. For SHA-384, this is the concatenation of H(N)0, H(N)1, through H(N)5.
Below are brief descriptions and pointers to more complete descriptions and code for (1) SHA-based HMACs and (2) an HMAC-based extract-and-expand key derivation function. Both HKDF and HMAC were devised by Hugo Krawczyk.
HMAC is a method for computing a keyed MAC (Message Authentication Code) using a hash function as described in [RFC2104]. It uses a key to mix in with the input text to produce the final hash.
Sample code is also provided, in Section 8.3 below, to perform HMAC based on any of the SHA algorithms described herein. The sample code found in [RFC2104] was written in terms of a specified text size. Since SHA is defined in terms of an arbitrary number of bits, the sample HMAC code has been written to allow the text input to HMAC to have an arbitrary number of octets and bits. A fixed-length interface is also provided.
HKDF is a specific Key Derivation Function (KDF), that is, a function of initial keying material from which the KDF derives one or more cryptographically strong secret keys. HKDF, which is described in [RFC5869], is based on HMAC.
Sample code for HKDF is provided in Section 8.4 below.
Below is a demonstration implementation of these secure hash functions in C. Section 8.1 contains the header file sha.h that declares all constants, structures, and functions used by the SHA and HMAC functions. It includes conditionals based on the state of definition of USE_32BIT_ONLY that, if that symbol is defined at compile time, avoids 64-bit operations. It also contains sha- private.h that provides some declarations common to all the SHA functions. Section 8.2 contains the C code for sha1.c, sha224-256.c, sha384-512.c, and usha.c. Section 8.3 contains the C code for the HMAC functions, and Section 8.4 contains the C code for HKDF. Section 8.5 contains a test driver to exercise the code.
For each of the digest lengths $$$, there is the following set of constants, a structure, and functions:
Eastlake & Hansen Informational [Page 17]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
Constants: SHA$$$HashSize number of octets in the hash SHA$$$HashSizeBits number of bits in the hash SHA$$$_Message_Block_Size number of octets used in the intermediate message blocks Most functions return an enum value that is one of: shaSuccess(0) on success shaNull(1) when presented with a null pointer parameter shaInputTooLong(2) when the input data is too long shaStateError(3) when SHA$$$Input is called after SHA$$$FinalBits or SHA$$$Result
Structure: typedef SHA$$$Context an opaque structure holding the complete state for producing the hash
Functions: int SHA$$$Reset(SHA$$$Context *context); Reset the hash context state. int SHA$$$Input(SHA$$$Context *context, const uint8_t *octets, unsigned int bytecount); Incorporate bytecount octets into the hash. int SHA$$$FinalBits(SHA$$$Context *, const uint8_t octet, unsigned int bitcount); Incorporate bitcount bits into the hash. The bits are in the upper portion of the octet. SHA$$$Input() cannot be called after this. int SHA$$$Result(SHA$$$Context *, uint8_t Message_Digest[SHA$$$HashSize]); Do the final calculations on the hash and copy the value into Message_Digest.
In addition, functions with the prefix USHA are provided that take a SHAversion value (SHA$$$) to select the SHA function suite. They add the following constants, structure, and functions:
Constants: shaBadParam(4) constant returned by USHA functions when presented with a bad SHAversion (SHA$$$) parameter or other illegal parameter values USAMaxHashSize maximum of the SHA hash sizes SHA$$$ SHAversion enumeration values, used by USHA, HMAC, and HKDF functions to select the SHA function suite
Eastlake & Hansen Informational [Page 18]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
Structure: typedef USHAContext an opaque structure holding the complete state for producing the hash
Functions: int USHAReset(USHAContext *context, SHAversion whichSha); Reset the hash context state. int USHAInput(USHAContext context*, const uint8_t *bytes, unsigned int bytecount); Incorporate bytecount octets into the hash. int USHAFinalBits(USHAContext *context, const uint8_t bits, unsigned int bitcount); Incorporate bitcount bits into the hash. int USHAResult(USHAContext *context, uint8_t Message_Digest[USHAMaxHashSize]); Do the final calculations on the hash and copy the value into Message_Digest. Octets in Message_Digest beyond USHAHashSize(whichSha) are left untouched. int USHAHashSize(enum SHAversion whichSha); The number of octets in the given hash. int USHAHashSizeBits(enum SHAversion whichSha); The number of bits in the given hash. int USHABlockSize(enum SHAversion whichSha); The internal block size for the given hash. const char *USHAHashName(enum SHAversion whichSha); This function will return the name of the given SHA algorithm as a string.
The HMAC functions follow the same pattern to allow any length of text input to be used.
Structure: typedef HMACContext an opaque structure holding the complete state for producing the keyed message digest (MAC)
Functions: int hmacReset(HMACContext *ctx, enum SHAversion whichSha, const unsigned char *key, int key_len); Reset the MAC context state. int hmacInput(HMACContext *ctx, const unsigned char *text, int text_len); Incorporate text_len octets into the MAC. int hmacFinalBits(HMACContext *ctx, const uint8_t bits, unsigned int bitcount); Incorporate bitcount bits into the MAC. int hmacResult(HMACContext *ctx, uint8_t Message_Digest[USHAMaxHashSize]);
Eastlake & Hansen Informational [Page 19]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
Do the final calculations on the MAC and copy the value into Message_Digest. Octets in Message_Digest beyond USHAHashSize(whichSha) are left untouched.
In addition, a combined interface is provided, similar to that shown in [RFC2104], that allows a fixed-length text input to be used.
int hmac(SHAversion whichSha, const unsigned char *text, int text_len, const unsigned char *key, int key_len, uint8_t Message_Digest[USHAMaxHashSize]); Calculate the given digest for the given text and key, and return the resulting MAC. Octets in Message_Digest beyond USHAHashSize(whichSha) are left untouched.
The HKDF functions follow the same pattern to allow any length of text input to be used.
Structure: typedef HKDFContext an opaque structure holding the complete state for producing the keying material Functions: int hkdfReset(HKDFContext *context, enum SHAversion whichSha, const unsigned char *salt, int salt_len) Reset the key derivation state and initialize it with the salt_len octets of the optional salt. int hkdfInput(HKDFContext *context, const unsigned char *ikm, int ikm_len) Incorporate ikm_len octets into the entropy extractor. int hkdfFinalBits(HKDFContext *context, uint8_t ikm_bits, unsigned int ikm_bit_count) Incorporate ikm_bit_count bits into the entropy extractor. int hkdfResult(HKDFContext *context, uint8_t prk[USHAMaxHashSize], const unsigned char *info, int info_len, uint8_t okm[ ], int okm_len) Finish the HKDF extraction and perform the final HKDF expansion, storing the okm_len octets into output keying material (okm). Optionally store the pseudo-random key (prk) that is generated internally.
In addition, combined interfaces are provided, similar to that shown in [RFC5869], that allows a fixed-length text input to be used.
int hkdfExtract(SHAversion whichSha, const unsigned char *salt, int salt_len, const unsigned char *ikm, int ikm_len, uint8_t prk[USHAMaxHashSize])
Eastlake & Hansen Informational [Page 20]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
Perform HKDF extraction, combining the salt_len octets of the optional salt with the ikm_len octets of the input keying material (ikm) to form the pseudo-random key prk. The output prk must be large enough to hold the octets appropriate for the given hash type.
int hkdfExpand(SHAversion whichSha, const uint8_t prk[ ], int prk_len, const unsigned char *info, int info_len, uint8_t okm[ ], int okm_len) Perform HKDF expansion, combining the prk_len octets of the pseudo-random key prk with the info_len octets of info to form the okm_len octets stored in okm.
int hkdf(SHAversion whichSha, const unsigned char *salt, int salt_len, const unsigned char *ikm, int ikm_len, const unsigned char *info, int info_len, uint8_t okm[ ], int okm_len) This combined interface performs both HKDF extraction and expansion. The variables are the same as in hkdfExtract() and hkdfExpand().
The following sha.h file, as stated in the comments within the file, assumes that <stdint.h> is available on your system. If it is not, you should change to including <stdint-example.h>, provided in Section 8.1.2, or the like.
/**************************** sha.h ****************************/ /***************** See RFC 6234 for details. *******************/ /* Copyright (c) 2011 IETF Trust and the persons identified as authors of the code. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Eastlake & Hansen Informational [Page 21]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SHA_H_ #define _SHA_H_
/* * Description: * This file implements the Secure Hash Algorithms * as defined in the U.S. National Institute of Standards * and Technology Federal Information Processing Standards * Publication (FIPS PUB) 180-3 published in October 2008 * and formerly defined in its predecessors, FIPS PUB 180-1 * and FIP PUB 180-2. * * A combined document showing all algorithms is available at * http://csrc.nist.gov/publications/fips/ * fips180-3/fips180-3_final.pdf * * The five hashes are defined in these sizes: * SHA-1 20 byte / 160 bit * SHA-224 28 byte / 224 bit * SHA-256 32 byte / 256 bit * SHA-384 48 byte / 384 bit * SHA-512 64 byte / 512 bit *
Eastlake & Hansen Informational [Page 22]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* Compilation Note: * These files may be compiled with two options: * USE_32BIT_ONLY - use 32-bit arithmetic only, for systems * without 64-bit integers * * USE_MODIFIED_MACROS - use alternate form of the SHA_Ch() * and SHA_Maj() macros that are equivalent * and potentially faster on many systems * */
#include <stdint.h> /* * If you do not have the ISO standard stdint.h header file, then you * must typedef the following: * name meaning * uint64_t unsigned 64-bit integer * uint32_t unsigned 32-bit integer * uint8_t unsigned 8-bit integer (i.e., unsigned char) * int_least16_t integer of >= 16 bits * * See stdint-example.h */
#ifndef _SHA_enum_ #define _SHA_enum_ /* * All SHA functions return one of these values. */ enum { shaSuccess = 0, shaNull, /* Null pointer parameter */ shaInputTooLong, /* input data too long */ shaStateError, /* called Input after FinalBits or Result */ shaBadParam /* passed a bad parameter */ }; #endif /* _SHA_enum_ */
/* * These constants hold size information for each of the SHA * hashing operations */ enum { SHA1_Message_Block_Size = 64, SHA224_Message_Block_Size = 64, SHA256_Message_Block_Size = 64, SHA384_Message_Block_Size = 128, SHA512_Message_Block_Size = 128, USHA_Max_Message_Block_Size = SHA512_Message_Block_Size,
/* * These constants are used in the USHA (Unified SHA) functions. */ typedef enum SHAversion { SHA1, SHA224, SHA256, SHA384, SHA512 } SHAversion;
/* * This structure will hold context information for the SHA-1 * hashing operation. */ typedef struct SHA1Context { uint32_t Intermediate_Hash[SHA1HashSize/4]; /* Message Digest */
uint32_t Length_High; /* Message length in bits */ uint32_t Length_Low; /* Message length in bits */
int Computed; /* Is the hash computed? */ int Corrupted; /* Cumulative corruption code */ } SHA1Context;
/* * This structure will hold context information for the SHA-256 * hashing operation. */ typedef struct SHA256Context { uint32_t Intermediate_Hash[SHA256HashSize/4]; /* Message Digest */
uint32_t Length_High; /* Message length in bits */ uint32_t Length_Low; /* Message length in bits */
int Computed; /* Is the hash computed?*/ int Corrupted; /* Cumulative corruption code */ } SHA512Context;
/* * This structure will hold context information for the SHA-224 * hashing operation. It uses the SHA-256 structure for computation. */ typedef struct SHA256Context SHA224Context;
/* * This structure will hold context information for the SHA-384 * hashing operation. It uses the SHA-512 structure for computation. */ typedef struct SHA512Context SHA384Context;
/* * This structure holds context information for all SHA * hashing operations. */ typedef struct USHAContext { int whichSha; /* which SHA is being used */ union { SHA1Context sha1Context; SHA224Context sha224Context; SHA256Context sha256Context; SHA384Context sha384Context; SHA512Context sha512Context; } ctx;
Eastlake & Hansen Informational [Page 25]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
} USHAContext;
/* * This structure will hold context information for the HMAC * keyed-hashing operation. */ typedef struct HMACContext { int whichSha; /* which SHA is being used */ int hashSize; /* hash size of SHA being used */ int blockSize; /* block size of SHA being used */ USHAContext shaContext; /* SHA context */ unsigned char k_opad[USHA_Max_Message_Block_Size]; /* outer padding - key XORd with opad */ int Computed; /* Is the MAC computed? */ int Corrupted; /* Cumulative corruption code */
} HMACContext;
/* * This structure will hold context information for the HKDF * extract-and-expand Key Derivation Functions. */ typedef struct HKDFContext { int whichSha; /* which SHA is being used */ HMACContext hmacContext; int hashSize; /* hash size of SHA being used */ unsigned char prk[USHAMaxHashSize]; /* pseudo-random key - output of hkdfInput */ int Computed; /* Is the key material computed? */ int Corrupted; /* Cumulative corruption code */ } HKDFContext;
/* * Function Prototypes */
/* SHA-1 */ extern int SHA1Reset(SHA1Context *); extern int SHA1Input(SHA1Context *, const uint8_t *bytes, unsigned int bytecount); extern int SHA1FinalBits(SHA1Context *, uint8_t bits, unsigned int bit_count); extern int SHA1Result(SHA1Context *, uint8_t Message_Digest[SHA1HashSize]);
Eastlake & Hansen Informational [Page 26]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
/* SHA-224 */ extern int SHA224Reset(SHA224Context *); extern int SHA224Input(SHA224Context *, const uint8_t *bytes, unsigned int bytecount); extern int SHA224FinalBits(SHA224Context *, uint8_t bits, unsigned int bit_count); extern int SHA224Result(SHA224Context *, uint8_t Message_Digest[SHA224HashSize]);
/* SHA-256 */ extern int SHA256Reset(SHA256Context *); extern int SHA256Input(SHA256Context *, const uint8_t *bytes, unsigned int bytecount); extern int SHA256FinalBits(SHA256Context *, uint8_t bits, unsigned int bit_count); extern int SHA256Result(SHA256Context *, uint8_t Message_Digest[SHA256HashSize]);
/* SHA-384 */ extern int SHA384Reset(SHA384Context *); extern int SHA384Input(SHA384Context *, const uint8_t *bytes, unsigned int bytecount); extern int SHA384FinalBits(SHA384Context *, uint8_t bits, unsigned int bit_count); extern int SHA384Result(SHA384Context *, uint8_t Message_Digest[SHA384HashSize]);
/* SHA-512 */ extern int SHA512Reset(SHA512Context *); extern int SHA512Input(SHA512Context *, const uint8_t *bytes, unsigned int bytecount); extern int SHA512FinalBits(SHA512Context *, uint8_t bits, unsigned int bit_count); extern int SHA512Result(SHA512Context *, uint8_t Message_Digest[SHA512HashSize]);
/* Unified SHA functions, chosen by whichSha */ extern int USHAReset(USHAContext *context, SHAversion whichSha); extern int USHAInput(USHAContext *context, const uint8_t *bytes, unsigned int bytecount); extern int USHAFinalBits(USHAContext *context, uint8_t bits, unsigned int bit_count); extern int USHAResult(USHAContext *context, uint8_t Message_Digest[USHAMaxHashSize]); extern int USHABlockSize(enum SHAversion whichSha); extern int USHAHashSize(enum SHAversion whichSha); extern int USHAHashSizeBits(enum SHAversion whichSha); extern const char *USHAHashName(enum SHAversion whichSha);
Eastlake & Hansen Informational [Page 27]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
/* * HMAC Keyed-Hashing for Message Authentication, RFC 2104, * for all SHAs. * This interface allows a fixed-length text input to be used. */ extern int hmac(SHAversion whichSha, /* which SHA algorithm to use */ const unsigned char *text, /* pointer to data stream */ int text_len, /* length of data stream */ const unsigned char *key, /* pointer to authentication key */ int key_len, /* length of authentication key */ uint8_t digest[USHAMaxHashSize]); /* caller digest to fill in */
/* * HMAC Keyed-Hashing for Message Authentication, RFC 2104, * for all SHAs. * This interface allows any length of text input to be used. */ extern int hmacReset(HMACContext *context, enum SHAversion whichSha, const unsigned char *key, int key_len); extern int hmacInput(HMACContext *context, const unsigned char *text, int text_len); extern int hmacFinalBits(HMACContext *context, uint8_t bits, unsigned int bit_count); extern int hmacResult(HMACContext *context, uint8_t digest[USHAMaxHashSize]);
/* * HKDF HMAC-based Extract-and-Expand Key Derivation Function, * RFC 5869, for all SHAs. */ extern int hkdf(SHAversion whichSha, const unsigned char *salt, int salt_len, const unsigned char *ikm, int ikm_len, const unsigned char *info, int info_len, uint8_t okm[ ], int okm_len); extern int hkdfExtract(SHAversion whichSha, const unsigned char *salt, int salt_len, const unsigned char *ikm, int ikm_len, uint8_t prk[USHAMaxHashSize]); extern int hkdfExpand(SHAversion whichSha, const uint8_t prk[ ], int prk_len, const unsigned char *info, int info_len, uint8_t okm[ ], int okm_len);
/* * HKDF HMAC-based Extract-and-Expand Key Derivation Function, * RFC 5869, for all SHAs. * This interface allows any length of text input to be used. */ extern int hkdfReset(HKDFContext *context, enum SHAversion whichSha, const unsigned char *salt, int salt_len);
Eastlake & Hansen Informational [Page 28]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
extern int hkdfInput(HKDFContext *context, const unsigned char *ikm, int ikm_len); extern int hkdfFinalBits(HKDFContext *context, uint8_t ikm_bits, unsigned int ikm_bit_count); extern int hkdfResult(HKDFContext *context, uint8_t prk[USHAMaxHashSize], const unsigned char *info, int info_len, uint8_t okm[USHAMaxHashSize], int okm_len); #endif /* _SHA_H_ */
If your system does not have <stdint.h>, the following should be adequate as a substitute for compiling the other code in this document.
/*********************** stdint-example.h **********************/ /**** Use this file if your system does not have a stdint.h. ***/ /***************** See RFC 6234 for details. *******************/ #ifndef STDINT_H #define STDINT_H
typedef unsigned long long uint64_t; /* unsigned 64-bit integer */ typedef unsigned int uint32_t; /* unsigned 32-bit integer */ typedef unsigned char uint8_t; /* unsigned 8-bit integer */ /* (i.e., unsigned char) */ typedef int int_least32_t; /* integer of >= 32 bits */ typedef short int_least16_t; /* integer of >= 16 bits */
The sha-private.h header file contains definitions that should only be needed internally in the other code in this document. These definitions should not be needed in application code calling the code provided in this document.
/************************ sha-private.h ************************/ /***************** See RFC 6234 for details. *******************/ #ifndef _SHA_PRIVATE__H #define _SHA_PRIVATE__H /* * These definitions are defined in FIPS 180-3, section 4.1. * Ch() and Maj() are defined identically in sections 4.1.1, * 4.1.2, and 4.1.3. * * The definitions used in FIPS 180-3 are as follows: */
Eastlake & Hansen Informational [Page 29]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
#ifndef USE_MODIFIED_MACROS #define SHA_Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) #define SHA_Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) #else /* USE_MODIFIED_MACROS */ /* * The following definitions are equivalent and potentially faster. */
This code is primarily intended as expository reference code and could be optimized further. For example, the assignment rotations through the variables a, b, ..., h could be treated as a cycle and the loop unrolled, rather than doing the explicit copying.
Note that there are alternative representations of the Ch() and Maj() functions controlled by an ifdef.
/**************************** sha1.c ***************************/ /***************** See RFC 6234 for details. *******************/ /* Copyright (c) 2011 IETF Trust and the persons identified as */ /* authors of the code. All rights reserved. */ /* See sha.h for terms of use and redistribution. */
/* * Description: * This file implements the Secure Hash Algorithm SHA-1 * as defined in the U.S. National Institute of Standards * and Technology Federal Information Processing Standards * Publication (FIPS PUB) 180-3 published in October 2008 * and formerly defined in its predecessors, FIPS PUB 180-1 * and FIP PUB 180-2. * * A combined document showing all algorithms is available at * http://csrc.nist.gov/publications/fips/ * fips180-3/fips180-3_final.pdf *
Eastlake & Hansen Informational [Page 30]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* The SHA-1 algorithm produces a 160-bit message digest for a * given data stream that can serve as a means of providing a * "fingerprint" for a message. * * Portability Issues: * SHA-1 is defined in terms of 32-bit "words". This code * uses <stdint.h> (included via "sha.h") to define 32- and * 8-bit unsigned integer types. If your C compiler does * not support 32-bit unsigned integers, this code is not * appropriate. * * Caveats: * SHA-1 is designed to work with messages less than 2^64 bits * long. This implementation uses SHA1Input() to hash the bits * that are a multiple of the size of an 8-bit octet, and then * optionally uses SHA1FinalBits() to hash the final few bits of * the input. */
#include "sha.h" #include "sha-private.h"
/* * Define the SHA1 circular left shift macro */ #define SHA1_ROTL(bits,word) \ (((word) << (bits)) | ((word) >> (32-(bits))))
/* * Add "length" to the length. * Set Corrupted when overflow has occurred. */ static uint32_t addTemp; #define SHA1AddLength(context, length) \ (addTemp = (context)->Length_Low, \ (context)->Corrupted = \ (((context)->Length_Low += (length)) < addTemp) && \ (++(context)->Length_High == 0) ? shaInputTooLong \ : (context)->Corrupted )
/* * SHA1Reset * * Description: * This function will initialize the SHA1Context in preparation * for computing a new SHA1 message digest. * * Parameters: * context: [in/out] * The context to reset. * * Returns: * sha Error Code. * */ int SHA1Reset(SHA1Context *context) { if (!context) return shaNull;
/* * SHA1Input * * Description: * This function accepts an array of octets as the next portion * of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_array[ ]: [in] * An array of octets representing the next portion of * the message.
Eastlake & Hansen Informational [Page 32]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* length: [in] * The length of the message in message_array. * * Returns: * sha Error Code. * */ int SHA1Input(SHA1Context *context, const uint8_t *message_array, unsigned length) { if (!context) return shaNull; if (!length) return shaSuccess; if (!message_array) return shaNull; if (context->Computed) return context->Corrupted = shaStateError; if (context->Corrupted) return context->Corrupted;
while (length--) { context->Message_Block[context->Message_Block_Index++] = *message_array;
if ((SHA1AddLength(context, 8) == shaSuccess) && (context->Message_Block_Index == SHA1_Message_Block_Size)) SHA1ProcessMessageBlock(context);
message_array++; }
return context->Corrupted; }
/* * SHA1FinalBits * * Description: * This function will add in any final bits of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_bits: [in] * The final bits of the message, in the upper portion of the * byte. (Use 0b###00000 instead of 0b00000### to input the * three bits ###.) * length: [in] * The number of bits in message_bits, between 1 and 7. * * Returns: * sha Error Code.
/* * SHA1Result * * Description: * This function will return the 160-bit message digest * into the Message_Digest array provided by the caller. * NOTE: * The first octet of hash is stored in the element with index 0, * the last octet of hash in the element with index 19. * * Parameters: * context: [in/out] * The context to use to calculate the SHA-1 hash. * Message_Digest[ ]: [out] * Where the digest is returned. *
Eastlake & Hansen Informational [Page 34]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* Returns: * sha Error Code. * */ int SHA1Result(SHA1Context *context, uint8_t Message_Digest[SHA1HashSize]) { int i;
if (!context) return shaNull; if (!Message_Digest) return shaNull; if (context->Corrupted) return context->Corrupted;
if (!context->Computed) SHA1Finalize(context, 0x80);
for (i = 0; i < SHA1HashSize; ++i) Message_Digest[i] = (uint8_t) (context->Intermediate_Hash[i>>2] >> (8 * ( 3 - ( i & 0x03 ) )));
return shaSuccess; }
/* * SHA1ProcessMessageBlock * * Description: * This helper function will process the next 512 bits of the * message stored in the Message_Block array. * * Parameters: * context: [in/out] * The SHA context to update. * * Returns: * Nothing. * * Comments: * Many of the variable names in this code, especially the * single character names, were used because those were the * names used in the Secure Hash Standard. */ static void SHA1ProcessMessageBlock(SHA1Context *context) { /* Constants defined in FIPS 180-3, section 4.2.1 */ const uint32_t K[4] = { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 };
Eastlake & Hansen Informational [Page 35]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
int t; /* Loop counter */ uint32_t temp; /* Temporary word value */ uint32_t W[80]; /* Word sequence */ uint32_t A, B, C, D, E; /* Word buffers */
/* * Initialize the first 16 words in the array W */ for (t = 0; t < 16; t++) { W[t] = ((uint32_t)context->Message_Block[t * 4]) << 24; W[t] |= ((uint32_t)context->Message_Block[t * 4 + 1]) << 16; W[t] |= ((uint32_t)context->Message_Block[t * 4 + 2]) << 8; W[t] |= ((uint32_t)context->Message_Block[t * 4 + 3]); }
for (t = 16; t < 80; t++) W[t] = SHA1_ROTL(1, W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
A = context->Intermediate_Hash[0]; B = context->Intermediate_Hash[1]; C = context->Intermediate_Hash[2]; D = context->Intermediate_Hash[3]; E = context->Intermediate_Hash[4];
for (t = 0; t < 20; t++) { temp = SHA1_ROTL(5,A) + SHA_Ch(B, C, D) + E + W[t] + K[0]; E = D; D = C; C = SHA1_ROTL(30,B); B = A; A = temp; }
for (t = 20; t < 40; t++) { temp = SHA1_ROTL(5,A) + SHA_Parity(B, C, D) + E + W[t] + K[1]; E = D; D = C; C = SHA1_ROTL(30,B); B = A; A = temp; }
for (t = 40; t < 60; t++) { temp = SHA1_ROTL(5,A) + SHA_Maj(B, C, D) + E + W[t] + K[2]; E = D; D = C; C = SHA1_ROTL(30,B); B = A;
Eastlake & Hansen Informational [Page 36]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
A = temp; }
for (t = 60; t < 80; t++) { temp = SHA1_ROTL(5,A) + SHA_Parity(B, C, D) + E + W[t] + K[3]; E = D; D = C; C = SHA1_ROTL(30,B); B = A; A = temp; }
/* * SHA1Finalize * * Description: * This helper function finishes off the digest calculations. * * Parameters: * context: [in/out] * The SHA context to update. * Pad_Byte: [in] * The last byte to add to the message block before the 0-padding * and length. This will contain the last bits of the message * followed by another single bit. If the message was an * exact multiple of 8-bits long, Pad_Byte will be 0x80. * * Returns: * sha Error Code. * */ static void SHA1Finalize(SHA1Context *context, uint8_t Pad_Byte) { int i; SHA1PadMessage(context, Pad_Byte); /* message may be sensitive, clear it out */ for (i = 0; i < SHA1_Message_Block_Size; ++i) context->Message_Block[i] = 0; context->Length_High = 0; /* and clear length */ context->Length_Low = 0;
Eastlake & Hansen Informational [Page 37]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
context->Computed = 1; }
/* * SHA1PadMessage * * Description: * According to the standard, the message must be padded to the next * even multiple of 512 bits. The first padding bit must be a '1'. * The last 64 bits represent the length of the original message. * All bits in between should be 0. This helper function will pad * the message according to those rules by filling the Message_Block * array accordingly. When it returns, it can be assumed that the * message digest has been computed. * * Parameters: * context: [in/out] * The context to pad. * Pad_Byte: [in] * The last byte to add to the message block before the 0-padding * and length. This will contain the last bits of the message * followed by another single bit. If the message was an * exact multiple of 8-bits long, Pad_Byte will be 0x80. * * Returns: * Nothing. */ static void SHA1PadMessage(SHA1Context *context, uint8_t Pad_Byte) { /* * Check to see if the current message block is too small to hold * the initial padding bits and length. If so, we will pad the * block, process it, and then continue padding into a second * block. */ if (context->Message_Block_Index >= (SHA1_Message_Block_Size - 8)) { context->Message_Block[context->Message_Block_Index++] = Pad_Byte; while (context->Message_Block_Index < SHA1_Message_Block_Size) context->Message_Block[context->Message_Block_Index++] = 0;
/************************* sha224-256.c ************************/ /***************** See RFC 6234 for details. *******************/ /* Copyright (c) 2011 IETF Trust and the persons identified as */ /* authors of the code. All rights reserved. */ /* See sha.h for terms of use and redistribution. */
/* * Description: * This file implements the Secure Hash Algorithms SHA-224 and * SHA-256 as defined in the U.S. National Institute of Standards * and Technology Federal Information Processing Standards * Publication (FIPS PUB) 180-3 published in October 2008 * and formerly defined in its predecessors, FIPS PUB 180-1 * and FIP PUB 180-2. * * A combined document showing all algorithms is available at * http://csrc.nist.gov/publications/fips/ * fips180-3/fips180-3_final.pdf * * The SHA-224 and SHA-256 algorithms produce 224-bit and 256-bit * message digests for a given data stream. It should take about * 2**n steps to find a message with the same digest as a given * message and 2**(n/2) to find any two messages with the same * digest, when n is the digest size in bits. Therefore, this * algorithm can serve as a means of providing a * "fingerprint" for a message. * * Portability Issues: * SHA-224 and SHA-256 are defined in terms of 32-bit "words". * This code uses <stdint.h> (included via "sha.h") to define 32- * and 8-bit unsigned integer types. If your C compiler does not
Eastlake & Hansen Informational [Page 39]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* support 32-bit unsigned integers, this code is not * appropriate. * * Caveats: * SHA-224 and SHA-256 are designed to work with messages less * than 2^64 bits long. This implementation uses SHA224/256Input() * to hash the bits that are a multiple of the size of an 8-bit * octet, and then optionally uses SHA224/256FinalBits() * to hash the final few bits of the input. */
/* * SHA224Reset * * Description: * This function will initialize the SHA224Context in preparation * for computing a new SHA224 message digest. * * Parameters: * context: [in/out] * The context to reset. * * Returns: * sha Error Code. */ int SHA224Reset(SHA224Context *context) { return SHA224_256Reset(context, SHA224_H0); }
/* * SHA224Input * * Description: * This function accepts an array of octets as the next portion * of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_array[ ]: [in] * An array of octets representing the next portion of * the message.
Eastlake & Hansen Informational [Page 41]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* length: [in] * The length of the message in message_array. * * Returns: * sha Error Code. * */ int SHA224Input(SHA224Context *context, const uint8_t *message_array, unsigned int length) { return SHA256Input(context, message_array, length); }
/* * SHA224FinalBits * * Description: * This function will add in any final bits of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_bits: [in] * The final bits of the message, in the upper portion of the * byte. (Use 0b###00000 instead of 0b00000### to input the * three bits ###.) * length: [in] * The number of bits in message_bits, between 1 and 7. * * Returns: * sha Error Code. */ int SHA224FinalBits(SHA224Context *context, uint8_t message_bits, unsigned int length) { return SHA256FinalBits(context, message_bits, length); }
/* * SHA224Result * * Description: * This function will return the 224-bit message digest * into the Message_Digest array provided by the caller. * NOTE: * The first octet of hash is stored in the element with index 0, * the last octet of hash in the element with index 27. *
Eastlake & Hansen Informational [Page 42]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* Parameters: * context: [in/out] * The context to use to calculate the SHA hash. * Message_Digest[ ]: [out] * Where the digest is returned. * * Returns: * sha Error Code. */ int SHA224Result(SHA224Context *context, uint8_t Message_Digest[SHA224HashSize]) { return SHA224_256ResultN(context, Message_Digest, SHA224HashSize); }
/* * SHA256Reset * * Description: * This function will initialize the SHA256Context in preparation * for computing a new SHA256 message digest. * * Parameters: * context: [in/out] * The context to reset. * * Returns: * sha Error Code. */ int SHA256Reset(SHA256Context *context) { return SHA224_256Reset(context, SHA256_H0); }
/* * SHA256Input * * Description: * This function accepts an array of octets as the next portion * of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_array[ ]: [in] * An array of octets representing the next portion of * the message.
Eastlake & Hansen Informational [Page 43]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* length: [in] * The length of the message in message_array. * * Returns: * sha Error Code. */ int SHA256Input(SHA256Context *context, const uint8_t *message_array, unsigned int length) { if (!context) return shaNull; if (!length) return shaSuccess; if (!message_array) return shaNull; if (context->Computed) return context->Corrupted = shaStateError; if (context->Corrupted) return context->Corrupted;
while (length--) { context->Message_Block[context->Message_Block_Index++] = *message_array;
if ((SHA224_256AddLength(context, 8) == shaSuccess) && (context->Message_Block_Index == SHA256_Message_Block_Size)) SHA224_256ProcessMessageBlock(context);
message_array++; }
return context->Corrupted;
}
/* * SHA256FinalBits * * Description: * This function will add in any final bits of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_bits: [in] * The final bits of the message, in the upper portion of the * byte. (Use 0b###00000 instead of 0b00000### to input the * three bits ###.) * length: [in] * The number of bits in message_bits, between 1 and 7. * * Returns: * sha Error Code.
/* * SHA256Result * * Description: * This function will return the 256-bit message digest * into the Message_Digest array provided by the caller. * NOTE: * The first octet of hash is stored in the element with index 0, * the last octet of hash in the element with index 31. * * Parameters: * context: [in/out] * The context to use to calculate the SHA hash. * Message_Digest[ ]: [out] * Where the digest is returned. * * Returns: * sha Error Code.
/* * SHA224_256Reset * * Description: * This helper function will initialize the SHA256Context in * preparation for computing a new SHA-224 or SHA-256 message digest. * * Parameters: * context: [in/out] * The context to reset. * H0[ ]: [in] * The initial hash value array to use. * * Returns: * sha Error Code. */ static int SHA224_256Reset(SHA256Context *context, uint32_t *H0) { if (!context) return shaNull;
* Description: * This helper function will process the next 512 bits of the * message stored in the Message_Block array. * * Parameters: * context: [in/out] * The SHA context to update. * * Returns: * Nothing. * * Comments: * Many of the variable names in this code, especially the * single character names, were used because those were the * names used in the Secure Hash Standard. */ static void SHA224_256ProcessMessageBlock(SHA256Context *context) { /* Constants defined in FIPS 180-3, section 4.2.2 */ static const uint32_t K[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; int t, t4; /* Loop counter */ uint32_t temp1, temp2; /* Temporary word value */ uint32_t W[64]; /* Word sequence */ uint32_t A, B, C, D, E, F, G, H; /* Word buffers */
/* * Initialize the first 16 words in the array W */ for (t = t4 = 0; t < 16; t++, t4 += 4) W[t] = (((uint32_t)context->Message_Block[t4]) << 24) | (((uint32_t)context->Message_Block[t4 + 1]) << 16) | (((uint32_t)context->Message_Block[t4 + 2]) << 8) | (((uint32_t)context->Message_Block[t4 + 3]));
Eastlake & Hansen Informational [Page 47]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
for (t = 16; t < 64; t++) W[t] = SHA256_sigma1(W[t-2]) + W[t-7] + SHA256_sigma0(W[t-15]) + W[t-16];
A = context->Intermediate_Hash[0]; B = context->Intermediate_Hash[1]; C = context->Intermediate_Hash[2]; D = context->Intermediate_Hash[3]; E = context->Intermediate_Hash[4]; F = context->Intermediate_Hash[5]; G = context->Intermediate_Hash[6]; H = context->Intermediate_Hash[7];
for (t = 0; t < 64; t++) { temp1 = H + SHA256_SIGMA1(E) + SHA_Ch(E,F,G) + K[t] + W[t]; temp2 = SHA256_SIGMA0(A) + SHA_Maj(A,B,C); H = G; G = F; F = E; E = D + temp1; D = C; C = B; B = A; A = temp1 + temp2; }
/* * SHA224_256Finalize * * Description: * This helper function finishes off the digest calculations. * * Parameters: * context: [in/out] * The SHA context to update. * Pad_Byte: [in]
Eastlake & Hansen Informational [Page 48]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* The last byte to add to the message block before the 0-padding * and length. This will contain the last bits of the message * followed by another single bit. If the message was an * exact multiple of 8-bits long, Pad_Byte will be 0x80. * * Returns: * sha Error Code. */ static void SHA224_256Finalize(SHA256Context *context, uint8_t Pad_Byte) { int i; SHA224_256PadMessage(context, Pad_Byte); /* message may be sensitive, so clear it out */ for (i = 0; i < SHA256_Message_Block_Size; ++i) context->Message_Block[i] = 0; context->Length_High = 0; /* and clear length */ context->Length_Low = 0; context->Computed = 1; }
/* * SHA224_256PadMessage * * Description: * According to the standard, the message must be padded to the next * even multiple of 512 bits. The first padding bit must be a '1'. * The last 64 bits represent the length of the original message. * All bits in between should be 0. This helper function will pad * the message according to those rules by filling the * Message_Block array accordingly. When it returns, it can be * assumed that the message digest has been computed. * * Parameters: * context: [in/out] * The context to pad. * Pad_Byte: [in] * The last byte to add to the message block before the 0-padding * and length. This will contain the last bits of the message * followed by another single bit. If the message was an * exact multiple of 8-bits long, Pad_Byte will be 0x80. * * Returns: * Nothing. */ static void SHA224_256PadMessage(SHA256Context *context, uint8_t Pad_Byte) {
Eastlake & Hansen Informational [Page 49]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
/* * Check to see if the current message block is too small to hold * the initial padding bits and length. If so, we will pad the * block, process it, and then continue padding into a second * block. */ if (context->Message_Block_Index >= (SHA256_Message_Block_Size-8)) { context->Message_Block[context->Message_Block_Index++] = Pad_Byte; while (context->Message_Block_Index < SHA256_Message_Block_Size) context->Message_Block[context->Message_Block_Index++] = 0; SHA224_256ProcessMessageBlock(context); } else context->Message_Block[context->Message_Block_Index++] = Pad_Byte;
while (context->Message_Block_Index < (SHA256_Message_Block_Size-8)) context->Message_Block[context->Message_Block_Index++] = 0;
/* * Store the message length as the last 8 octets */ context->Message_Block[56] = (uint8_t)(context->Length_High >> 24); context->Message_Block[57] = (uint8_t)(context->Length_High >> 16); context->Message_Block[58] = (uint8_t)(context->Length_High >> 8); context->Message_Block[59] = (uint8_t)(context->Length_High); context->Message_Block[60] = (uint8_t)(context->Length_Low >> 24); context->Message_Block[61] = (uint8_t)(context->Length_Low >> 16); context->Message_Block[62] = (uint8_t)(context->Length_Low >> 8); context->Message_Block[63] = (uint8_t)(context->Length_Low);
SHA224_256ProcessMessageBlock(context); }
/* * SHA224_256ResultN * * Description: * This helper function will return the 224-bit or 256-bit message * digest into the Message_Digest array provided by the caller. * NOTE: * The first octet of hash is stored in the element with index 0, * the last octet of hash in the element with index 27/31. * * Parameters: * context: [in/out] * The context to use to calculate the SHA hash. * Message_Digest[ ]: [out] * Where the digest is returned. * HashSize: [in]
Eastlake & Hansen Informational [Page 50]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* The size of the hash, either 28 or 32. * * Returns: * sha Error Code. */ static int SHA224_256ResultN(SHA256Context *context, uint8_t Message_Digest[ ], int HashSize) { int i;
if (!context) return shaNull; if (!Message_Digest) return shaNull; if (context->Corrupted) return context->Corrupted;
if (!context->Computed) SHA224_256Finalize(context, 0x80);
for (i = 0; i < HashSize; ++i) Message_Digest[i] = (uint8_t) (context->Intermediate_Hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) ));
/************************* sha384-512.c ************************/ /***************** See RFC 6234 for details. *******************/ /* Copyright (c) 2011 IETF Trust and the persons identified as */ /* authors of the code. All rights reserved. */ /* See sha.h for terms of use and redistribution. */
/* * Description: * This file implements the Secure Hash Algorithms SHA-384 and * SHA-512 as defined in the U.S. National Institute of Standards * and Technology Federal Information Processing Standards * Publication (FIPS PUB) 180-3 published in October 2008 * and formerly defined in its predecessors, FIPS PUB 180-1 * and FIP PUB 180-2. * * A combined document showing all algorithms is available at * http://csrc.nist.gov/publications/fips/ * fips180-3/fips180-3_final.pdf * * The SHA-384 and SHA-512 algorithms produce 384-bit and 512-bit * message digests for a given data stream. It should take about * 2**n steps to find a message with the same digest as a given
Eastlake & Hansen Informational [Page 51]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* message and 2**(n/2) to find any two messages with the same * digest, when n is the digest size in bits. Therefore, this * algorithm can serve as a means of providing a * "fingerprint" for a message. * * Portability Issues: * SHA-384 and SHA-512 are defined in terms of 64-bit "words", * but if USE_32BIT_ONLY is #defined, this code is implemented in * terms of 32-bit "words". This code uses <stdint.h> (included * via "sha.h") to define the 64-, 32- and 8-bit unsigned integer * types. If your C compiler does not support 64-bit unsigned * integers and you do not #define USE_32BIT_ONLY, this code is * not appropriate. * * Caveats: * SHA-384 and SHA-512 are designed to work with messages less * than 2^128 bits long. This implementation uses SHA384/512Input() * to hash the bits that are a multiple of the size of an 8-bit * octet, and then optionally uses SHA384/256FinalBits() * to hash the final few bits of the input. * */
#include "sha.h"
#ifdef USE_32BIT_ONLY /* * Define 64-bit arithmetic in terms of 32-bit arithmetic. * Each 64-bit number is represented in a 2-word array. * All macros are defined such that the result is the last parameter. */
/* * SHA384Reset * * Description: * This function will initialize the SHA384Context in preparation * for computing a new SHA384 message digest. * * Parameters: * context: [in/out] * The context to reset. * * Returns: * sha Error Code. * */ int SHA384Reset(SHA384Context *context) { return SHA384_512Reset(context, SHA384_H0); }
/* * SHA384Input * * Description: * This function accepts an array of octets as the next portion * of the message.
Eastlake & Hansen Informational [Page 58]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* * Parameters: * context: [in/out] * The SHA context to update. * message_array[ ]: [in] * An array of octets representing the next portion of * the message. * length: [in] * The length of the message in message_array. * * Returns: * sha Error Code. * */ int SHA384Input(SHA384Context *context, const uint8_t *message_array, unsigned int length) { return SHA512Input(context, message_array, length); }
/* * SHA384FinalBits * * Description: * This function will add in any final bits of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_bits: [in] * The final bits of the message, in the upper portion of the * byte. (Use 0b###00000 instead of 0b00000### to input the * three bits ###.) * length: [in] * The number of bits in message_bits, between 1 and 7. * * Returns: * sha Error Code. * */ int SHA384FinalBits(SHA384Context *context, uint8_t message_bits, unsigned int length) { return SHA512FinalBits(context, message_bits, length); }
/* * SHA384Result
Eastlake & Hansen Informational [Page 59]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* * Description: * This function will return the 384-bit message digest * into the Message_Digest array provided by the caller. * NOTE: * The first octet of hash is stored in the element with index 0, * the last octet of hash in the element with index 47. * * Parameters: * context: [in/out] * The context to use to calculate the SHA hash. * Message_Digest[ ]: [out] * Where the digest is returned. * * Returns: * sha Error Code. * */ int SHA384Result(SHA384Context *context, uint8_t Message_Digest[SHA384HashSize]) { return SHA384_512ResultN(context, Message_Digest, SHA384HashSize); }
/* * SHA512Reset * * Description: * This function will initialize the SHA512Context in preparation * for computing a new SHA512 message digest. * * Parameters: * context: [in/out] * The context to reset. * * Returns: * sha Error Code. * */ int SHA512Reset(SHA512Context *context) { return SHA384_512Reset(context, SHA512_H0); }
/* * SHA512Input * * Description:
Eastlake & Hansen Informational [Page 60]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* This function accepts an array of octets as the next portion * of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_array[ ]: [in] * An array of octets representing the next portion of * the message. * length: [in] * The length of the message in message_array. * * Returns: * sha Error Code. * */ int SHA512Input(SHA512Context *context, const uint8_t *message_array, unsigned int length) { if (!context) return shaNull; if (!length) return shaSuccess; if (!message_array) return shaNull; if (context->Computed) return context->Corrupted = shaStateError; if (context->Corrupted) return context->Corrupted;
while (length--) { context->Message_Block[context->Message_Block_Index++] = *message_array;
if ((SHA384_512AddLength(context, 8) == shaSuccess) && (context->Message_Block_Index == SHA512_Message_Block_Size)) SHA384_512ProcessMessageBlock(context);
message_array++; }
return context->Corrupted; }
/* * SHA512FinalBits * * Description: * This function will add in any final bits of the message. * * Parameters: * context: [in/out]
Eastlake & Hansen Informational [Page 61]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* The SHA context to update. * message_bits: [in] * The final bits of the message, in the upper portion of the * byte. (Use 0b###00000 instead of 0b00000### to input the * three bits ###.) * length: [in] * The number of bits in message_bits, between 1 and 7. * * Returns: * sha Error Code. * */ int SHA512FinalBits(SHA512Context *context, uint8_t message_bits, unsigned int length) { static uint8_t masks[8] = { /* 0 0b00000000 */ 0x00, /* 1 0b10000000 */ 0x80, /* 2 0b11000000 */ 0xC0, /* 3 0b11100000 */ 0xE0, /* 4 0b11110000 */ 0xF0, /* 5 0b11111000 */ 0xF8, /* 6 0b11111100 */ 0xFC, /* 7 0b11111110 */ 0xFE }; static uint8_t markbit[8] = { /* 0 0b10000000 */ 0x80, /* 1 0b01000000 */ 0x40, /* 2 0b00100000 */ 0x20, /* 3 0b00010000 */ 0x10, /* 4 0b00001000 */ 0x08, /* 5 0b00000100 */ 0x04, /* 6 0b00000010 */ 0x02, /* 7 0b00000001 */ 0x01 };
if (!context) return shaNull; if (!length) return shaSuccess; if (context->Corrupted) return context->Corrupted; if (context->Computed) return context->Corrupted = shaStateError; if (length >= 8) return context->Corrupted = shaBadParam;
/* * SHA512Result * * Description: * This function will return the 512-bit message digest * into the Message_Digest array provided by the caller. * NOTE:
Eastlake & Hansen Informational [Page 62]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* The first octet of hash is stored in the element with index 0, * the last octet of hash in the element with index 63. * * Parameters: * context: [in/out] * The context to use to calculate the SHA hash. * Message_Digest[ ]: [out] * Where the digest is returned. * * Returns: * sha Error Code. * */ int SHA512Result(SHA512Context *context, uint8_t Message_Digest[SHA512HashSize]) { return SHA384_512ResultN(context, Message_Digest, SHA512HashSize); }
/* * SHA384_512Reset * * Description: * This helper function will initialize the SHA512Context in * preparation for computing a new SHA384 or SHA512 message * digest. * * Parameters: * context: [in/out] * The context to reset. * H0[ ]: [in] * The initial hash value array to use. * * Returns: * sha Error Code. * */ #ifdef USE_32BIT_ONLY static int SHA384_512Reset(SHA512Context *context, uint32_t H0[SHA512HashSize/4]) #else /* !USE_32BIT_ONLY */ static int SHA384_512Reset(SHA512Context *context, uint64_t H0[SHA512HashSize/8]) #endif /* USE_32BIT_ONLY */ { int i; if (!context) return shaNull;
/* * SHA384_512ProcessMessageBlock * * Description: * This helper function will process the next 1024 bits of the * message stored in the Message_Block array. * * Parameters: * context: [in/out] * The SHA context to update. * * Returns: * Nothing. * * Comments: * Many of the variable names in this code, especially the * single character names, were used because those were the * names used in the Secure Hash Standard. * * */ static void SHA384_512ProcessMessageBlock(SHA512Context *context) { #ifdef USE_32BIT_ONLY /* Constants defined in FIPS 180-3, section 4.2.3 */ static const uint32_t K[80*2] = { 0x428A2F98, 0xD728AE22, 0x71374491, 0x23EF65CD, 0xB5C0FBCF,
0x28DB77F523047D84ll, 0x32CAAB7B40C72493ll, 0x3C9EBE0A15C9BEBCll, 0x431D67C49C100D4Cll, 0x4CC5D4BECB3E42B6ll, 0x597F299CFC657E2All, 0x5FCB6FAB3AD6FAECll, 0x6C44198C4A475817ll }; int t, t8; /* Loop counter */ uint64_t temp1, temp2; /* Temporary word value */ uint64_t W[80]; /* Word sequence */ uint64_t A, B, C, D, E, F, G, H; /* Word buffers */
/* * Initialize the first 16 words in the array W */ for (t = t8 = 0; t < 16; t++, t8 += 8) W[t] = ((uint64_t)(context->Message_Block[t8 ]) << 56) | ((uint64_t)(context->Message_Block[t8 + 1]) << 48) | ((uint64_t)(context->Message_Block[t8 + 2]) << 40) | ((uint64_t)(context->Message_Block[t8 + 3]) << 32) | ((uint64_t)(context->Message_Block[t8 + 4]) << 24) | ((uint64_t)(context->Message_Block[t8 + 5]) << 16) | ((uint64_t)(context->Message_Block[t8 + 6]) << 8) | ((uint64_t)(context->Message_Block[t8 + 7]));
for (t = 16; t < 80; t++) W[t] = SHA512_sigma1(W[t-2]) + W[t-7] + SHA512_sigma0(W[t-15]) + W[t-16]; A = context->Intermediate_Hash[0]; B = context->Intermediate_Hash[1]; C = context->Intermediate_Hash[2]; D = context->Intermediate_Hash[3]; E = context->Intermediate_Hash[4]; F = context->Intermediate_Hash[5]; G = context->Intermediate_Hash[6]; H = context->Intermediate_Hash[7];
for (t = 0; t < 80; t++) { temp1 = H + SHA512_SIGMA1(E) + SHA_Ch(E,F,G) + K[t] + W[t]; temp2 = SHA512_SIGMA0(A) + SHA_Maj(A,B,C); H = G; G = F; F = E; E = D + temp1; D = C; C = B; B = A; A = temp1 + temp2; }
/* * SHA384_512Finalize * * Description: * This helper function finishes off the digest calculations. * * Parameters: * context: [in/out] * The SHA context to update. * Pad_Byte: [in] * The last byte to add to the message block before the 0-padding * and length. This will contain the last bits of the message * followed by another single bit. If the message was an * exact multiple of 8-bits long, Pad_Byte will be 0x80. * * Returns: * sha Error Code. * */ static void SHA384_512Finalize(SHA512Context *context, uint8_t Pad_Byte) { int_least16_t i; SHA384_512PadMessage(context, Pad_Byte); /* message may be sensitive, clear it out */ for (i = 0; i < SHA512_Message_Block_Size; ++i) context->Message_Block[i] = 0; #ifdef USE_32BIT_ONLY /* and clear length */ context->Length[0] = context->Length[1] = 0; context->Length[2] = context->Length[3] = 0; #else /* !USE_32BIT_ONLY */ context->Length_High = context->Length_Low = 0; #endif /* USE_32BIT_ONLY */ context->Computed = 1; }
Eastlake & Hansen Informational [Page 69]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
/* * SHA384_512PadMessage * * Description: * According to the standard, the message must be padded to the next * even multiple of 1024 bits. The first padding bit must be a '1'. * The last 128 bits represent the length of the original message. * All bits in between should be 0. This helper function will * pad the message according to those rules by filling the * Message_Block array accordingly. When it returns, it can be * assumed that the message digest has been computed. * * Parameters: * context: [in/out] * The context to pad. * Pad_Byte: [in] * The last byte to add to the message block before the 0-padding * and length. This will contain the last bits of the message * followed by another single bit. If the message was an * exact multiple of 8-bits long, Pad_Byte will be 0x80. * * Returns: * Nothing. * */ static void SHA384_512PadMessage(SHA512Context *context, uint8_t Pad_Byte) { /* * Check to see if the current message block is too small to hold * the initial padding bits and length. If so, we will pad the * block, process it, and then continue padding into a second * block. */ if (context->Message_Block_Index >= (SHA512_Message_Block_Size-16)) { context->Message_Block[context->Message_Block_Index++] = Pad_Byte; while (context->Message_Block_Index < SHA512_Message_Block_Size) context->Message_Block[context->Message_Block_Index++] = 0;
/* * SHA384_512ResultN * * Description: * This helper function will return the 384-bit or 512-bit message * digest into the Message_Digest array provided by the caller.
Eastlake & Hansen Informational [Page 71]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* NOTE: * The first octet of hash is stored in the element with index 0, * the last octet of hash in the element with index 47/63. * * Parameters: * context: [in/out] * The context to use to calculate the SHA hash. * Message_Digest[ ]: [out] * Where the digest is returned. * HashSize: [in] * The size of the hash, either 48 or 64. * * Returns: * sha Error Code. * */ static int SHA384_512ResultN(SHA512Context *context, uint8_t Message_Digest[ ], int HashSize) { int i; #ifdef USE_32BIT_ONLY int i2; #endif /* USE_32BIT_ONLY */
if (!context) return shaNull; if (!Message_Digest) return shaNull; if (context->Corrupted) return context->Corrupted;
if (!context->Computed) SHA384_512Finalize(context, 0x80);
#ifdef USE_32BIT_ONLY for (i = i2 = 0; i < HashSize; ) { Message_Digest[i++]=(uint8_t)(context->Intermediate_Hash[i2]>>24); Message_Digest[i++]=(uint8_t)(context->Intermediate_Hash[i2]>>16); Message_Digest[i++]=(uint8_t)(context->Intermediate_Hash[i2]>>8); Message_Digest[i++]=(uint8_t)(context->Intermediate_Hash[i2++]); Message_Digest[i++]=(uint8_t)(context->Intermediate_Hash[i2]>>24); Message_Digest[i++]=(uint8_t)(context->Intermediate_Hash[i2]>>16); Message_Digest[i++]=(uint8_t)(context->Intermediate_Hash[i2]>>8); Message_Digest[i++]=(uint8_t)(context->Intermediate_Hash[i2++]); } #else /* !USE_32BIT_ONLY */ for (i = 0; i < HashSize; ++i) Message_Digest[i] = (uint8_t) (context->Intermediate_Hash[i>>3] >> 8 * ( 7 - ( i % 8 ) )); #endif /* USE_32BIT_ONLY */
/**************************** usha.c ***************************/ /***************** See RFC 6234 for details. *******************/ /* Copyright (c) 2011 IETF Trust and the persons identified as */ /* authors of the code. All rights reserved. */ /* See sha.h for terms of use and redistribution. */
/* * Description: * This file implements a unified interface to the SHA algorithms. */
#include "sha.h"
/* * USHAReset * * Description: * This function will initialize the SHA Context in preparation * for computing a new SHA message digest. * * Parameters: * context: [in/out] * The context to reset. * whichSha: [in] * Selects which SHA reset to call * * Returns: * sha Error Code. * */ int USHAReset(USHAContext *context, enum SHAversion whichSha) { if (!context) return shaNull; context->whichSha = whichSha; switch (whichSha) { case SHA1: return SHA1Reset((SHA1Context*)&context->ctx); case SHA224: return SHA224Reset((SHA224Context*)&context->ctx); case SHA256: return SHA256Reset((SHA256Context*)&context->ctx); case SHA384: return SHA384Reset((SHA384Context*)&context->ctx); case SHA512: return SHA512Reset((SHA512Context*)&context->ctx); default: return shaBadParam; } }
Eastlake & Hansen Informational [Page 73]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
/* * USHAInput * * Description: * This function accepts an array of octets as the next portion * of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_array: [in] * An array of octets representing the next portion of * the message. * length: [in] * The length of the message in message_array. * * Returns: * sha Error Code. * */ int USHAInput(USHAContext *context, const uint8_t *bytes, unsigned int bytecount) { if (!context) return shaNull; switch (context->whichSha) { case SHA1: return SHA1Input((SHA1Context*)&context->ctx, bytes, bytecount); case SHA224: return SHA224Input((SHA224Context*)&context->ctx, bytes, bytecount); case SHA256: return SHA256Input((SHA256Context*)&context->ctx, bytes, bytecount); case SHA384: return SHA384Input((SHA384Context*)&context->ctx, bytes, bytecount); case SHA512: return SHA512Input((SHA512Context*)&context->ctx, bytes, bytecount); default: return shaBadParam; } }
Eastlake & Hansen Informational [Page 74]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
/* * USHAFinalBits * * Description: * This function will add in any final bits of the message. * * Parameters: * context: [in/out] * The SHA context to update. * message_bits: [in] * The final bits of the message, in the upper portion of the * byte. (Use 0b###00000 instead of 0b00000### to input the * three bits ###.) * length: [in] * The number of bits in message_bits, between 1 and 7. * * Returns: * sha Error Code. */ int USHAFinalBits(USHAContext *context, uint8_t bits, unsigned int bit_count) { if (!context) return shaNull; switch (context->whichSha) { case SHA1: return SHA1FinalBits((SHA1Context*)&context->ctx, bits, bit_count); case SHA224: return SHA224FinalBits((SHA224Context*)&context->ctx, bits, bit_count); case SHA256: return SHA256FinalBits((SHA256Context*)&context->ctx, bits, bit_count); case SHA384: return SHA384FinalBits((SHA384Context*)&context->ctx, bits, bit_count); case SHA512: return SHA512FinalBits((SHA512Context*)&context->ctx, bits, bit_count); default: return shaBadParam; } }
Eastlake & Hansen Informational [Page 75]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
/* * USHAResult * * Description: * This function will return the message digest of the appropriate * bit size, as returned by USHAHashSizeBits(whichSHA) for the * 'whichSHA' value used in the preceeding call to USHAReset, * into the Message_Digest array provided by the caller. * * Parameters: * context: [in/out] * The context to use to calculate the SHA-1 hash. * Message_Digest: [out] * Where the digest is returned. * * Returns: * sha Error Code. * */ int USHAResult(USHAContext *context, uint8_t Message_Digest[USHAMaxHashSize]) { if (!context) return shaNull; switch (context->whichSha) { case SHA1: return SHA1Result((SHA1Context*)&context->ctx, Message_Digest); case SHA224: return SHA224Result((SHA224Context*)&context->ctx, Message_Digest); case SHA256: return SHA256Result((SHA256Context*)&context->ctx, Message_Digest); case SHA384: return SHA384Result((SHA384Context*)&context->ctx, Message_Digest); case SHA512: return SHA512Result((SHA512Context*)&context->ctx, Message_Digest); default: return shaBadParam; } }
/* * USHABlockSize * * Description: * This function will return the blocksize for the given SHA * algorithm.
Eastlake & Hansen Informational [Page 76]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* * Parameters: * whichSha: * which SHA algorithm to query * * Returns: * block size * */ int USHABlockSize(enum SHAversion whichSha) { switch (whichSha) { case SHA1: return SHA1_Message_Block_Size; case SHA224: return SHA224_Message_Block_Size; case SHA256: return SHA256_Message_Block_Size; case SHA384: return SHA384_Message_Block_Size; default: case SHA512: return SHA512_Message_Block_Size; } }
/* * USHAHashSize * * Description: * This function will return the hashsize for the given SHA * algorithm. * * Parameters: * whichSha: * which SHA algorithm to query * * Returns: * hash size * */ int USHAHashSize(enum SHAversion whichSha) { switch (whichSha) { case SHA1: return SHA1HashSize; case SHA224: return SHA224HashSize; case SHA256: return SHA256HashSize; case SHA384: return SHA384HashSize; default: case SHA512: return SHA512HashSize; } }
Eastlake & Hansen Informational [Page 77]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
/* * USHAHashSizeBits * * Description: * This function will return the hashsize for the given SHA * algorithm, expressed in bits. * * Parameters: * whichSha: * which SHA algorithm to query * * Returns: * hash size in bits * */ int USHAHashSizeBits(enum SHAversion whichSha) { switch (whichSha) { case SHA1: return SHA1HashSizeBits; case SHA224: return SHA224HashSizeBits; case SHA256: return SHA256HashSizeBits; case SHA384: return SHA384HashSizeBits; default: case SHA512: return SHA512HashSizeBits; } }
/* * USHAHashName * * Description: * This function will return the name of the given SHA algorithm * as a string. * * Parameters: * whichSha: * which SHA algorithm to query * * Returns: * character string with the name in it * */ const char *USHAHashName(enum SHAversion whichSha) { switch (whichSha) { case SHA1: return "SHA1"; case SHA224: return "SHA224"; case SHA256: return "SHA256";
Eastlake & Hansen Informational [Page 78]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
case SHA384: return "SHA384"; default: case SHA512: return "SHA512"; } }
/**************************** hmac.c ***************************/ /***************** See RFC 6234 for details. *******************/ /* Copyright (c) 2011 IETF Trust and the persons identified as */ /* authors of the code. All rights reserved. */ /* See sha.h for terms of use and redistribution. */
/* * Description: * This file implements the HMAC algorithm (Keyed-Hashing for * Message Authentication, [RFC 2104]), expressed in terms of * the various SHA algorithms. */
#include "sha.h"
/* * hmac * * Description: * This function will compute an HMAC message digest. * * Parameters: * whichSha: [in] * One of SHA1, SHA224, SHA256, SHA384, SHA512 * message_array[ ]: [in] * An array of octets representing the message. * Note: in RFC 2104, this parameter is known * as 'text'. * length: [in] * The length of the message in message_array. * key[ ]: [in] * The secret shared key. * key_len: [in] * The length of the secret shared key. * digest[ ]: [out] * Where the digest is to be returned. * NOTE: The length of the digest is determined by * the value of whichSha. *
/* * hmacReset * * Description: * This function will initialize the hmacContext in preparation * for computing a new HMAC message digest. * * Parameters: * context: [in/out] * The context to reset. * whichSha: [in] * One of SHA1, SHA224, SHA256, SHA384, SHA512 * key[ ]: [in] * The secret shared key. * key_len: [in] * The length of the secret shared key. * * Returns: * sha Error Code. * */ int hmacReset(HMACContext *context, enum SHAversion whichSha, const unsigned char *key, int key_len) { int i, blocksize, hashsize, ret;
/* * If key is longer than the hash blocksize, * reset it to key = HASH(key). */ if (key_len > blocksize) { USHAContext tcontext; int err = USHAReset(&tcontext, whichSha) || USHAInput(&tcontext, key, key_len) || USHAResult(&tcontext, tempkey); if (err != shaSuccess) return err;
key = tempkey; key_len = hashsize; }
/* * The HMAC transform looks like: * * SHA(K XOR opad, SHA(K XOR ipad, text)) * * where K is an n byte key, 0-padded to a total of blocksize bytes, * ipad is the byte 0x36 repeated blocksize times, * opad is the byte 0x5c repeated blocksize times, * and text is the data being protected. */
/* store key into the pads, XOR'd with ipad and opad values */ for (i = 0; i < key_len; i++) { k_ipad[i] = key[i] ^ 0x36; context->k_opad[i] = key[i] ^ 0x5c; } /* remaining pad bytes are '\0' XOR'd with ipad and opad values */ for ( ; i < blocksize; i++) { k_ipad[i] = 0x36; context->k_opad[i] = 0x5c; }
/* perform inner hash */ /* init context for 1st pass */ ret = USHAReset(&context->shaContext, whichSha) ||
Eastlake & Hansen Informational [Page 81]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
/* and start with inner pad */ USHAInput(&context->shaContext, k_ipad, blocksize); return context->Corrupted = ret; }
/* * hmacInput * * Description: * This function accepts an array of octets as the next portion * of the message. It may be called multiple times. * * Parameters: * context: [in/out] * The HMAC context to update. * text[ ]: [in] * An array of octets representing the next portion of * the message. * text_len: [in] * The length of the message in text. * * Returns: * sha Error Code. * */ int hmacInput(HMACContext *context, const unsigned char *text, int text_len) { if (!context) return shaNull; if (context->Corrupted) return context->Corrupted; if (context->Computed) return context->Corrupted = shaStateError; /* then text of datagram */ return context->Corrupted = USHAInput(&context->shaContext, text, text_len); }
/* * hmacFinalBits * * Description: * This function will add in any final bits of the message. * * Parameters: * context: [in/out] * The HMAC context to update. * message_bits: [in] * The final bits of the message, in the upper portion of the * byte. (Use 0b###00000 instead of 0b00000### to input the
Eastlake & Hansen Informational [Page 82]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* three bits ###.) * length: [in] * The number of bits in message_bits, between 1 and 7. * * Returns: * sha Error Code. */ int hmacFinalBits(HMACContext *context, uint8_t bits, unsigned int bit_count) { if (!context) return shaNull; if (context->Corrupted) return context->Corrupted; if (context->Computed) return context->Corrupted = shaStateError; /* then final bits of datagram */ return context->Corrupted = USHAFinalBits(&context->shaContext, bits, bit_count); }
/* * hmacResult * * Description: * This function will return the N-byte message digest into the * Message_Digest array provided by the caller. * * Parameters: * context: [in/out] * The context to use to calculate the HMAC hash. * digest[ ]: [out] * Where the digest is returned. * NOTE 2: The length of the hash is determined by the value of * whichSha that was passed to hmacReset(). * * Returns: * sha Error Code. * */ int hmacResult(HMACContext *context, uint8_t *digest) { int ret; if (!context) return shaNull; if (context->Corrupted) return context->Corrupted; if (context->Computed) return context->Corrupted = shaStateError;
/* finish up 1st pass */ /* (Use digest here as a temporary buffer.) */ ret = USHAResult(&context->shaContext, digest) ||
/**************************** hkdf.c ***************************/ /***************** See RFC 6234 for details. *******************/ /* Copyright (c) 2011 IETF Trust and the persons identified as */ /* authors of the code. All rights reserved. */ /* See sha.h for terms of use and redistribution. */
/* * Description: * This file implements the HKDF algorithm (HMAC-based * Extract-and-Expand Key Derivation Function, RFC 5869), * expressed in terms of the various SHA algorithms. */
/* * hkdf * * Description: * This function will generate keying material using HKDF. * * Parameters: * whichSha: [in] * One of SHA1, SHA224, SHA256, SHA384, SHA512 * salt[ ]: [in] * The optional salt value (a non-secret random value); * if not provided (salt == NULL), it is set internally
Eastlake & Hansen Informational [Page 84]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* to a string of HashLen(whichSha) zeros. * salt_len: [in] * The length of the salt value. (Ignored if salt == NULL.) * ikm[ ]: [in] * Input keying material. * ikm_len: [in] * The length of the input keying material. * info[ ]: [in] * The optional context and application specific information. * If info == NULL or a zero-length string, it is ignored. * info_len: [in] * The length of the optional context and application specific * information. (Ignored if info == NULL.) * okm[ ]: [out] * Where the HKDF is to be stored. * okm_len: [in] * The length of the buffer to hold okm. * okm_len must be <= 255 * USHABlockSize(whichSha) * * Notes: * Calls hkdfExtract() and hkdfExpand(). * * Returns: * sha Error Code. * */ int hkdf(SHAversion whichSha, const unsigned char *salt, int salt_len, const unsigned char *ikm, int ikm_len, const unsigned char *info, int info_len, uint8_t okm[ ], int okm_len) { uint8_t prk[USHAMaxHashSize]; return hkdfExtract(whichSha, salt, salt_len, ikm, ikm_len, prk) || hkdfExpand(whichSha, prk, USHAHashSize(whichSha), info, info_len, okm, okm_len); }
/* * hkdfExtract * * Description: * This function will perform HKDF extraction. * * Parameters: * whichSha: [in] * One of SHA1, SHA224, SHA256, SHA384, SHA512 * salt[ ]: [in]
Eastlake & Hansen Informational [Page 85]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* The optional salt value (a non-secret random value); * if not provided (salt == NULL), it is set internally * to a string of HashLen(whichSha) zeros. * salt_len: [in] * The length of the salt value. (Ignored if salt == NULL.) * ikm[ ]: [in] * Input keying material. * ikm_len: [in] * The length of the input keying material. * prk[ ]: [out] * Array where the HKDF extraction is to be stored. * Must be larger than USHAHashSize(whichSha); * * Returns: * sha Error Code. * */ int hkdfExtract(SHAversion whichSha, const unsigned char *salt, int salt_len, const unsigned char *ikm, int ikm_len, uint8_t prk[USHAMaxHashSize]) { unsigned char nullSalt[USHAMaxHashSize]; if (salt == 0) { salt = nullSalt; salt_len = USHAHashSize(whichSha); memset(nullSalt, '\0', salt_len); } else if (salt_len < 0) { return shaBadParam; } return hmac(whichSha, ikm, ikm_len, salt, salt_len, prk); }
/* * hkdfExpand * * Description: * This function will perform HKDF expansion. * * Parameters: * whichSha: [in] * One of SHA1, SHA224, SHA256, SHA384, SHA512 * prk[ ]: [in] * The pseudo-random key to be expanded; either obtained * directly from a cryptographically strong, uniformly * distributed pseudo-random number generator, or as the * output from hkdfExtract(). * prk_len: [in]
Eastlake & Hansen Informational [Page 86]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* The length of the pseudo-random key in prk; * should at least be equal to USHAHashSize(whichSHA). * info[ ]: [in] * The optional context and application specific information. * If info == NULL or a zero-length string, it is ignored. * info_len: [in] * The length of the optional context and application specific * information. (Ignored if info == NULL.) * okm[ ]: [out] * Where the HKDF is to be stored. * okm_len: [in] * The length of the buffer to hold okm. * okm_len must be <= 255 * USHABlockSize(whichSha) * * Returns: * sha Error Code. * */ int hkdfExpand(SHAversion whichSha, const uint8_t prk[ ], int prk_len, const unsigned char *info, int info_len, uint8_t okm[ ], int okm_len) { int hash_len, N; unsigned char T[USHAMaxHashSize]; int Tlen, where, i;
if (info == 0) { info = (const unsigned char *)""; info_len = 0; } else if (info_len < 0) { return shaBadParam; } if (okm_len <= 0) return shaBadParam; if (!okm) return shaBadParam;
hash_len = USHAHashSize(whichSha); if (prk_len < hash_len) return shaBadParam; N = okm_len / hash_len; if ((okm_len % hash_len) != 0) N++; if (N > 255) return shaBadParam;
Tlen = 0; where = 0; for (i = 1; i <= N; i++) { HMACContext context; unsigned char c = i; int ret = hmacReset(&context, whichSha, prk, prk_len) || hmacInput(&context, T, Tlen) ||
/* * hkdfReset * * Description: * This function will initialize the hkdfContext in preparation * for key derivation using the modular HKDF interface for * arbitrary length inputs. * * Parameters: * context: [in/out] * The context to reset. * whichSha: [in] * One of SHA1, SHA224, SHA256, SHA384, SHA512 * salt[ ]: [in] * The optional salt value (a non-secret random value); * if not provided (salt == NULL), it is set internally * to a string of HashLen(whichSha) zeros. * salt_len: [in] * The length of the salt value. (Ignored if salt == NULL.) * * Returns: * sha Error Code. * */ int hkdfReset(HKDFContext *context, enum SHAversion whichSha, const unsigned char *salt, int salt_len) { unsigned char nullSalt[USHAMaxHashSize]; if (!context) return shaNull;
context->whichSha = whichSha; context->hashSize = USHAHashSize(whichSha); if (salt == 0) { salt = nullSalt; salt_len = context->hashSize; memset(nullSalt, '\0', salt_len);
/* * hkdfInput * * Description: * This function accepts an array of octets as the next portion * of the input keying material. It may be called multiple times. * * Parameters: * context: [in/out] * The HKDF context to update. * ikm[ ]: [in] * An array of octets representing the next portion of * the input keying material. * ikm_len: [in] * The length of ikm. * * Returns: * sha Error Code. * */ int hkdfInput(HKDFContext *context, const unsigned char *ikm, int ikm_len) { if (!context) return shaNull; if (context->Corrupted) return context->Corrupted; if (context->Computed) return context->Corrupted = shaStateError; return hmacInput(&context->hmacContext, ikm, ikm_len); }
/* * hkdfFinalBits * * Description: * This function will add in any final bits of the * input keying material. * * Parameters: * context: [in/out] * The HKDF context to update * ikm_bits: [in] * The final bits of the input keying material, in the upper * portion of the byte. (Use 0b###00000 instead of 0b00000### * to input the three bits ###.)
Eastlake & Hansen Informational [Page 89]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* ikm_bit_count: [in] * The number of bits in message_bits, between 1 and 7. * * Returns: * sha Error Code. */ int hkdfFinalBits(HKDFContext *context, uint8_t ikm_bits, unsigned int ikm_bit_count) { if (!context) return shaNull; if (context->Corrupted) return context->Corrupted; if (context->Computed) return context->Corrupted = shaStateError; return hmacFinalBits(&context->hmacContext, ikm_bits, ikm_bit_count); }
/* * hkdfResult * * Description: * This function will finish the HKDF extraction and perform the * final HKDF expansion. * * Parameters: * context: [in/out] * The HKDF context to use to calculate the HKDF hash. * prk[ ]: [out] * An optional location to store the HKDF extraction. * Either NULL, or pointer to a buffer that must be * larger than USHAHashSize(whichSha); * info[ ]: [in] * The optional context and application specific information. * If info == NULL or a zero-length string, it is ignored. * info_len: [in] * The length of the optional context and application specific * information. (Ignored if info == NULL.) * okm[ ]: [out] * Where the HKDF is to be stored. * okm_len: [in] * The length of the buffer to hold okm. * okm_len must be <= 255 * USHABlockSize(whichSha) * * Returns: * sha Error Code. * */ int hkdfResult(HKDFContext *context, uint8_t prk[USHAMaxHashSize], const unsigned char *info, int info_len,
Eastlake & Hansen Informational [Page 90]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
uint8_t okm[ ], int okm_len) { uint8_t prkbuf[USHAMaxHashSize]; int ret;
if (!context) return shaNull; if (context->Corrupted) return context->Corrupted; if (context->Computed) return context->Corrupted = shaStateError; if (!okm) return context->Corrupted = shaBadParam; if (!prk) prk = prkbuf;
The following code is a main program test driver to exercise the code in sha1.c, sha224-256.c, sha384-512.c, hmac.c, and hkdf.c. The test driver can also be used as a standalone program for generating the hashes. Note that the tests assume that character values are as in [US-ASCII] and a run time check warns if the code appears to have been compiled with some other character system.
See also [SHAVS].
/************************** shatest.c **************************/ /***************** See RFC 6234 for details. *******************/ /* Copyright (c) 2011 IETF Trust and the persons identified as */ /* authors of the code. All rights reserved. */ /* See sha.h for terms of use and redistribution. */
/* * Description: * This file will exercise the SHA code performing * the three tests documented in FIPS PUB 180-3 * (http://csrc.nist.gov/publications/fips/ * fips180-2/fips180-2withchangenotice.pdf) * one that calls SHAInput with an exact multiple of 512 bits * the seven tests documented for each algorithm in * "The Secure Hash Algorithm Validation System (SHAVS)" * (http://csrc.nist.gov/cryptval/shs/SHAVS.pdf), * three of which are bit-level tests *
Eastlake & Hansen Informational [Page 91]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
* These tests have subsequently been moved to pages linked from * http://csrc.nist.gov/groups/ST/toolkit/examples.html * * This file will exercise the HMAC SHA1 code performing * the seven tests documented in RFCs [RFC 2202] and [RFC 4231]. * * This file will exercise the HKDF code performing * the seven tests documented in RFC 4869. * * To run the tests and just see PASSED/FAILED, use the -p option. * * Other options exercise: * hashing an arbitrary string * hashing a file's contents * a few error test checks * printing the results in raw format * * Portability Issues: * None. * */
/* * Check the hash value against the expected string, expressed in hex */ static const char hexdigits[ ] = "0123456789ABCDEF"; int checkmatch(const unsigned char *hashvalue, const char *hexstr, int hashsize) { int i; for (i = 0; i < hashsize; ++i) { if (*hexstr++ != hexdigits[(hashvalue[i] >> 4) & 0xF]) return 0; if (*hexstr++ != hexdigits[hashvalue[i] & 0xF]) return 0; } return 1; }
/* * Print the string, converting non-printable characters to "." */ void printstr(const char *str, int len) { for ( ; len-- > 0; str++) putchar(isprint((unsigned char)*str) ? *str : '.'); }
/* * Print the string, converting all characters to hex "## ". */ void printxstr(const char *str, int len) { char *sep = ""; for ( ; len-- > 0; str++) { printf("%s%c%c", sep, hexdigits[(*str >> 4) & 0xF],
Eastlake & Hansen Informational [Page 107]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
hexdigits[*str & 0xF]); sep = " "; } }
/* * Print a usage message. */ void usage(const char *argv0) { fprintf(stderr, "Usage:\n" "Common options: [-h hash] [-w|-x|-6] [-H]\n" "Hash a string:\n" "\t%s [-S expectedresult] -s hashstr [-k key] " "[-i info -L okm-len]\n" "Hash a file:\n" "\t%s [-S expectedresult] -f file [-k key] " "[-i info -L okm-len]\n" "Hash a file, ignoring whitespace:\n" "\t%s [-S expectedresult] -F file [-k key] " "[-i info -L okm-len]\n" "Additional bits to add in: [-B bitcount -b bits]\n" "(If -k,-i&-L are used, run HKDF-SHA###.\n" " If -k is used, but not -i&-L, run HMAC-SHA###.\n" " Otherwise, run SHA###.)\n" "Standard tests:\n" "\t%s [-m | -d] [-l loopcount] [-t test#] [-e]\n" "\t\t[-r randomseed] [-R randomloop-count] " "[-p] [-P|-X]\n" "-h\thash to test: " "0|SHA1, 1|SHA224, 2|SHA256, 3|SHA384, 4|SHA512\n" "-m\tperform hmac standard tests\n" "-k\tkey for hmac test\n" "-d\tperform hkdf standard tests\n" "-t\ttest case to run, 1-10\n" "-l\thow many times to run the test\n" "-e\ttest error returns\n" "-p\tdo not print results\n" "-P\tdo not print PASSED/FAILED\n" "-X\tprint FAILED, but not PASSED\n" "-r\tseed for random test\n" "-R\thow many times to run random test\n" "-s\tstring to hash\n" "-S\texpected result of hashed string, in hex\n" "-w\toutput hash in raw format\n" "-x\toutput hash in hex format\n" "-6\toutput hash in base64 format\n"
Eastlake & Hansen Informational [Page 108]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
"-B\t# extra bits to add in after string or file input\n" "-b\textra bits to add (high order bits of #, 0# or 0x#)\n" "-H\tinput hashstr or randomseed is in hex\n" , argv0, argv0, argv0, argv0); exit(1); }
/* * Print the results and PASS/FAIL. */ void printResult(uint8_t *Message_Digest, int hashsize, const char *hashname, const char *testtype, const char *testname, const char *resultarray, int printResults, int printPassFail) { int i, k; if (printResults == PRINTTEXT) { printf("\nhashsize=%d\n", hashsize); putchar('\t'); for (i = 0; i < hashsize; ++i) { putchar(hexdigits[(Message_Digest[i] >> 4) & 0xF]); putchar(hexdigits[Message_Digest[i] & 0xF]); putchar(' '); } putchar('\n'); } else if (printResults == PRINTRAW) { fwrite(Message_Digest, 1, hashsize, stdout); } else if (printResults == PRINTHEX) { for (i = 0; i < hashsize; ++i) { putchar(hexdigits[(Message_Digest[i] >> 4) & 0xF]); putchar(hexdigits[Message_Digest[i] & 0xF]); } putchar('\n'); } else if (printResults == PRINTBASE64) { unsigned char b; char *sm = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" "0123456789+/"; for (i = 0; i < hashsize; i += 3) { putchar(sm[Message_Digest[i] >> 2]); b = (Message_Digest[i] & 0x03) << 4; if (i+1 < hashsize) b |= Message_Digest[i+1] >> 4; putchar(sm[b]); if (i+1 < hashsize) { b = (Message_Digest[i+1] & 0x0f) << 2; if (i+2 < hashsize) b |= Message_Digest[i+2] >> 6; putchar(sm[b]); } else putchar('='); if (i+2 < hashsize) putchar(sm[Message_Digest[i+2] & 0x3f]); else putchar('=');
Eastlake & Hansen Informational [Page 109]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
} putchar('\n'); }
if (printResults && resultarray) { printf(" Should match:\n\t"); for (i = 0, k = 0; i < hashsize; i++, k += 2) { putchar(resultarray[k]); putchar(resultarray[k+1]); putchar(' '); } putchar('\n'); }
if (printPassFail && resultarray) { int ret = checkmatch(Message_Digest, resultarray, hashsize); if ((printPassFail == PRINTPASSFAIL) || !ret) printf("%s %s %s: %s\n", hashname, testtype, testname, ret ? "PASSED" : "FAILED"); } }
/* * Exercise a hash series of functions. The input is the testarray, * repeated repeatcount times, followed by the extrabits. If the * result is known, it is in resultarray in uppercase hex. */ int hash(int testno, int loopno, int hashno, const char *testarray, int length, long repeatcount, int numberExtrabits, int extrabits, const unsigned char *keyarray, int keylen, const unsigned char *info, int infolen, int okmlen, const char *resultarray, int hashsize, int printResults, int printPassFail) { USHAContext sha; HMACContext hmac; HKDFContext hkdf; int err, i; uint8_t Message_Digest_Buf[USHAMaxHashSize]; uint8_t *Message_Digest = Message_Digest_Buf; char buf[20];
if (info) Message_Digest = malloc(okmlen); memset(&sha, '\343', sizeof(sha)); /* force bad data into struct */ memset(&hmac, '\343', sizeof(hmac)); memset(&hkdf, '\343', sizeof(hkdf));
Message_Digest, okmlen) : keyarray ? hmacResult(&hmac, Message_Digest) : USHAResult(&sha, Message_Digest); if (err != shaSuccess) { fprintf(stderr, "hash(): %s Result Error %d, could not compute " "message digest.\n", info ? "hkdf" : keyarray ? "hmac" : "sha", err); return err; }
sprintf(buf, "%d", testno+1); printResult(Message_Digest, info ? okmlen : hashsize, hashes[hashno].name, info ? "hkdf standard test" : keyarray ? "hmac standard test" : "sha standard test", buf, resultarray, printResults, printPassFail);
return err; }
/* * Exercise an HKDF series. The input is the testarray, * repeated repeatcount times, followed by the extrabits. If the * result is known, it is in resultarray in uppercase hex. */ int hashHkdf(int testno, int loopno, int hashno, int printResults, int printPassFail) { int err; unsigned char prk[USHAMaxHashSize+1]; uint8_t okm[255 * USHAMaxHashSize+1]; char buf[20];
/* Now run hkdfExtract() by itself against the test vectors */ /* to verify the intermediate results. */ err = hkdfExtract(hkdfhashes[testno].whichSha, (const uint8_t *) hkdfhashes[testno].saltarray, hkdfhashes[testno].saltlength, (const uint8_t *) hkdfhashes[testno].ikmarray, hkdfhashes[testno].ikmlength, prk); if (err != shaSuccess) { fprintf(stderr, "hashHkdf(): hkdfExtract Error %d.\n", err); return err; } sprintf(buf, "hkdfExtract %d", testno+1); printResult(prk, USHAHashSize(hkdfhashes[testno].whichSha), USHAHashName(hkdfhashes[testno].whichSha), "hkdf standard test", buf, hkdfhashes[testno].prkarray, printResults, printPassFail);
/* Now run hkdfExpand() by itself against the test vectors */ /* using the intermediate results from hkdfExtract. */ err = hkdfExpand(hkdfhashes[testno].whichSha, prk, USHAHashSize(hkdfhashes[testno].whichSha), (const uint8_t *)hkdfhashes[testno].infoarray, hkdfhashes[testno].infolength, okm, hkdfhashes[testno].okmlength); if (err != shaSuccess) { fprintf(stderr, "hashHkdf(): hkdfExpand Error %d.\n", err); return err; } sprintf(buf, "hkdfExpand %d", testno+1); printResult(okm, hkdfhashes[testno].okmlength, USHAHashName(hkdfhashes[testno].whichSha), "hkdf standard test", buf, hkdfhashes[testno].okmarray, printResults, printPassFail);
return err;
Eastlake & Hansen Informational [Page 113]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
}
/* * Exercise a hash series of functions. The input is a filename. * If the result is known, it is in resultarray in uppercase hex. */ int hashfile(int hashno, const char *hashfilename, int bits, int bitcount, int skipSpaces, const unsigned char *keyarray, int keylen, const unsigned char *info, int infolen, int okmlen, const char *resultarray, int hashsize, int printResults, int printPassFail) { USHAContext sha; HMACContext hmac; HKDFContext hkdf; int err, nread, c; unsigned char buf[4096]; uint8_t Message_Digest_Buf[USHAMaxHashSize]; uint8_t *Message_Digest = Message_Digest_Buf; unsigned char cc; FILE *hashfp = (strcmp(hashfilename, "-") == 0) ? stdin : fopen(hashfilename, "r");
if (!hashfp) { fprintf(stderr, "cannot open file '%s'\n", hashfilename); return shaStateError; }
if (info) Message_Digest = malloc(okmlen); memset(&sha, '\343', sizeof(sha)); /* force bad data into struct */ memset(&hmac, '\343', sizeof(hmac)); memset(&hkdf, '\343', sizeof(hkdf)); err = info ? hkdfReset(&hkdf, hashes[hashno].whichSha, keyarray, keylen) : keyarray ? hmacReset(&hmac, hashes[hashno].whichSha, keyarray, keylen) : USHAReset(&sha, hashes[hashno].whichSha); if (err != shaSuccess) { fprintf(stderr, "hashfile(): %sReset Error %d.\n", info ? "hkdf" : keyarray ? "hmac" : "sha", err); return err; }
if (skipSpaces) while ((c = getc(hashfp)) != EOF) { if (!isspace(c)) { cc = (unsigned char)c; err = info ? hkdfInput(&hkdf, &cc, 1) :
if (hashfp != stdin) fclose(hashfp); if (info) free(Message_Digest); return err; }
/* * Exercise a hash series of functions through multiple permutations. * The input is an initial seed. That seed is replicated 3 times. * For 1000 rounds, the previous three results are used as the input. * This result is then checked, and used to seed the next cycle. * If the result is known, it is in resultarrays in uppercase hex. */ void randomtest(int hashno, const char *seed, int hashsize, const char **resultarrays, int randomcount, int printResults, int printPassFail) { int i, j; char buf[20]; unsigned char SEED[USHAMaxHashSize], MD[1003][USHAMaxHashSize];
/* INPUT: Seed - A random seed n bits long */ memcpy(SEED, seed, hashsize); if (printResults == PRINTTEXT) { printf("%s random test seed= '", hashes[hashno].name); printxstr(seed, hashsize); printf("'\n"); }
/* * Run some tests that should invoke errors. */ void testErrors(int hashnolow, int hashnohigh, int printResults, int printPassFail) { USHAContext usha; uint8_t Message_Digest[USHAMaxHashSize]; int hashno, err;
for (hashno = hashnolow; hashno <= hashnohigh; hashno++) { memset(&usha, '\343', sizeof(usha)); /* force bad data */ USHAReset(&usha, hashno); USHAResult(&usha, Message_Digest); err = USHAInput(&usha, (const unsigned char *)"foo", 3); if (printResults == PRINTTEXT) printf ("\nError %d. Should be %d.\n", err, shaStateError);
err = USHAFinalBits(&usha, 0x80, 3); if (printResults == PRINTTEXT) printf ("\nError %d. Should be %d.\n", err, shaStateError); if ((printPassFail == PRINTPASSFAIL) || ((printPassFail == PRINTFAIL) && (err != shaStateError))) printf("%s se: %s\n", hashes[hashno].name, (err == shaStateError) ? "PASSED" : "FAILED");
err = USHAReset(0, hashes[hashno].whichSha); if (printResults == PRINTTEXT) printf("\nError %d. Should be %d.\n", err, shaNull); if ((printPassFail == PRINTPASSFAIL) || ((printPassFail == PRINTFAIL) && (err != shaNull))) printf("%s usha null: %s\n", hashes[hashno].name, (err == shaNull) ? "PASSED" : "FAILED");
switch (hashno) { case SHA1: err = SHA1Reset(0); break; case SHA224: err = SHA224Reset(0); break; case SHA256: err = SHA256Reset(0); break; case SHA384: err = SHA384Reset(0); break; case SHA512: err = SHA512Reset(0); break; } if (printResults == PRINTTEXT) printf("\nError %d. Should be %d.\n", err, shaNull); if ((printPassFail == PRINTPASSFAIL) || ((printPassFail == PRINTFAIL) && (err != shaNull))) printf("%s sha null: %s\n", hashes[hashno].name, (err == shaNull) ? "PASSED" : "FAILED"); } }
/* replace a hex string in place with its value */ int unhexStr(char *hexstr) { char *o = hexstr; int len = 0, nibble1 = 0, nibble2 = 0; if (!hexstr) return 0; for ( ; *hexstr; hexstr++) { if (isalpha((int)(unsigned char)(*hexstr))) { nibble1 = tolower((int)(unsigned char)(*hexstr)) - 'a' + 10; } else if (isdigit((int)(unsigned char)(*hexstr))) { nibble1 = *hexstr - '0';
Eastlake & Hansen Informational [Page 118]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
} else { printf("\nError: bad hex character '%c'\n", *hexstr); } if (!*++hexstr) break; if (isalpha((int)(unsigned char)(*hexstr))) { nibble2 = tolower((int)(unsigned char)(*hexstr)) - 'a' + 10; } else if (isdigit((int)(unsigned char)(*hexstr))) { nibble2 = *hexstr - '0'; } else { printf("\nError: bad hex character '%c'\n", *hexstr); } *o++ = (char)((nibble1 << 4) | nibble2); len++; } return len; }
int main(int argc, char **argv) { int i, err; int loopno, loopnohigh = 1; int hashno, hashnolow = 0, hashnohigh = HASHCOUNT - 1; int testno, testnolow = 0, testnohigh; int ntestnohigh = 0; int printResults = PRINTTEXT; int printPassFail = 1; int checkErrors = 0; char *hashstr = 0; int hashlen = 0; const char *resultstr = 0; char *randomseedstr = 0; int runHmacTests = 0; int runHkdfTests = 0; char *hmacKey = 0; int hmaclen = 0; char *info = 0; int infolen = 0, okmlen = 0; int randomcount = RANDOMCOUNT; const char *hashfilename = 0; const char *hashFilename = 0; int extrabits = 0, numberExtrabits = 0; int strIsHex = 0;
if ('A' != 0x41) { fprintf(stderr, "%s: these tests require ASCII\n", argv[0]); }
while ((i = getopt(argc, argv,
Eastlake & Hansen Informational [Page 119]
RFC 6234 SHAs, HMAC-SHAs, and HKDF May 2011
"6b:B:def:F:h:i:Hk:l:L:mpPr:R:s:S:t:wxX")) != -1) switch (i) { case 'b': extrabits = strtol(optarg, 0, 0); break; case 'B': numberExtrabits = atoi(optarg); break; case 'd': runHkdfTests = 1; break; case 'e': checkErrors = 1; break; case 'f': hashfilename = optarg; break; case 'F': hashFilename = optarg; break; case 'h': hashnolow = hashnohigh = findhash(argv[0], optarg); break; case 'H': strIsHex = 1; break; case 'i': info = optarg; infolen = strlen(optarg); break; case 'k': hmacKey = optarg; hmaclen = strlen(optarg); break; case 'l': loopnohigh = atoi(optarg); break; case 'L': okmlen = strtol(optarg, 0, 0); break; case 'm': runHmacTests = 1; break; case 'P': printPassFail = 0; break; case 'p': printResults = PRINTNONE; break; case 'R': randomcount = atoi(optarg); break; case 'r': randomseedstr = optarg; break; case 's': hashstr = optarg; hashlen = strlen(hashstr); break; case 'S': resultstr = optarg; break; case 't': testnolow = ntestnohigh = atoi(optarg) - 1; break; case 'w': printResults = PRINTRAW; break; case 'x': printResults = PRINTHEX; break; case 'X': printPassFail = 2; break; case '6': printResults = PRINTBASE64; break; default: usage(argv[0]); }
/* Test some error returns */ if (checkErrors) { testErrors(hashnolow, hashnohigh, printResults, printPassFail); }
return 0; }
/* * Compare two strings, case independently. * Equivalent to strcasecmp() found on some systems. */ int scasecmp(const char *s1, const char *s2) { for (;;) { char u1 = tolower((int)(unsigned char)(*s1++)); char u2 = tolower((int)(unsigned char)(*s2++)); if (u1 != u2) return u1 - u2; if (u1 == '\0') return 0; } }
This document is intended to provide convenient open source access by the Internet community to the United States of America Federal Information Processing Standard Secure Hash Algorithms (SHAs) [FIPS 180-2], HMACs based thereon, and HKDF. No independent assertion of the security of these functions by the authors for any particular use is intended.
See [RFC6194] for a discussion of SHA-1 Security Considerations.
Thanks for the corrections to [RFC4634] that were provided by Alfred Hoenes and Jan Andres and to Alfred's comments on the document hereof.
Also to the following in alphabetic order, whose comments lead to improvements in the document: James Carlson, Russ Housley, Tero Kivinen, Juergen Quittek, and Sean Turner.
[RFC2104] Krawczyk, H., Bellare, M., and R. Canetti, "HMAC: Keyed- Hashing for Message Authentication", RFC 2104, February 1997.
[RFC5869] Krawczyk, H. and P. Eronen, "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)", RFC 5869, May 2010.
[SHS] "Secure Hash Standard", United States of American, National Institute of Science and Technology, Federal Information Processing Standard (FIPS) 180-3, http://csrc.nist.gov/publications/fips/fips180-3/ fips180-3_final.pdf.
[US-ASCII] ANSI, "USA Standard Code for Information Interchange", X3.4, American National Standards Institute: New York, 1968.
[RFC3174] Eastlake 3rd, D. and P. Jones, "US Secure Hash Algorithm 1 (SHA1)", RFC 3174, September 2001.
[RFC3874] Housley, R., "A 224-bit One-way Hash Function: SHA-224", RFC 3874, September 2004.
[RFC4055] Schaad, J., Kaliski, B., and R. Housley, "Additional Algorithms and Identifiers for RSA Cryptography for use in the Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile", RFC 4055, June 2005.
[RFC4086] Eastlake 3rd, D., Schiller, J., and S. Crocker, "Randomness Requirements for Security", BCP 106, RFC 4086, June 2005.
[RFC4634] Eastlake 3rd, D. and T. Hansen, "US Secure Hash Algorithms (SHA and HMAC-SHA)", RFC 4634, July 2006.
[RFC6194] Polk, T., Chen, L., Turner, S., and P. Hoffman, "Security Considerations for the SHA-0 and SHA-1 Message-Digest Algorithms", RFC 6194, March 2011.
The following changes were made to RFC 4634 to produce this document:
1. Add code for HKDF and brief text about HKDF with pointer to [RFC5869].
2. Fix numerous errata filed against [RFC4634] as included below. Note that in no case did the old code return an incorrect hash value.
2.a. Correct some of the error return values which has erroneously been "shaNull" to the correct "shaInputTooLong" error.
2.b. Update comments and variable names within the code for consistency and clarity and other editorial changes.
2.c. The previous code for SHA-384 and SHA-512 would stop after 2^93 bytes (2^96 bits). The fixed code handles up to 2^125 bytes (2^128 bits).
2.d. Add additional error checking including a run time check in the test driver to detect attempts to run the test driver after compilation using some other character set instead of [US-ASCII].
3. Update boilerplate, remove special license in [RFC4634] as new boilerplate mandates simplified BSD license.
4. Replace MIT version of getopt with new code to satisfy IETF incoming and outgoing license restrictions.