This document is obsolete. Please
refer to RFC 6234.
Network Working Group D. Eastlake 3rd Request for Comments: 4634 Motorola Labs Updates: 3174 T. Hansen Category: Informational AT&T Labs July 2006
US Secure Hash Algorithms (SHA and HMAC-SHA)
Status of This Memo
This memo provides information for the Internet community. It does not specify an Internet standard of any kind. Distribution of this memo is unlimited.
Copyright Notice
Copyright (C) The Internet Society (2006).
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), specifically SHA-224 (RFC 3874), SHA-256, SHA-384, and SHA-512. The purpose of this document is to make source code performing these hash functions conveniently available to the Internet community. The sample code supports input strings of arbitrary bit length. SHA-1's sample code from RFC 3174 has also been updated to handle input strings of arbitrary bit length. Most of the text herein was adapted by the authors from FIPS 180-2.
Code to perform SHA-based HMACs, with arbitrary bit length text, is also included.
Eastlake 3rd & Hansen Informational [Page 1]
RFC 4634 SHAs and HMAC-SHAs July 2006
Table of Contents
1. Overview of Contents ............................................3 1.1. License ....................................................4 2. Notation for Bit Strings and Integers ...........................4 3. Operations on Words .............................................5 4. Message Padding and Parsing .....................................6 4.1. SHA-224 and SHA-256 ........................................7 4.2. SHA-384 and SHA-512 ........................................8 5. Functions and Constants Used ....................................9 5.1. SHA-224 and SHA-256 ........................................9 5.2. SHA-384 and SHA-512 .......................................10 6. Computing the Message Digest ...................................11 6.1. SHA-224 and SHA-256 Initialization ........................11 6.2. SHA-224 and SHA-256 Processing ............................11 6.3. SHA-384 and SHA-512 Initialization ........................13 6.4. SHA-384 and SHA-512 Processing ............................14 7. SHA-Based HMACs ................................................15 8. C Code for SHAs ................................................15 8.1. The .h File ...............................................18 8.2. The SHA Code ..............................................24 8.2.1. sha1.c .............................................24 8.2.2. sha224-256.c .......................................33 8.2.3. sha384-512.c .......................................45 8.2.4. usha.c .............................................67 8.2.5. sha-private.h ......................................72 8.3. The HMAC Code .............................................73 8.4. The Test Driver ...........................................78 9. Security Considerations .......................................106 10. Normative References .........................................106 11. Informative References .......................................106
NOTE: Much of the text below is taken from [FIPS180-2] and assertions therein of the security of the algorithms described are made by the US Government, the author of [FIPS180-2], and not by the authors of this document.
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, or in the generation of random numbers [RFC4086].
The four 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. See Section 1.1 for license information for this code.
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 these 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 based on the SHA algorithms. Section 8 gives sample code for the SHA algorithms and Section 9 code for SHA-based HMACs. The SHA-based HMACs will accept arbitrary bit length text.
Permission is granted for all uses, commercial and non-commercial, of the sample code found in Section 8. Royalty free license to use, copy, modify and distribute the software found in Section 8 is granted, provided that this document is identified in all material mentioning or referencing this software, and provided that redistributed derivative works do not contain misleading author or version information.
The authors make no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind.
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, which 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 left-most 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 right-most 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.
Eastlake 3rd & Hansen Informational [Page 4]
RFC 4634 SHAs and HMAC-SHAs July 2006
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).
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 left-most 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).
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.
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.
Eastlake 3rd & Hansen Informational [Page 5]
RFC 4634 SHAs and HMAC-SHAs July 2006
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 a number of "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 minimum number of "0"s necessary to meet this criterion is used. 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 = 448 (mod 512)
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 = 896 (mod 1024)
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
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 thirty-two 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 sixty-four 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 thirty-two bits of the fractional parts of the square roots of the first eight prime numbers.
SHA-224 and SHA-256 perform identical processing on messages 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
Eastlake 3rd & Hansen Informational [Page 11]
RFC 4634 SHAs and HMAC-SHAs July 2006
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, which are considered to be composed of 16 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(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 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
Eastlake 3rd & Hansen Informational [Page 12]
RFC 4634 SHAs and HMAC-SHAs July 2006
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 sixty-four 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 sixty-four 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, which are considered to be composed of 16 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.
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(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
Eastlake 3rd & Hansen Informational [Page 14]
RFC 4634 SHAs and HMAC-SHAs July 2006
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.
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.
Below is a demonstration implementation of these secure hash functions in C. Section 8.1 contains the header file sha.h, which declares all constants, structures, and functions used by the sha and hmac functions. Section 8.2 contains the C code for sha1.c, sha224-256.c, sha384-512.c, and usha.c along with sha-private.h, which provides some declarations common to all the sha functions. Section 8.3 contains the C code for the hmac functions. Section 8.4 contains a test driver to exercise the code.
Eastlake 3rd & Hansen Informational [Page 15]
RFC 4634 SHAs and HMAC-SHAs July 2006
For each of the digest length $$$, there is the following set of constants, a structure, and functions:
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 shaSuccess = 0 constant returned by each function on success shaNull = 1 constant returned by each function when presented with a null pointer parameter shaInputTooLong = 2 constant returned by each function when the input data is too long shaStateError constant returned by each function 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 *); Reset the hash context state int SHA$$$Input(SHA$$$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 constant returned by USHA functions when presented with a bad SHAversion (SHA$$$) parameter
Eastlake 3rd & Hansen Informational [Page 16]
RFC 4634 SHAs and HMAC-SHAs July 2006
SHA$$$ SHAversion enumeration values, used by usha and hmac functions to select the SHA function suite
Structure: typedef USHAContext an opaque structure holding the complete state for producing the hash
Functions: int USHAReset(USHAContext *, SHAversion whichSha); Reset the hash context state. int USHAInput(USHAContext *, const uint8_t *bytes, unsigned int bytecount); Incorporate bytecount octets into the hash. int USHAFinalBits(USHAContext *, const uint8_t bits, unsigned int bitcount); Incorporate bitcount bits into the hash. int USHAResult(USHAContext *, 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.
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 hash
Functions: int hmacReset(HMACContext *ctx, enum SHAversion whichSha, const unsigned char *key, int key_len); Reset the hash context state. int hmacInput(HMACContext *ctx, const unsigned char *text, int text_len); Incorporate text_len octets into the hash. int hmacFinalBits(HMACContext *ctx, const uint8_t bits, unsigned int bitcount); Incorporate bitcount bits into the hash.
Eastlake 3rd & Hansen Informational [Page 17]
RFC 4634 SHAs and HMAC-SHAs July 2006
int hmacResult(HMACContext *ctx, 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.
In addition, a combined interface is provided, similar to that shown in RFC 2104, 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 hash. Octets in Message_Digest beyond USHAHashSize(whichSha) are left untouched.
/**************************** sha.h ****************************/ /******************* See RFC 4634 for details ******************/ #ifndef _SHA_H_ #define _SHA_H_
/* * Description: * This file implements the Secure Hash Signature Standard * algorithms as defined in the National Institute of Standards * and Technology Federal Information Processing Standards * Publication (FIPS PUB) 180-1 published on April 17, 1995, 180-2 * published on August 1, 2002, and the FIPS PUB 180-2 Change * Notice published on February 28, 2004. * * A combined document showing all algorithms is available at * http://csrc.nist.gov/publications/fips/ * fips180-2/fips180-2withchangenotice.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 */
#include <stdint.h> /* * If you do not have the ISO standard stdint.h header file, then you
Eastlake 3rd & Hansen Informational [Page 18]
RFC 4634 SHAs and HMAC-SHAs July 2006
* 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 * */
#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;
Eastlake 3rd & Hansen Informational [Page 19]
RFC 4634 SHAs and HMAC-SHAs July 2006
/* * 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_Low; /* Message length in bits */ uint32_t Length_High; /* Message length in bits */
int Computed; /* Is the digest computed? */ int Corrupted; /* Is the digest corrupted? */ } 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_Low; /* Message length in bits */ uint32_t Length_High; /* Message length in bits */
int Computed; /* Is the digest computed?*/ int Corrupted; /* Is the digest corrupted? */ } 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; } 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 */ } HMACContext;
Eastlake 3rd & Hansen Informational [Page 21]
RFC 4634 SHAs and HMAC-SHAs July 2006
/* * Function Prototypes */
/* SHA-1 */ extern int SHA1Reset(SHA1Context *); extern int SHA1Input(SHA1Context *, const uint8_t *bytes, unsigned int bytecount); extern int SHA1FinalBits(SHA1Context *, const uint8_t bits, unsigned int bitcount); extern int SHA1Result(SHA1Context *, uint8_t Message_Digest[SHA1HashSize]);
/* SHA-224 */ extern int SHA224Reset(SHA224Context *); extern int SHA224Input(SHA224Context *, const uint8_t *bytes, unsigned int bytecount); extern int SHA224FinalBits(SHA224Context *, const uint8_t bits, unsigned int bitcount); 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 *, const uint8_t bits, unsigned int bitcount); 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 *, const uint8_t bits, unsigned int bitcount); 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 *, const uint8_t bits, unsigned int bitcount); extern int SHA512Result(SHA512Context *, uint8_t Message_Digest[SHA512HashSize]);
Eastlake 3rd & Hansen Informational [Page 22]
RFC 4634 SHAs and HMAC-SHAs July 2006
/* Unified SHA functions, chosen by whichSha */ extern int USHAReset(USHAContext *, SHAversion whichSha); extern int USHAInput(USHAContext *, const uint8_t *bytes, unsigned int bytecount); extern int USHAFinalBits(USHAContext *, const uint8_t bits, unsigned int bitcount); extern int USHAResult(USHAContext *, uint8_t Message_Digest[USHAMaxHashSize]); extern int USHABlockSize(enum SHAversion whichSha); extern int USHAHashSize(enum SHAversion whichSha); extern int USHAHashSizeBits(enum SHAversion whichSha);
/* * HMAC Keyed-Hashing for Message Authentication, RFC2104, * 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, RFC2104, * for all SHAs. * This interface allows any length of text input to be used. */ extern int hmacReset(HMACContext *ctx, enum SHAversion whichSha, const unsigned char *key, int key_len); extern int hmacInput(HMACContext *ctx, const unsigned char *text, int text_len);
extern int hmacFinalBits(HMACContext *ctx, const uint8_t bits, unsigned int bitcount); extern int hmacResult(HMACContext *ctx, uint8_t digest[USHAMaxHashSize]);
This code is primarily intended as expository 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 4634 for details ******************/ /* * Description: * This file implements the Secure Hash Signature Standard * algorithms as defined in the National Institute of Standards * and Technology Federal Information Processing Standards * Publication (FIPS PUB) 180-1 published on April 17, 1995, 180-2 * published on August 1, 2002, and the FIPS PUB 180-2 Change * Notice published on February 28, 2004. * * A combined document showing all algorithms is available at * http://csrc.nist.gov/publications/fips/ * fips180-2/fips180-2withchangenotice.pdf * * The SHA-1 algorithm produces a 160-bit message digest 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-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 character, and then * uses SHA1FinalBits() to hash the final few bits of the input. */
Eastlake 3rd & Hansen Informational [Page 24]
RFC 4634 SHAs and HMAC-SHAs July 2006
#include "sha.h" #include "sha-private.h"
/* * Define the SHA1 circular left shift macro */ #define SHA1_ROTL(bits,word) \ (((word) << (bits)) | ((word) >> (32-(bits))))
/* * 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 characters representing the next portion of * the message. * 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 (!length) return shaSuccess;
if (!context || !message_array) return shaNull;
if (context->Computed) { context->Corrupted = shaStateError; return shaStateError; }
if (context->Corrupted)
Eastlake 3rd & Hansen Informational [Page 26]
RFC 4634 SHAs and HMAC-SHAs July 2006
return context->Corrupted;
while (length-- && !context->Corrupted) { context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF);
if (!SHA1AddLength(context, 8) && (context->Message_Block_Index == SHA1_Message_Block_Size)) SHA1ProcessMessageBlock(context);
message_array++; }
return shaSuccess; }
/* * 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. */ int SHA1FinalBits(SHA1Context *context, const uint8_t message_bits, unsigned int length) { 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 }; uint8_t markbit[8] = { /* 0 0b10000000 */ 0x80, /* 1 0b01000000 */ 0x40, /* 2 0b00100000 */ 0x20, /* 3 0b00010000 */ 0x10, /* 4 0b00001000 */ 0x08, /* 5 0b00000100 */ 0x04,
/* * 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 0th element, * the last octet of hash in the 19th element. * * 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 SHA1Result(SHA1Context *context, uint8_t Message_Digest[SHA1HashSize]) { int i;
Eastlake 3rd & Hansen Informational [Page 28]
RFC 4634 SHAs and HMAC-SHAs July 2006
if (!context || !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; }
/* * 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 digest 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_Low = 0; /* and clear length */ context->Length_High = 0; context->Computed = 1; }
/*
Eastlake 3rd & Hansen Informational [Page 29]
RFC 4634 SHAs and HMAC-SHAs July 2006
* SHA1PadMessage * * Description: * According to the standard, the message must be padded to an * even 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 digest 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;
while (context->Message_Block_Index < (SHA1_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);
/* * SHA1ProcessMessageBlock * * Description: * This helper function will process the next 512 bits of the * message stored in the Message_Block array. * * Parameters: * None. * * 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 publication. */ static void SHA1ProcessMessageBlock(SHA1Context *context) { /* Constants defined in FIPS-180-2, section 4.2.1 */ const uint32_t K[4] = { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 }; 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]); }
Eastlake 3rd & Hansen Informational [Page 31]
RFC 4634 SHAs and HMAC-SHAs July 2006
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; 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; }
/*************************** sha224-256.c ***************************/ /********************* See RFC 4634 for details *********************/ /* * Description: * This file implements the Secure Hash Signature Standard * algorithms as defined in the National Institute of Standards * and Technology Federal Information Processing Standards * Publication (FIPS PUB) 180-1 published on April 17, 1995, 180-2 * published on August 1, 2002, and the FIPS PUB 180-2 Change * Notice published on February 28, 2004. * * A combined document showing all algorithms is available at * http://csrc.nist.gov/publications/fips/ * fips180-2/fips180-2withchangenotice.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 * 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 * character, and then uses SHA224/256FinalBits() to hash the * final few bits of the input. */
#include "sha.h" #include "sha-private.h"
Eastlake 3rd & Hansen Informational [Page 33]
RFC 4634 SHAs and HMAC-SHAs July 2006
/* Define the SHA shift, rotate left and rotate right macro */ #define SHA256_SHR(bits,word) ((word) >> (bits)) #define SHA256_ROTL(bits,word) \ (((word) << (bits)) | ((word) >> (32-(bits)))) #define SHA256_ROTR(bits,word) \ (((word) >> (bits)) | ((word) << (32-(bits))))
/* * SHA224Reset * * Description: * This function will initialize the SHA384Context 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 characters representing the next portion of * the message. * 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 *
Eastlake 3rd & Hansen Informational [Page 35]
RFC 4634 SHAs and HMAC-SHAs July 2006
* 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, const 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 0th element, * the last octet of hash in the 28th element. * * 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
Eastlake 3rd & Hansen Informational [Page 36]
RFC 4634 SHAs and HMAC-SHAs July 2006
* * 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 characters representing the next portion of * the message. * 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 (!length) return shaSuccess;
if (!context || !message_array) return shaNull;
if (context->Computed) { context->Corrupted = shaStateError; return shaStateError;
Eastlake 3rd & Hansen Informational [Page 37]
RFC 4634 SHAs and HMAC-SHAs July 2006
}
if (context->Corrupted) return context->Corrupted;
while (length-- && !context->Corrupted) { context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF);
if (!SHA224_256AddLength(context, 8) && (context->Message_Block_Index == SHA256_Message_Block_Size)) SHA224_256ProcessMessageBlock(context);
message_array++; }
return shaSuccess;
}
/* * 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. */ int SHA256FinalBits(SHA256Context *context, const uint8_t message_bits, unsigned int length) { 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 };
/* * 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 0th element, * the last octet of hash in the 32nd element. * * 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 SHA256Result(SHA256Context *context, uint8_t Message_Digest[]) {
/* * SHA224_256Finalize * * 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 digest 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_Low = 0; /* and clear length */ context->Length_High = 0; context->Computed = 1; }
/* * SHA224_256PadMessage * * Description: * According to the standard, the message must be padded to an * even 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]
Eastlake 3rd & Hansen Informational [Page 40]
RFC 4634 SHAs and HMAC-SHAs July 2006
* The context to pad * Pad_Byte: [in] * The last byte to add to the digest 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) { /* * 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_256ProcessMessageBlock *
Eastlake 3rd & Hansen Informational [Page 41]
RFC 4634 SHAs and HMAC-SHAs July 2006
* Description: * This 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 publication. */ static void SHA224_256ProcessMessageBlock(SHA256Context *context) { /* Constants defined in FIPS-180-2, 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 3rd & Hansen Informational [Page 42]
RFC 4634 SHAs and HMAC-SHAs July 2006
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_256Reset * * Description: * This helper function will initialize the SHA256Context in * preparation for computing a new SHA256 message digest. * * Parameters: * context: [in/out] * The context to reset.
Eastlake 3rd & Hansen Informational [Page 43]
RFC 4634 SHAs and HMAC-SHAs July 2006
* H0 * The initial hash value to use. * * Returns: * sha Error Code. */ static int SHA224_256Reset(SHA256Context *context, uint32_t *H0) { if (!context) return shaNull;
/* * 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 0th element, * the last octet of hash in the 28th/32nd element. * * 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 28 or 32. * * Returns:
Eastlake 3rd & Hansen Informational [Page 44]
RFC 4634 SHAs and HMAC-SHAs July 2006
* sha Error Code. */ static int SHA224_256ResultN(SHA256Context *context, uint8_t Message_Digest[], int HashSize) { int i;
if (!context || !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 4634 for details *********************/ /* * Description: * This file implements the Secure Hash Signature Standard * algorithms as defined in the National Institute of Standards * and Technology Federal Information Processing Standards * Publication (FIPS PUB) 180-1 published on April 17, 1995, 180-2 * published on August 1, 2002, and the FIPS PUB 180-2 Change * Notice published on February 28, 2004. * * A combined document showing all algorithms is available at * http://csrc.nist.gov/publications/fips/ * fips180-2/fips180-2withchangenotice.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 * 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. *
Eastlake 3rd & Hansen Informational [Page 45]
RFC 4634 SHAs and HMAC-SHAs July 2006
* 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 character, and then uses SHA384/256FinalBits() * to hash the final few bits of the input. * */
#include "sha.h" #include "sha-private.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. * * Parameters: * context: [in/out] * The SHA context to update * message_array: [in] * An array of characters representing the next portion of * the message. * length: [in] * The length of the message in message_array * * Returns: * sha Error Code. *
Eastlake 3rd & Hansen Informational [Page 52]
RFC 4634 SHAs and HMAC-SHAs July 2006
*/ 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, const uint8_t message_bits, unsigned int length) { return SHA512FinalBits(context, message_bits, length); }
/* * SHA384Result * * 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 0th element, * the last octet of hash in the 48th element. * * Parameters: * context: [in/out] * The context to use to calculate the SHA hash. * Message_Digest: [out] * Where the digest is returned. *
/* * 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: * 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 characters representing the next portion of * the message. * length: [in] * The length of the message in message_array * * Returns: * sha Error Code.
Eastlake 3rd & Hansen Informational [Page 54]
RFC 4634 SHAs and HMAC-SHAs July 2006
* */ int SHA512Input(SHA512Context *context, const uint8_t *message_array, unsigned int length) { if (!length) return shaSuccess;
if (!context || !message_array) return shaNull;
if (context->Computed) { context->Corrupted = shaStateError; return shaStateError; }
if (context->Corrupted) return context->Corrupted;
while (length-- && !context->Corrupted) { context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF);
if (!SHA384_512AddLength(context, 8) && (context->Message_Block_Index == SHA512_Message_Block_Size)) SHA384_512ProcessMessageBlock(context);
message_array++; }
return shaSuccess; }
/* * SHA512FinalBits * * 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]
/* * SHA384_512Finalize * * Description: * This helper function finishes off the digest calculations.
Eastlake 3rd & Hansen Informational [Page 56]
RFC 4634 SHAs and HMAC-SHAs July 2006
* * Parameters: * context: [in/out] * The SHA context to update * Pad_Byte: [in] * The last byte to add to the digest 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_Low = 0; context->Length_High = 0; #endif /* USE_32BIT_ONLY */ context->Computed = 1; }
/* * SHA512Result * * Description: * This function will return the 512-bit message * digest into the Message_Digest array provided by the caller. * NOTE: The first octet of hash is stored in the 0th element, * the last octet of hash in the 64th element. * * Parameters: * context: [in/out] * The context to use to calculate the SHA hash. * Message_Digest: [out] * Where the digest is returned. * * Returns:
/* * SHA384_512PadMessage * * Description: * According to the standard, the message must be padded to an * even 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 digest 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;
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_512Reset * * Description: * This helper function will initialize the SHA512Context in * preparation for computing a new SHA384 or SHA512 message
Eastlake 3rd & Hansen Informational [Page 64]
RFC 4634 SHAs and HMAC-SHAs July 2006
* digest. * * Parameters: * context: [in/out] * The context to reset. * H0 * The initial hash value to use. * * Returns: * sha Error Code. * */ #ifdef USE_32BIT_ONLY static int SHA384_512Reset(SHA512Context *context, uint32_t H0[]) #else /* !USE_32BIT_ONLY */ static int SHA384_512Reset(SHA512Context *context, uint64_t H0[]) #endif /* USE_32BIT_ONLY */ { int i; if (!context) return shaNull;
for (i = 0; i < SHA512HashSize/4; i++) context->Intermediate_Hash[i] = H0[i]; #else /* !USE_32BIT_ONLY */ context->Length_High = context->Length_Low = 0;
for (i = 0; i < SHA512HashSize/8; i++) context->Intermediate_Hash[i] = H0[i]; #endif /* USE_32BIT_ONLY */
context->Computed = 0; context->Corrupted = 0;
return shaSuccess; }
/* * SHA384_512ResultN * * Description: * This helper function will return the 384-bit or 512-bit message
Eastlake 3rd & Hansen Informational [Page 65]
RFC 4634 SHAs and HMAC-SHAs July 2006
* digest into the Message_Digest array provided by the caller. * NOTE: The first octet of hash is stored in the 0th element, * the last octet of hash in the 48th/64th element. * * 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 || !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)
/**************************** usha.c ****************************/ /******************** See RFC 4634 for details ******************/ /* * 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 *ctx, enum SHAversion whichSha) { if (ctx) { ctx->whichSha = whichSha; switch (whichSha) { case SHA1: return SHA1Reset((SHA1Context*)&ctx->ctx); case SHA224: return SHA224Reset((SHA224Context*)&ctx->ctx); case SHA256: return SHA256Reset((SHA256Context*)&ctx->ctx); case SHA384: return SHA384Reset((SHA384Context*)&ctx->ctx); case SHA512: return SHA512Reset((SHA512Context*)&ctx->ctx); default: return shaBadParam; } } else { return shaNull;
Eastlake 3rd & Hansen Informational [Page 67]
RFC 4634 SHAs and HMAC-SHAs July 2006
} }
/* * 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 characters representing the next portion of * the message. * length: [in] * The length of the message in message_array * * Returns: * sha Error Code. * */ int USHAInput(USHAContext *ctx, const uint8_t *bytes, unsigned int bytecount) { if (ctx) { switch (ctx->whichSha) { case SHA1: return SHA1Input((SHA1Context*)&ctx->ctx, bytes, bytecount); case SHA224: return SHA224Input((SHA224Context*)&ctx->ctx, bytes, bytecount); case SHA256: return SHA256Input((SHA256Context*)&ctx->ctx, bytes, bytecount); case SHA384: return SHA384Input((SHA384Context*)&ctx->ctx, bytes, bytecount); case SHA512: return SHA512Input((SHA512Context*)&ctx->ctx, bytes, bytecount); default: return shaBadParam; } } else { return shaNull; } }
Eastlake 3rd & Hansen Informational [Page 68]
RFC 4634 SHAs and HMAC-SHAs July 2006
/* * 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 *ctx, const uint8_t bits, unsigned int bitcount) { if (ctx) { switch (ctx->whichSha) { case SHA1: return SHA1FinalBits((SHA1Context*)&ctx->ctx, bits, bitcount); case SHA224: return SHA224FinalBits((SHA224Context*)&ctx->ctx, bits, bitcount); case SHA256: return SHA256FinalBits((SHA256Context*)&ctx->ctx, bits, bitcount); case SHA384: return SHA384FinalBits((SHA384Context*)&ctx->ctx, bits, bitcount); case SHA512: return SHA512FinalBits((SHA512Context*)&ctx->ctx, bits, bitcount); default: return shaBadParam; } } else { return shaNull; } }
/* * USHAResult *
Eastlake 3rd & Hansen Informational [Page 69]
RFC 4634 SHAs and HMAC-SHAs July 2006
* 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 0th element, * the last octet of hash in the 19th element. * * 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 *ctx, uint8_t Message_Digest[USHAMaxHashSize]) { if (ctx) { switch (ctx->whichSha) { case SHA1: return SHA1Result((SHA1Context*)&ctx->ctx, Message_Digest); case SHA224: return SHA224Result((SHA224Context*)&ctx->ctx, Message_Digest); case SHA256: return SHA256Result((SHA256Context*)&ctx->ctx, Message_Digest); case SHA384: return SHA384Result((SHA384Context*)&ctx->ctx, Message_Digest); case SHA512: return SHA512Result((SHA512Context*)&ctx->ctx, Message_Digest); default: return shaBadParam; } } else { return shaNull; } }
/* * USHABlockSize * * Description: * This function will return the blocksize for the given SHA * algorithm. * * Parameters: * whichSha: * which SHA algorithm to query
Eastlake 3rd & Hansen Informational [Page 70]
RFC 4634 SHAs and HMAC-SHAs July 2006
* * 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; } }
/* * USHAHashSizeBits * * Description:
Eastlake 3rd & Hansen Informational [Page 71]
RFC 4634 SHAs and HMAC-SHAs July 2006
* 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; } }
/*************************** sha-private.h ***************************/ /********************** See RFC 4634 for details *********************/ #ifndef _SHA_PRIVATE__H #define _SHA_PRIVATE__H /* * These definitions are defined in FIPS-180-2, 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-2 are as follows: */
/**************************** hmac.c ****************************/ /******************** See RFC 4634 for details ******************/ /* * Description: * This file implements the HMAC algorithm (Keyed-Hashing for * Message Authentication, RFC2104), 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 * key: [in] * The secret shared key. * key_len: [in] * The length of the secret shared key. * message_array: [in] * An array of characters representing the message. * length: [in] * The length of the message in message_array * digest: [out] * Where the digest is returned. * NOTE: The length of the digest is determined by * the value of whichSha. * * Returns: * sha Error Code. * */ int hmac(SHAversion whichSha, const unsigned char *text, int text_len, const unsigned char *key, int key_len, uint8_t digest[USHAMaxHashSize])
/* * 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 *ctx, enum SHAversion whichSha, const unsigned char *key, int key_len) { int i, blocksize, hashsize;
* reset it to key = HASH(key). */ if (key_len > blocksize) { USHAContext tctx; int err = USHAReset(&tctx, whichSha) || USHAInput(&tctx, key, key_len) || USHAResult(&tctx, 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. * 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; ctx->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; ctx->k_opad[i] = 0x5c; }
/* perform inner hash */ /* init context for 1st pass */ return USHAReset(&ctx->shaContext, whichSha) || /* and start with inner pad */ USHAInput(&ctx->shaContext, k_ipad, blocksize); }
/* * hmacInput * * Description: * This function accepts an array of octets as the next portion * of the message.
Eastlake 3rd & Hansen Informational [Page 75]
RFC 4634 SHAs and HMAC-SHAs July 2006
* * Parameters: * context: [in/out] * The HMAC context to update * message_array: [in] * An array of characters representing the next portion of * the message. * length: [in] * The length of the message in message_array * * Returns: * sha Error Code. * */ int hmacInput(HMACContext *ctx, const unsigned char *text, int text_len) { if (!ctx) return shaNull; /* then text of datagram */ return USHAInput(&ctx->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 * three bits ###.) * length: [in] * The number of bits in message_bits, between 1 and 7. * * Returns: * sha Error Code. */ int hmacFinalBits(HMACContext *ctx, const uint8_t bits, unsigned int bitcount) { if (!ctx) return shaNull; /* then final bits of datagram */ return USHAFinalBits(&ctx->shaContext, bits, bitcount);
Eastlake 3rd & Hansen Informational [Page 76]
RFC 4634 SHAs and HMAC-SHAs July 2006
}
/* * HMACResult * * Description: * This function will return the N-byte message digest into the * Message_Digest array provided by the caller. * NOTE: The first octet of hash is stored in the 0th element, * the last octet of hash in the Nth element. * * 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 *ctx, uint8_t *digest) { if (!ctx) return shaNull;
/* finish up 1st pass */ /* (Use digest here as a temporary buffer.) */ return USHAResult(&ctx->shaContext, digest) ||
The following code is a main program test driver to exercise the code in sha1.c, sha224-256.c, and sha384-512.c. The test driver can also be used as a stand-alone program for generating the hashes.
/**************************** shatest.c ****************************/ /********************* See RFC 4634 for details ********************/ /* * Description: * This file will exercise the SHA code performing * the three tests documented in FIPS PUB 180-2 * (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)", * three of which are bit-level tests * (http://csrc.nist.gov/cryptval/shs/SHAVS.pdf) * * This file will exercise the HMAC SHA1 code performing * the seven tests documented in RFCs 2202 and 4231. * * 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. * */
{ /* 7 */ { "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" }, { 80, 131 }, { "Test Using Larger Than Block-Size Key and " "Larger Than One Block-Size Data", "\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74\x20" "\x75\x73\x69\x6e\x67\x20\x61\x20\x6c\x61\x72\x67\x65\x72\x20" "\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73\x69\x7a\x65" "\x20\x6b\x65\x79\x20\x61\x6e\x64\x20\x61\x20\x6c\x61\x72\x67" "\x65\x72\x20\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73" "\x69\x7a\x65\x20\x64\x61\x74\x61\x2e\x20\x54\x68\x65\x20\x6b" "\x65\x79\x20\x6e\x65\x65\x64\x73\x20\x74\x6f\x20\x62\x65\x20" "\x68\x61\x73\x68\x65\x64\x20\x62\x65\x66\x6f\x72\x65\x20\x62" "\x65\x69\x6e\x67\x20\x75\x73\x65\x64\x20\x62\x79\x20\x74\x68" "\x65\x20\x48\x4d\x41\x43\x20\x61\x6c\x67\x6f\x72\x69\x74\x68" "\x6d\x2e" /* "This is a test using a larger than block-size key and a " "larger than block-size data. The key needs to be hashed " "before being used by the HMAC algorithm." */ }, { 73, 152 }, { /* HMAC-SHA-1 */ "E8E99D0F45237D786D6BBAA7965C7808BBFF1A91", /* HMAC-SHA-224 */ "3A854166AC5D9F023F54D517D0B39DBD946770DB9C2B95C9F6F565D1", /* HMAC-SHA-256 */ "9B09FFA71B942FCB27635FBCD5B0E944BFDC63644F0713938A7F51535C3A" "35E2", /* HMAC-SHA-384 */ "6617178E941F020D351E2F254E8FD32C602420FEB0B8FB9ADCCEBB82461E" "99C5A678CC31E799176D3860E6110C46523E", /* HMAC-SHA-512 */ "E37B6A775DC87DBAA4DFA9F96E5E3FFDDEBD71F8867289865DF5A32D20CD" "C944B6022CAC3C4982B10D5EEB55C3E4DE15134676FB6DE0446065C97440" "FA8C6A58" }, { SHA1HashSize, SHA224HashSize, SHA256HashSize, SHA384HashSize, SHA512HashSize } } };
/*
Eastlake 3rd & Hansen Informational [Page 90]
RFC 4634 SHAs and HMAC-SHAs July 2006
* 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 non-printable characters to hex "## ". */ void printxstr(const char *str, int len) { for ( ; len-- > 0; str++) printf("%c%c ", hexdigits[(*str >> 4) & 0xF], hexdigits[*str & 0xF]); }
"Hash a file:\n" "\t%s [-S expectedresult] -f file [-k key]\n" "Hash a file, ignoring whitespace:\n" "\t%s [-S expectedresult] -F file [-k key]\n" "Additional bits to add in: [-B bitcount -b bits]\n" "-h\thash to test: " "0|SHA1, 1|SHA224, 2|SHA256, 3|SHA384, 4|SHA512\n" "-m\tperform hmac test\n" "-k\tkey for hmac test\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" "-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) { 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) {
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 char *resultarray, int hashsize, int printResults, int printPassFail) { USHAContext sha; HMACContext hmac; int err, i; uint8_t Message_Digest[USHAMaxHashSize]; char buf[20];
err = 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", keyarray ? "hmac" : "sha", err); return err; }
sprintf(buf, "%d", testno+1);
Eastlake 3rd & Hansen Informational [Page 94]
RFC 4634 SHAs and HMAC-SHAs July 2006
printResult(Message_Digest, hashsize, hashes[hashno].name, keyarray ? "hmac standard test" : "sha standard test", buf, resultarray, printResults, printPassFail);
return err; }
/* * 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 char *resultarray, int hashsize, int printResults, int printPassFail) { USHAContext sha; HMACContext hmac; int err, nread, c; unsigned char buf[4096]; uint8_t Message_Digest[USHAMaxHashSize]; unsigned char cc; FILE *hashfp = (strcmp(hashfilename, "-") == 0) ? stdin : fopen(hashfilename, "r");
if (!hashfp) { fprintf(stderr, "cannot open file '%s'\n", hashfilename); return shaStateError; }
memset(&sha, '\343', sizeof(sha)); /* force bad data into struct */ memset(&hmac, '\343', sizeof(hmac)); err = keyarray ? hmacReset(&hmac, hashes[hashno].whichSha, keyarray, keylen) : USHAReset(&sha, hashes[hashno].whichSha);
if (hashfp != stdin) fclose(hashfp); return err; }
/* * Exercise a hash series of functions through multiple permutations.
Eastlake 3rd & Hansen Informational [Page 96]
RFC 4634 SHAs and HMAC-SHAs July 2006
* 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); if ((printPassFail == PRINTPASSFAIL) || ((printPassFail == PRINTFAIL) && (err != shaStateError))) printf("%s se: %s\n", hashes[hashno].name, (err == shaStateError) ? "PASSED" : "FAILED");
err = USHAFinalBits(&usha, 0x80, 3); if (printResults == PRINTTEXT) printf ("\nError %d. Should be %d.\n", err, shaStateError); if ((printPassFail == PRINTPASSFAIL) || ((printPassFail == PRINTFAIL) && (err != shaStateError)))
/* 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(*s1++); char u2 = tolower(*s2++); if (u1 != u2) return u1 - u2; if (u1 == '\0') return 0; } }
/* * This is a copy of getopt provided for those systems that do not * have it. The name was changed to xgetopt to not conflict on those * systems that do have it. Similarly, optarg, optind and opterr * were renamed to xoptarg, xoptind and xopterr. * * Copyright 1990, 1991, 1992 by the Massachusetts Institute of * Technology and UniSoft Group Limited.
Eastlake 3rd & Hansen Informational [Page 103]
RFC 4634 SHAs and HMAC-SHAs July 2006
* * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the names of MIT and UniSoft not * be used in advertising or publicity pertaining to distribution of * the software without specific, written prior permission. MIT and * UniSoft make no representations about the suitability of this * software for any purpose. It is provided "as is" without express * or implied warranty. * * $XConsortium: getopt.c,v 1.2 92/07/01 11:59:04 rws Exp $ * NB: Reformatted to match above style. */
char *xoptarg; int xoptind = 1; int xopterr = 1;
static int xgetopt(int argc, char **argv, const char *optstring) { static int avplace; char *ap; char *cp; int c;
if (xoptind >= argc) return EOF;
ap = argv[xoptind] + avplace;
/* At beginning of arg but not an option */ if (avplace == 0) { if (ap[0] != '-') return EOF; else if (ap[1] == '-') { /* Special end of options option */ xoptind++; return EOF; } else if (ap[1] == '\0') return EOF; /* single '-' is not allowed */ }
/* Get next letter */ avplace++; c = *++ap;
Eastlake 3rd & Hansen Informational [Page 104]
RFC 4634 SHAs and HMAC-SHAs July 2006
cp = strchr(optstring, c); if (cp == NULL || c == ':') { if (xopterr) fprintf(stderr, "Unrecognised option -- %c\n", c); return '?'; }
if (cp[1] == ':') { /* There should be an option arg */ avplace = 0; if (ap[1] == '\0') { /* It is a separate arg */ if (++xoptind >= argc) { if (xopterr) fprintf(stderr, "Option requires an argument\n"); return '?'; } xoptarg = argv[xoptind++]; } else { /* is attached to option letter */ xoptarg = ap + 1; ++xoptind; } } else { /* If we are out of letters then go to next arg */ if (ap[1] == '\0') { ++xoptind; avplace = 0; }
This document is intended to provides the Internet community convenient access to source code that implements the United States of America Federal Information Processing Standard Secure Hash Algorithms (SHAs) [FIPS180-2] and HMACs based upon these one-way hash functions. See license in Section 1.1. No independent assertion of the security of this hash function by the authors for any particular use is intended.
[FIPS180-2] "Secure Hash Standard", United States of America, National Institute of Standards and Technology, Federal Information Processing Standard (FIPS) 180-2, http://csrc.nist.gov/publications/fips/fips180-2/ fips180-2withchangenotice.pdf.
[RFC2104] Krawczyk, H., Bellare, M., and R. Canetti, "HMAC: Keyed- Hashing for Message Authentication", RFC 2104, February 1997.
This document is subject to the rights, licenses and restrictions contained in BCP 78, and except as set forth therein, the authors retain all their rights.
This document and the information contained herein are provided on an "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
Intellectual Property
The IETF takes no position regarding the validity or scope of any Intellectual Property Rights or other rights that might be claimed to pertain to the implementation or use of the technology described in this document or the extent to which any license under such rights might or might not be available; nor does it represent that it has made any independent effort to identify any such rights. Information on the procedures with respect to rights in RFC documents can be found in BCP 78 and BCP 79.
Copies of IPR disclosures made to the IETF Secretariat and any assurances of licenses to be made available, or the result of an attempt made to obtain a general license or permission for the use of such proprietary rights by implementers or users of this specification can be obtained from the IETF on-line IPR repository at http://www.ietf.org/ipr.
The IETF invites any interested party to bring to its attention any copyrights, patents or patent applications, or other proprietary rights that may cover technology that may be required to implement this standard. Please address the information to the IETF at ietf-ipr@ietf.org.
Acknowledgement
Funding for the RFC Editor function is provided by the IETF Administrative Support Activity (IASA).