Network Working Group Donald E. Eastlake 3rd
INTERNET-DRAFT Motorola Labs
Updates RFC 3174 Tony Hansen
AT&T Labs
Expires: July 2006 January 2006
US Secure Hash Algorithms (SHA and HMAC-SHA)-- ------ ---- ---------- ---- --- ---------<draft-eastlake-sha2-02.txt>
Status of This Document
By submitting this Internet-Draft, each author represents that any
applicable patent or other IPR claims of which he or she is aware
have been or will be disclosed, and any of which he or she becomes
aware will be disclosed, in accordance with Section 6 of BCP 79.
Distribution of this document is unlimited. Comments should be sent
to the authors. Internet-Drafts are working documents of the
Internet Engineering Task Force (IETF), its areas, and its working
groups. Note that other groups may also distribute working documents
as Internet-Drafts.
Internet-Drafts are draft documents valid for a maximum of six months
and may be updated, replaced, or obsoleted by other documents at any
time. It is inappropriate to use Internet-Drafts as reference
material or to cite them other than as "work in progress."
The list of current Internet-Drafts can be accessed at
http://www.ietf.org/1id-abstracts.html
The list of Internet-Draft Shadow Directories can be accessed at
http://www.ietf.org/shadow.html
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 open 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 length. Most of the text herein was adapted by the authors
from FIPS 180-2.
Code to perform SHA based HMACs is also included.
D. Eastlake 3rd, T. Hansen [Page 1]

INTERNET-DRAFT SHAs and HMAC-SHAs January 20061. Overview of Contents
NOTE: Much of the text below is taken from [FIPS 180-2] and
assertions therein of the security of the algorithms described are
made by the US Government, the author of [FIPS 180-2], and not by the
authors of this document.
The text below specifies Secure Hash Algorithms, SHA-224 [RFC 3874],
SHA-256, SHA-384, and SHA-512, for computing a condensed
representation of a message or a data file. (SHA-1 is specified in
[RFC 3174].) 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
or random numbers [RFC 4086].
The four algorithms specified in this document are called secure
because it is computationally infeasible to (1) find a message which
corresponds to a given message digest, or (2) to find two different
messages which 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 [RFC 3174] has also been updated to
handle input strings of arbitrary bit length. Permission is granted
for all uses, commercial and non-commercial, of this code.
Section 2 below defines the terminology and functions used as
building blocks to form these algorithms. Section 3 described the
fundamental operations on words from which these algorithms are
built. Section 4 described 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 specfication 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.
D. Eastlake 3rd, T. Hansen [Page 3]

