Skip to content

Commit

Permalink
feat: add HKDF key derivation and HMAC signature generation
Browse files Browse the repository at this point in the history
  • Loading branch information
kele-leanes committed Jan 25, 2024
1 parent a60d655 commit e269e40
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion Sources/XMTP/Crypto.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<SHA256>.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<SHA256>.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)
}
}

0 comments on commit e269e40

Please sign in to comment.