今天在swift组件模块化的时候,有一个生成动态口令的功能,发现使用的谷歌的OC类,很是不爽。
于是就自己写一个了一个动态口令解密的代码
原来旧代码展示:
let gtmString = GTMStringEncoding()
let secretData = gtmString.base32Decode(keyString)
let generator = TOTPGenerator.init(secret: secretData, algorithm: "SHA1", digits: 6, period: TOTPGenerator.defaultPeriod())
let str = generator?.generateOTP(for: Date())
我们采用swift OneTimePassword
pod引入
pod 'OneTimePassword'
swift TOTPGenerator的实现
import OneTimePassword
class TOTPGenerator {
private var totpGenerator: Generator?
init?(secret: Data) {
guard let generator = Generator(
factor: .timer(period: 30),
secret: secret,
algorithm: .sha1,
digits: 6) else {
return nil
}
self.totpGenerator = generator
}
func generateOTP(for date: Date = Date()) -> String? {
guard let generator = self.totpGenerator else { return nil }
do {
let password = try generator.password(at: date)
return password
} catch {
return nil
}
}
}
最后使用方法改完之后的新代码:
guard let secretData = base32Decode(keyString) else { return }
let generator = TOTPGenerator(secret: secretData)
let str = generator?.generateOTP(for: Date())
运行正常显示完成
网友评论