SHA-1: Difference between revisions

387 bytes removed ,  4 months ago
m
(New post directly implementing the algorithm. In addition to an existing post which calls a built in language feature.)
m (→‎{{header|Wren}}: Minor tidy)
 
(2 intermediate revisions by one other user not shown)
Line 1,175:
public:
std::string message_digest(const std::string& message) {
std::vector<int64_tuint32_t> state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 };
 
const std::vector<int8_t> bytes = add_padding(message);
for ( uint64_t i = 0; i < bytes.size() / BLOCK_LENGTH; ++i ) {
std::vector<int32_tuint32_t> values(80, 0);
for ( uint32_t j = 0; j < BLOCK_LENGTH; ++j ) {
values[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 );
}
for ( uint32_t j = 16; j < 80; ++j ) {
int32_tuint32_t value = values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16];
values[j] = std::rotl(static_cast<uint32_t>(value), 1);
}
 
int32_tuint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4];
int32_tuint32_t f = 0, k = 0;
for ( uint32_t j = 0; j < 80; ++j ) {
switch ( j / 20 ) {
case 0 : { f = ( b & c ) | ( ~b & d ); k = 0x5a827999; break; }
case 1 : { f = b ^ c ^ d; k = 0x6ed9eba1; break; }
case 2 : { f = ( b & c ) | ( b & d ) | ( c & d ); k = 0x8f1bbcdc; break; }
case 3 : { f = b ^ c ^ d; k = 0xca62c1d6; break; }
}
 
int32_tuint32_t temp = std::rotl(static_cast<uint32_t>(a), 5) + f + e + k + values[j];
e = d; d = c; c = std::rotl(static_cast<uint32_t>(b), 30); b = a; a = temp;
}
 
Line 1,207:
std::stringstream stream;
for ( uint32_t i = 0; i < 20; ++i ) {
int8_t byte_value = static_cast<int8_t>(unsigned_right_shift(state[i / 4], >> ( 24 - ( i % 4 ) * 8 ));
stream << std::setfill('0') << std::setw(2) << std::hex << ( byte_value & 0xFF0xff );
}
return stream.str();
Line 1,229:
}
return bytes;
}
 
int32_t unsigned_right_shift(const int32_t& base, const int32_t& shift) {
if ( shift < 0 || shift >= 32 ) {
throw std::invalid_argument("Shift must be in the range 0..31: " + shift);
}
if ( base == 0 ) {
return 0;
}
return ( base > 0 ) ? base >> shift : static_cast<uint32_t>(base) >> shift;
}
 
Line 3,163 ⟶ 3,153:
{{libheader|Wren-crypto}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./crypto" for Sha1
import "./fmt" for Fmt
var strings = [
9,485

edits