-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathHMACCommonCrypto.swift
More file actions
48 lines (39 loc) · 1.19 KB
/
HMACCommonCrypto.swift
File metadata and controls
48 lines (39 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import Foundation
import CommonCrypto
extension HMACAlgorithm: SignAlgorithm, VerifyAlgorithm {
public func sign(_ message: Data) -> Data {
let context = UnsafeMutablePointer<CCHmacContext>.allocate(capacity: 1)
defer { context.deallocate() }
key.withUnsafeBytes() { (buffer: UnsafePointer<UInt8>) in
CCHmacInit(context, hash.commonCryptoAlgorithm, buffer, size_t(key.count))
}
message.withUnsafeBytes { (buffer: UnsafePointer<UInt8>) in
CCHmacUpdate(context, buffer, size_t(message.count))
}
var hmac = Array<UInt8>(repeating: 0, count: Int(hash.commonCryptoDigestLength))
CCHmacFinal(context, &hmac)
return Data(hmac)
}
}
extension HMACAlgorithm.Hash {
var commonCryptoAlgorithm: CCHmacAlgorithm {
switch self {
case .sha256:
return CCHmacAlgorithm(kCCHmacAlgSHA256)
case .sha384:
return CCHmacAlgorithm(kCCHmacAlgSHA384)
case .sha512:
return CCHmacAlgorithm(kCCHmacAlgSHA512)
}
}
var commonCryptoDigestLength: Int32 {
switch self {
case .sha256:
return CC_SHA256_DIGEST_LENGTH
case .sha384:
return CC_SHA384_DIGEST_LENGTH
case .sha512:
return CC_SHA512_DIGEST_LENGTH
}
}
}