Skip to content

Commit b2d803e

Browse files
committed
[Basic] Fix the SHA256 padding function
The padding function wasn't written correctly to handle cases when mod of input length was greater than 448.
1 parent 7502ddf commit b2d803e

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

Sources/Basic/SHA256.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ public final class SHA256 {
174174
//
175175
// inputBitLength + 1 + bitsToAppend ≡ 448 mod 512
176176
let mod = inputBitLength % 512
177-
let bitsToAppend = mod == 448 ? 512 : 448 - mod - 1
177+
let bitsToAppend = mod < 448 ? 448 - 1 - mod : 512 + 448 - mod - 1
178178

179179
// We already appended first 7 bits with 0x80 above.
180180
input += [UInt8](repeating: 0, count: (bitsToAppend - 7) / 8)

Tests/BasicTests/SHA256Tests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,14 @@ class SHA256Tests: XCTestCase {
3737
XCTAssertEqual(SHA256(stream.bytes).digestString(), "23d00697ba26b4140869bab958431251e7e41982794d41b605b6a1d5dee56abf")
3838
}
3939

40+
func testLargeData() {
41+
let data: [UInt8] = (0..<1788).map { _ in 0x03 }
42+
let digest = SHA256(data).digestString()
43+
XCTAssertEqual(digest, "907422e2f24d749d0add2b504ccae8ad1aa392477591905880fb2dc494e33d63")
44+
}
45+
4046
static var allTests = [
4147
("testBasics", testBasics),
48+
("testLargeData", testLargeData),
4249
]
4350
}

0 commit comments

Comments
 (0)