浏览代码

Fixes bitPadding() #363

Marcin Krzyżanowski 8 年之前
父节点
当前提交
bf035decc5
共有 2 个文件被更改,包括 13 次插入6 次删除
  1. 7 4
      Sources/CryptoSwift/Utils.swift
  2. 6 2
      Tests/CryptoSwiftTests/DigestTests.swift

+ 7 - 4
Sources/CryptoSwift/Utils.swift

@@ -70,14 +70,17 @@ func xor(_ a: Array<UInt8>, _ b:Array<UInt8>) -> Array<UInt8> {
  */
 @inline(__always)
 func bitPadding(to data: inout Array<UInt8>, blockSize: Int, allowance: Int = 0) {
+    let msgLength = data.count
     // Step 1. Append Padding Bits
     // append one bit (UInt8 with one bit) to message
     data.append(0x80)
 
     // Step 2. append "0" bit until message length in bits ≡ 448 (mod 512)
-    let msgLength = data.count
-    let max = blockSize &- allowance
-    let l = msgLength % blockSize
+    let max = blockSize - allowance // 448, 986
+    if msgLength % blockSize < max { // 448
+        data += Array<UInt8>(repeating: 0, count: max - 1 - (msgLength % blockSize))
+    } else {
+        data += Array<UInt8>(repeating: 0, count: blockSize + max - 1 - (msgLength % blockSize))
+    }
 
-    data += Array<UInt8>(repeating: 0, count: (l >= max ? blockSize : 0) &+ max &- l)
 }

+ 6 - 2
Tests/CryptoSwiftTests/DigestTests.swift

@@ -43,12 +43,16 @@ final class DigestTests: XCTestCase {
     }
 
     func testSHA1() {
-        let data:Data = Data(bytes: UnsafePointer<UInt8>([0x31, 0x32, 0x33] as Array<UInt8>), count: 3)
-        XCTAssertEqual(data.sha1().toHexString(), "40bd001563085fc35165329ea1ff5c5ecbdbbeef", "SHA1 calculation failed");
+        XCTAssertEqual([0x31, 0x32, 0x33].sha1().toHexString(), "40bd001563085fc35165329ea1ff5c5ecbdbbeef", "SHA1 calculation failed");
 
         XCTAssertEqual("abc".sha1(), "a9993e364706816aba3e25717850c26c9cd0d89d", "SHA1 calculation failed")
         XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha1(), "84983e441c3bd26ebaae4aa1f95129e5e54670f1", "SHA1 calculation failed")
         XCTAssertEqual("".sha1(), "da39a3ee5e6b4b0d3255bfef95601890afd80709", "SHA1 calculation failed")
+
+        // https://github.com/krzyzanowskim/CryptoSwift/issues/363
+        XCTAssertEqual("1477304791&1XpnGSRhOlZz2etXMeOdfNaHILTjW16U&8mpBBbzwsgs".sha1(), "0809bbf8489c594131c2030a84be364a0851a635", "Failed")
+        XCTAssertEqual("1477304791&1XpnGSRhOlZz2etXMeOdfNaHILTjW16U&8mpBBbzwsgsa".sha1(), "d345b525ebada7becc8107c54e07fa88644471f5", "Failed")
+        XCTAssertEqual("1477304791&1XpnGSRhOlZz2etXMeOdfNaHILTjW16U&8mpBBbzwsg".sha1(), "c106aa0a98606294ee35fd2d937e928ebb5339e0", "Failed")
     }
 
     func testSHA224() {