Skip to content

Instantly share code, notes, and snippets.

@0xWDG
Created June 10, 2024 14:42
Show Gist options
  • Save 0xWDG/4363dea81e7925308087d52174a79fd6 to your computer and use it in GitHub Desktop.
Save 0xWDG/4363dea81e7925308087d52174a79fd6 to your computer and use it in GitHub Desktop.
cryptoKit OTP
import CryptoKit
import CommonCrypto
import Foundation
let period = TimeInterval(30)
let digits = 6
let secret = base32Decode(value: "5FAA5JZ7WHO5WDNN")! // Change this.
var counter = UInt64(Date().timeIntervalSince1970 / period).bigEndian
func cryptoKitOTP() {
// Generate the key based on the counter.
let key = SymmetricKey(data: Data(bytes: &counter, count: MemoryLayout.size(ofValue: counter)))
let hash = HMAC<Insecure.SHA1>.authenticationCode(for: secret, using: key)
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("CryptoKit OTP value: \(String(format: "%0*u", digits, truncatedHash))")
}
cryptoKitOTP()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment