23 const std::string
SHA::sha1(
const std::string& data )
43 Message_Block_Index = 0;
68 for(
int i = 0; i < 20; ++i )
69 sprintf( buf + i * 2,
"%02x", (
unsigned char)( H[i >> 2] >> ( ( 3 - ( i & 3 ) ) << 3 ) ) );
71 return std::string( buf, 40 );
79 unsigned char digest[20];
80 for(
int i = 0; i < 20; ++i )
81 digest[i] = (
unsigned char)( H[i >> 2] >> ( ( 3 - ( i & 3 ) ) << 3 ) );
83 return std::string( (
char*)digest, 20 );
95 void SHA::feed(
const unsigned char* data,
unsigned length )
100 if( m_finished || m_corrupted )
106 while( length-- && !m_corrupted )
108 Message_Block[Message_Block_Index++] = ( *data & 0xFF );
111 Length_Low &= 0xFFFFFFFF;
112 if( Length_Low == 0 )
115 Length_High &= 0xFFFFFFFF;
116 if( Length_High == 0 )
122 if( Message_Block_Index == 64 )
133 feed( (
const unsigned char*)data.c_str(), (int)data.length() );
138 const unsigned K[] = { 0x5A827999,
146 unsigned A, B, C, D, E;
148 for( t = 0; t < 16; t++ )
150 W[t] = ((unsigned) Message_Block[t * 4]) << 24;
151 W[t] |= ((unsigned) Message_Block[t * 4 + 1]) << 16;
152 W[t] |= ((unsigned) Message_Block[t * 4 + 2]) << 8;
153 W[t] |= ((unsigned) Message_Block[t * 4 + 3]);
156 for( t = 16; t < 80; ++t )
158 W[t] = shift( 1, W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16] );
167 for( t = 0; t < 20; ++t )
169 temp = shift( 5, A ) + ( ( B & C ) | ( ( ~B ) & D ) ) + E + W[t] + K[0];
178 for( t = 20; t < 40; ++t )
180 temp = shift( 5, A ) + ( B ^ C ^ D ) + E + W[t] + K[1];
189 for( t = 40; t < 60; ++t )
191 temp = shift( 5, A ) + ( ( B & C ) | ( B & D ) | ( C & D ) ) + E + W[t] + K[2];
200 for( t = 60; t < 80; ++t )
202 temp = shift( 5, A ) + ( B ^ C ^ D ) + E + W[t] + K[3];
211 H[0] = ( H[0] + A ) & 0xFFFFFFFF;
212 H[1] = ( H[1] + B ) & 0xFFFFFFFF;
213 H[2] = ( H[2] + C ) & 0xFFFFFFFF;
214 H[3] = ( H[3] + D ) & 0xFFFFFFFF;
215 H[4] = ( H[4] + E ) & 0xFFFFFFFF;
217 Message_Block_Index = 0;
222 Message_Block[Message_Block_Index++] = 0x80;
224 if( Message_Block_Index > 56 )
226 while( Message_Block_Index < 64 )
228 Message_Block[Message_Block_Index++] = 0;
234 while( Message_Block_Index < 56 )
236 Message_Block[Message_Block_Index++] = 0;
239 Message_Block[56] =
static_cast<unsigned char>( ( Length_High >> 24 ) & 0xFF );
240 Message_Block[57] =
static_cast<unsigned char>( ( Length_High >> 16 ) & 0xFF );
241 Message_Block[58] =
static_cast<unsigned char>( ( Length_High >> 8 ) & 0xFF );
242 Message_Block[59] =
static_cast<unsigned char>( ( Length_High ) & 0xFF );
243 Message_Block[60] =
static_cast<unsigned char>( ( Length_Low >> 24 ) & 0xFF );
244 Message_Block[61] =
static_cast<unsigned char>( ( Length_Low >> 16 ) & 0xFF );
245 Message_Block[62] =
static_cast<unsigned char>( ( Length_Low >> 8 ) & 0xFF );
246 Message_Block[63] =
static_cast<unsigned char>( ( Length_Low ) & 0xFF );
252 unsigned SHA::shift(
int bits,
unsigned word )
254 return ( ( word << bits ) & 0xFFFFFFFF) | ( ( word & 0xFFFFFFFF ) >> ( 32-bits ) );