Posts

Post not yet marked as solved
2 Replies
Hi @aruffin! The digest can just be produced by invoking the hash function, this can be done in the following way: let digest = SHA256.hash(data: data) Can you explain why it would not be possible for you to re-hash the data? Blindly signing hashes can be concerning from a security perspective as the signer does not validate the data that is signed as part of the hash.
Post marked as solved
7 Replies
Hello Craig,The code was almost right, it seems you just swapped the key and data field from the TOTP spec.Here's the fixed code:I changed the serialization of the key to base64 above as I was missing your dependency for base32.I swapped the inputs to the HMAC code and adjusted to get the right types for each of the inputs.Hope this fixes it!import CryptoKit import Foundation let period = TimeInterval(30) let digits = 6 let secret = Data(base64Encoded: "6UAOpz+x3dsNrQ==")! var counter = UInt64(Date().timeIntervalSince1970 / period).bigEndian func cryptoKitOTPFixed() { let counterData = withUnsafeBytes(of: &counter) { Array($0) } let hash = HMAC<Insecure.SHA1>.authenticationCode(for: counterData, using: SymmetricKey(data: secret)) var truncatedHash = hash.withUnsafeBytes { ptr -> UInt32 in let offset = ptr[hash.byteCount - 1] & 0x0f let truncatedHashPtr = ptr.baseAddress! + Int(offset) return truncatedHashPtr.bindMemory(to: UInt32.self, capacity: 1).pointee } truncatedHash = UInt32(bigEndian: truncatedHash) truncatedHash = truncatedHash & 0x7FFF_FFFF truncatedHash = truncatedHash % UInt32(pow(10, Float(digits))) print("CryptoKitFixed OTP value: \(String(format: "%0*u", digits, truncatedHash))") }