INTERNET-DRAFT SHAs and HMAC-SHAs January 20061.1 License
Royalty free license to copy and use this software is granted
provided that this document is identified in all material mentioning
or referencing this software. Royalty free license is also granted to
make and use derivative works provided that such works are identified
as derived from this work.
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.
2. Notation for Bit Strings and Integers
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:
1010 0001 0000 0011 1111 1110 0010 0011 = A103FE23.
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.
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
D. Eastlake 3rd, T. Hansen [Page 4]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
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.
3. Operations on 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 zeroe 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.
NOT X = bitwise logical "complement" of X.
Example:
01101100101110011101001001111011
XOR 01100101110000010110100110110111
--------------------------------
= 00001001011110001011101111001100
b. The operation X + Y is defined as follows: words X and Y
represent w-bit integers x and y, where 0 <= x < 2^w and 0 <= y
< 2^w. For positive integers n and m, let
n mod m
be the remainder upon dividing n by m. Compute
z = (x + y) mod 2^w.
Then 0 <= z < 2^w. Convert z to a word, Z, and define Z = X +
Y.
c. The right shift operation SHR^n(x), where x is a w-bit word and n
is an integer with 0 <= n < w, is defined by
SHR^n(x) = x>>n
D. Eastlake 3rd, T. Hansen [Page 5]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
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:
ROTL^n(x) = ROTR^(w-x)(x)
ROTR^n(x) = ROTL^(w-n)(x)
4. Message Padding and Parsing
The hash functions specified herein are used to compute a message
digest for a message or data file that is provided as input. The
message or data file should be considered to be a bit string. The
length of the message is the number of bits in the message (the empty
message has length 0). If the number of bits in a message is a
multiple of 8, for compactness we can represent the message in hex.
The purpose of message padding is to make the total length of a
padded message a multiple of 512 for SHA-224 and SHA-256 or a
multiple of 1024 for SHA-384 and SHA-512.
The following specifies how this padding shall be performed. As a
summary, a "1" followed by m "0"s followed by a 64-bit or 128-bit
integer are appended to the end of the message to produce a padded
message of length 512*n or 1024*n. The appended integer is the
length of the original message. The padded message is then processed
by the hash function as n 512-bit or 1024-bit blocks.
4.1 SHA-224 and SHA-256
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".
D. Eastlake 3rd, T. Hansen [Page 6]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
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 which 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
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 = 407
"0"s are appended, making the total now 448. This gives the
following in hex:
61626364 65800000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000
The 64-bit representation of L = 40 is hex 00000000 00000028.
Hence the final padded message is the following hex
61626364 65800000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000028
4.2 SHA-384 and SHA-512
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 which is L in binary representation.
D. Eastlake 3rd, T. Hansen [Page 7]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
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:
61626364 65800000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
The 128-bit representation of L = 40 is hex 00000000 00000000
00000000 00000028. Hence the final padded message is the
following hex:
61626364 65800000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000028
5. Functions and Constants Used
The following subsections give the six logical functions and the
table of constants used in each of the hash functions.
5.1 SHA-224 and SHA-256
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.
D. Eastlake 3rd, T. Hansen [Page 8]

INTERNET-DRAFT SHAs and HMAC-SHAs January 20066.1 SHA-224 and SHA-256 Initialization
For SHA-224, the initial hash value, H(0), consists of the following
32-bit words in hex:
H(0)0 = c1059ed8
H(0)1 = 367cd507
H(0)2 = 3070dd17
H(0)3 = f70e5939
H(0)4 = ffc00b31
H(0)5 = 68581511
H(0)6 = 64f98fa7
H(0)7 = befa4fa4
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.
H(0)0 = 6a09e667
H(0)1 = bb67ae85
H(0)2 = 3c6ef372
H(0)3 = a54ff53a
H(0)4 = 510e527f
H(0)5 = 9b05688c
H(0)6 = 1f83d9ab
H(0)7 = 5be0cd19
6.2 SHA-224 and SHA-256 Processing
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
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
D. Eastlake 3rd, T. Hansen [Page 11]

