2022-04-09 17:43:33 +02:00
|
|
|
import Foundation
|
2022-04-13 14:55:22 +02:00
|
|
|
|
|
|
|
#if canImport(CryptoKit)
|
2022-04-09 17:43:33 +02:00
|
|
|
import CryptoKit
|
2022-04-13 14:55:22 +02:00
|
|
|
#else
|
|
|
|
import Crypto
|
|
|
|
#endif
|
2022-04-09 17:43:33 +02:00
|
|
|
|
|
|
|
extension Message {
|
|
|
|
|
|
|
|
static var length: Int {
|
2022-04-13 14:55:22 +02:00
|
|
|
SHA256.byteCount + Content.length
|
2022-04-09 17:43:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
init<T: Sequence>(decodeFrom data: T) where T.Element == UInt8 {
|
2022-04-13 14:55:22 +02:00
|
|
|
let count = SHA256.byteCount
|
2022-04-09 17:43:33 +02:00
|
|
|
self.mac = Data(data.prefix(count))
|
|
|
|
self.content = .init(decodeFrom: Array(data.dropFirst(count)))
|
|
|
|
}
|
|
|
|
|
|
|
|
func isValid(using key: SymmetricKey) -> Bool {
|
|
|
|
HMAC<SHA256>.isValidAuthenticationCode(mac, authenticating: content.encoded, using: key)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
extension Message.Content {
|
|
|
|
|
|
|
|
func authenticate(using key: SymmetricKey) -> Message {
|
|
|
|
let mac = HMAC<SHA256>.authenticationCode(for: encoded, using: key)
|
|
|
|
return .init(mac: Data(mac.map { $0 }), content: self)
|
|
|
|
}
|
|
|
|
|
|
|
|
func authenticateAndSerialize(using key: SymmetricKey) -> Data {
|
|
|
|
let encoded = self.encoded
|
|
|
|
let mac = HMAC<SHA256>.authenticationCode(for: encoded, using: key)
|
|
|
|
return Data(mac.map { $0 }) + encoded
|
|
|
|
}
|
|
|
|
}
|