From e269e409bd72999007aaa69a144e43565e56d2f4 Mon Sep 17 00:00:00 2001 From: kele-leanes Date: Thu, 25 Jan 2024 15:26:47 -0300 Subject: [PATCH] feat: add HKDF key derivation and HMAC signature generation --- Sources/XMTP/Crypto.swift | 40 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/Sources/XMTP/Crypto.swift b/Sources/XMTP/Crypto.swift index 6b3fdd65..4f3e7126 100644 --- a/Sources/XMTP/Crypto.swift +++ b/Sources/XMTP/Crypto.swift @@ -8,7 +8,7 @@ import Foundation public typealias CipherText = Xmtp_MessageContents_Ciphertext enum CryptoError: Error { - case randomBytes, combinedPayload + case randomBytes, combinedPayload, keyDerivationError, hmacSignatureError } enum Crypto { @@ -103,4 +103,42 @@ enum Crypto { throw CryptoError.randomBytes } } + + static func hkdfHmacKey(secret: Data, info: Data) throws -> SymmetricKey { + do { + let salt = try secureRandomBytes(count: 32) + let key = HKDF.deriveKey( + inputKeyMaterial: SymmetricKey(data: secret), + salt: salt, + info: info, + outputByteCount: 32) + return key + } catch { + throw CryptoError.keyDerivationError + } + } + + static func generateHmacSignature(secret: Data, info: Data, message: Data) throws -> Data { + do { + let key = try hkdfHmacKey(secret: secret, info: info) + let signature = HMAC.authenticationCode(for: message, using: key) + return Data(signature) + } catch { + throw CryptoError.hmacSignatureError + } + } + + static func exportHmacKey(key: SymmetricKey) -> Data { + var exportedData = Data(count: key.bitCount / 8) + exportedData.withUnsafeMutableBytes { buffer in + key.withUnsafeBytes { keyBuffer in + buffer.copyMemory(from: keyBuffer) + } + } + return exportedData + } + + static func importHmacKey(keyData: Data) -> SymmetricKey { + return SymmetricKey(data: keyData) + } }