INTERNET-DRAFT SHAs and HMAC-SHAs January 20066.3 SHA-384 and SHA-512 Initialization
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.
H(0)0 = cbbb9d5dc1059ed8
H(0)1 = 629a292a367cd507
H(0)2 = 9159015a3070dd17
H(0)3 = 152fecd8f70e5939
H(0)4 = 67332667ffc00b31
H(0)5 = 8eb44a8768581511
H(0)6 = db0c2e0d64f98fa7
H(0)7 = 47b5481dbefa4fa4
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.
H(0)0 = 6a09e667f3bcc908
H(0)1 = bb67ae8584caa73b
H(0)2 = 3c6ef372fe94f82b
H(0)3 = a54ff53a5f1d36f1
H(0)4 = 510e527fade682d1
H(0)5 = 9b05688c2b3e6c1f
H(0)6 = 1f83d9abfb41bd6b
H(0)7 = 5be0cd19137e2179
6.4 SHA-384 and SHA-512 Processing
SHA-384 and SHA-512 perform identical processing on message blocks
and differ only in how H(0) is initialized and how they produce thier
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
D. Eastlake 3rd, T. Hansen [Page 13]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
through H(N)5.
7. SHA Based HMACs
HMAC is a method for computing a keyed MAC (message authentication
code) using a hash function as described in [RFC 2104]. 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 [RFC 2104] 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.
8. C Code for SHAs
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. Section8.3 contains the C code for the hmac functions. Section 8.4 contains
a test driver to exercise the code.
For each of the digest length $$$, there are 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:
D. Eastlake 3rd, T. Hansen [Page 15]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
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 function:
Constants:
shaBadParam constant returned by USHA functions when
presented with a bad SHAversion (SHA$$$)
parameter
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
D. Eastlake 3rd, T. Hansen [Page 16]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
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.
Structures:
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.
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 RFC2104, that allows a fixed-length text input to be used.
int hmac(SHAversion whichSha,
const unsigned char *text, int text_len,
const unsigned char *key, int key_len,
uint8_t Message_Digest[USHAMaxHashSize]);
Calculate the given digest for the given text and key, and
return the resulting hash. Octets in Message_Digest beyond
USHAHashSize(whichSha) are left untouched.
8.1 The .h file
/**************************** sha.h ****************************/
#ifndef _SHA_H_
#define _SHA_H_
D. Eastlake 3rd, T. Hansen [Page 17]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
extern int hmacFinalBits(HMACContext *ctx, const uint8_t bits,
unsigned int bitcount);
extern int hmacResult(HMACContext *ctx,
uint8_t digest[USHAMaxHashSize]);
#endif /* _SHA_H_ */
8.2 The SHA Code
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 controller by an ifdef.
8.2.1 sha1.c
/**************************** sha1.c ****************************/
/*
* 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
D. Eastlake 3rd, T. Hansen [Page 23]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
* 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;
SHA1ProcessMessageBlock(context);
} else
context->Message_Block[context->Message_Block_Index++] = Pad_Byte;
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);
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);
D. Eastlake 3rd, T. Hansen [Page 29]

INTERNET-DRAFT SHAs and HMAC-SHAs January 20068.2.2 sha224-256.c
/*************************** sha224-256.c ***************************/
/*
* 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"
/* 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))))
/* Define the SHA SIGMA and sigma macros */
D. Eastlake 3rd, T. Hansen [Page 32]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
*/
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]
* 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)
D. Eastlake 3rd, T. Hansen [Page 39]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
* 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.
*
* 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.
*/
/*
* Define shift, rotate left and rotate right functions
*/
D. Eastlake 3rd, T. Hansen [Page 44]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
uint8_t Message_Digest[SHA512HashSize])
{
return SHA384_512ResultN(context, Message_Digest, SHA512HashSize);
}
/*
* 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 - 16))
context->Message_Block[context->Message_Block_Index++] = 0;
SHA384_512ProcessMessageBlock(context);
} else
context->Message_Block[context->Message_Block_Index++] = Pad_Byte;
while (context->Message_Block_Index < (SHA512_Message_Block_Size-16))
D. Eastlake 3rd, T. Hansen [Page 56]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
if (!runHmacTests) {
randomtest(hashno, hashes[hashno].randomtest,
hashes[hashno].hashsize, hashes[hashno].randomresults,
RANDOMCOUNT, printResults, printPassFail);
}
}
}
}
/* 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.
*
* 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
D. Eastlake 3rd, T. Hansen [Page 98]

INTERNET-DRAFT SHAs and HMAC-SHAs January 20069. IANA Considerations
None.
10. Security Considerations
This document is intended to provide convenient open source access by
the Internet community to the United States of America Federal
Information Processing Standard Secure Hash Algorithms (SHAs) [FIPS
180-2] and HMACs based thereon. No independent assertion of the
security of this hash function by the authors for any particular use
is intended.
D. Eastlake 3rd, T. Hansen [Page 101]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
Author's Address
Donald E. Eastlake, 3rd
Motorola Laboratories
155 Beaver Street
Milford, MA 01757 USA
Telephone: +1-508-786-7554 (w)
EMail: donald.eastlake@motorola.com
Tony Hansen
AT&T Laboratories
200 Laurel Ave.
Middletown, NJ 07748 USA
Telephone: +1-732-420-8934 (w)
Email: tony+shs@millennium.att.com
Additional IPR Provisions
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.
D. Eastlake 3rd, T. Hansen [Page 103]

INTERNET-DRAFT SHAs and HMAC-SHAs January 2006
Expiration and File Name
This draft expires July 2006.
Its file name is draft-eastlake-sha2-02.txt.
D. Eastlake 3rd, T. Hansen [Page 104]