Skip to content

Commit

Permalink
LibCrypto: Correctly pad blocks with FinalBlockSize < size < BlockSize
Browse files Browse the repository at this point in the history
This fixes SerenityOS#2488
  • Loading branch information
alimpfard authored and awesomekling committed Jun 4, 2020
1 parent a3f5108 commit 63cc2f5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
11 changes: 10 additions & 1 deletion Libraries/LibCrypto/Hash/SHA1.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -115,17 +115,26 @@ SHA1::DigestType SHA1::peek()
__builtin_memcpy(data, m_data_buffer, m_data_length);
__builtin_memcpy(state, m_state, 20);

if (BlockSize == m_data_length) {
transform(m_data_buffer);
m_bit_length += BlockSize * 8;
m_data_length = 0;
i = 0;
}

if (m_data_length < FinalBlockDataSize) {
m_data_buffer[i++] = 0x80;
while (i < FinalBlockDataSize)
m_data_buffer[i++] = 0x00;

} else {
// First, complete a block with some padding.
m_data_buffer[i++] = 0x80;
while (i < BlockSize)
m_data_buffer[i++] = 0x00;

transform(m_data_buffer);

// Then start another block with BlockSize - 8 bytes of zeros
__builtin_memset(m_data_buffer, 0, FinalBlockDataSize);
}

Expand Down
22 changes: 20 additions & 2 deletions Libraries/LibCrypto/Hash/SHA2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,26 @@ SHA256::DigestType SHA256::peek()
DigestType digest;
size_t i = m_data_length;

if (BlockSize == m_data_length) {
transform(m_data_buffer);
m_bit_length += BlockSize * 8;
m_data_length = 0;
i = 0;
}

if (m_data_length < FinalBlockDataSize) {
m_data_buffer[i++] = 0x80;
while (i < FinalBlockDataSize)
m_data_buffer[i++] = 0x00;

} else {
// First, complete a block with some padding.
m_data_buffer[i++] = 0x80;
while (i < BlockSize)
m_data_buffer[i++] = 0x00;

transform(m_data_buffer);

// Then start another block with BlockSize - 8 bytes of zeros
__builtin_memset(m_data_buffer, 0, FinalBlockDataSize);
}

Expand Down Expand Up @@ -218,17 +227,26 @@ SHA512::DigestType SHA512::peek()
DigestType digest;
size_t i = m_data_length;

if (BlockSize == m_data_length) {
transform(m_data_buffer);
m_bit_length += BlockSize * 8;
m_data_length = 0;
i = 0;
}

if (m_data_length < FinalBlockDataSize) {
m_data_buffer[i++] = 0x80;
while (i < FinalBlockDataSize)
m_data_buffer[i++] = 0x00;

} else {
// First, complete a block with some padding.
m_data_buffer[i++] = 0x80;
while (i < BlockSize)
m_data_buffer[i++] = 0x00;

transform(m_data_buffer);

// Then start another block with BlockSize - 8 bytes of zeros
__builtin_memset(m_data_buffer, 0, FinalBlockDataSize);
}

Expand Down

0 comments on commit 63cc2f5

Please sign in to comment.