Kaynağa Gözat

[HMAC] Support SHA384 and SHA512

Kyle Fuller 10 yıl önce
ebeveyn
işleme
77b2318146
2 değiştirilmiş dosya ile 29 ekleme ve 2 silme
  1. 11 2
      CryptoSwift/HMAC.swift
  2. 18 0
      CryptoSwiftTests/HMACTests.swift

+ 11 - 2
CryptoSwift/HMAC.swift

@@ -11,7 +11,7 @@ import Foundation
 public class HMAC {
     
     public enum Variant {
-        case sha1, sha256, md5
+        case sha1, sha256, sha384, sha512, md5
         
         func calculateHash(# bytes:[UInt8]) -> [UInt8]? {
             switch (self) {
@@ -19,13 +19,22 @@ public class HMAC {
                 return NSData.withBytes(bytes).sha1()?.bytes()
             case .sha256:
                 return NSData.withBytes(bytes).sha256()?.bytes()
+            case .sha384:
+                return NSData.withBytes(bytes).sha384()?.bytes()
+            case .sha512:
+                return NSData.withBytes(bytes).sha512()?.bytes()
             case .md5:
                 return NSData.withBytes(bytes).md5()?.bytes();
             }
         }
         
         func blockSize() -> Int {
-            return 64
+            switch self {
+            case .md5, .sha1, .sha256:
+                return 64
+            case .sha384, .sha512:
+                return 128
+            }
         }
     }
     

+ 18 - 0
CryptoSwiftTests/HMACTests.swift

@@ -48,4 +48,22 @@ class HMACTests: XCTestCase {
         XCTAssertEqual(hmac!, NSData.withBytes(expectedMac), "Invalid authentication result")
     }
 
+    func testSHA384() {
+        let key:[UInt8] = []
+        let msg:[UInt8] = []
+        let expectedMac:[UInt8] = [0x6c, 0x1f, 0x2e, 0xe9, 0x38, 0xfa, 0xd2, 0xe2, 0x4b, 0xd9, 0x12, 0x98, 0x47, 0x43, 0x82, 0xca, 0x21, 0x8c, 0x75, 0xdb, 0x3d, 0x83, 0xe1, 0x14, 0xb3, 0xd4, 0x36, 0x77, 0x76, 0xd1, 0x4d, 0x35, 0x51, 0x28, 0x9e, 0x75, 0xe8, 0x20, 0x9c, 0xd4, 0xb7, 0x92, 0x30, 0x28, 0x40, 0x23, 0x4a, 0xdc]
+
+        let hmac = Authenticator.HMAC(key: NSData.withBytes(key), variant: .sha384).authenticate(NSData.withBytes(msg))
+        XCTAssertEqual(hmac!, NSData.withBytes(expectedMac), "Invalid authentication result")
+    }
+
+    func testSHA512() {
+        let key:[UInt8] = []
+        let msg:[UInt8] = []
+        let expectedMac:[UInt8] = [0xb9, 0x36, 0xce, 0xe8, 0x6c, 0x9f, 0x87, 0xaa, 0x5d, 0x3c, 0x6f, 0x2e, 0x84, 0xcb, 0x5a, 0x42, 0x39, 0xa5, 0xfe, 0x50, 0x48, 0x0a, 0x6e, 0xc6, 0x6b, 0x70, 0xab, 0x5b, 0x1f, 0x4a, 0xc6, 0x73, 0x0c, 0x6c, 0x51, 0x54, 0x21, 0xb3, 0x27, 0xec, 0x1d, 0x69, 0x40, 0x2e, 0x53, 0xdf, 0xb4, 0x9a, 0xd7, 0x38, 0x1e, 0xb0, 0x67, 0xb3, 0x38, 0xfd, 0x7b, 0x0c, 0xb2, 0x22, 0x47, 0x22, 0x5d, 0x47]
+
+        let hmac = Authenticator.HMAC(key: NSData.withBytes(key), variant: .sha512).authenticate(NSData.withBytes(msg))
+        XCTAssertEqual(hmac!, NSData.withBytes(expectedMac), "Invalid authentication result")
+    }
+
 }