41 lines
1.1 KiB
Swift
41 lines
1.1 KiB
Swift
|
//
|
||
|
// Message+Extensions.swift
|
||
|
// Sesame
|
||
|
//
|
||
|
// Created by CH on 08.04.22.
|
||
|
//
|
||
|
|
||
|
import Foundation
|
||
|
import CryptoKit
|
||
|
|
||
|
extension Message {
|
||
|
|
||
|
static var length: Int {
|
||
|
SHA256Digest.byteCount + Content.length
|
||
|
}
|
||
|
|
||
|
init<T: Sequence>(decodeFrom data: T) where T.Element == UInt8 {
|
||
|
let count = SHA256Digest.byteCount
|
||
|
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
|
||
|
}
|
||
|
}
|