Last active
November 21, 2019 19:35
-
-
Save gonzula/6457567c005efcda25fd3ed0637750e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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