Skip to content

Instantly share code, notes, and snippets.

@gonzula
Last active November 21, 2019 19:35
Show Gist options
  • Save gonzula/6457567c005efcda25fd3ed0637750e8 to your computer and use it in GitHub Desktop.
Save gonzula/6457567c005efcda25fd3ed0637750e8 to your computer and use it in GitHub Desktop.
import CommonCrypto
func otp() -> String {
let secret = Data() // change this
let now = Date().timeIntervalSince1970
let count = Int(now) / 30
var fixedCounter = NSSwapHostLongLongToBig(UInt64(count))
let hash = malloc(1000)!
defer {free(hash)}
var ctx = CCHmacContext()
CCHmacInit(&ctx, CCHmacAlgorithm(kCCHmacAlgSHA1), (secret as NSData).bytes, secret.count)
CCHmacUpdate(&ctx, &fixedCounter, MemoryLayout<UInt64>.size)
CCHmacFinal(&ctx, hash)
let offset: CChar = hash.advanced(by: 20-1).bindMemory(to: CChar.self, capacity: 1).pointee & 0x0f
let truncatedHash = NSSwapBigIntToHost(
hash.advanced(by: Int(offset)).bindMemory(to: UInt32.self, capacity: 1).pointee) & 0x7fffffff
let pin = String(format: "%06u", truncatedHash % 1000000)
return pin
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment