├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Package.swift ├── README.md └── Sources └── OTP ├── Extensions ├── ArrayExtension.swift ├── DataExtension.swift └── UInt64Extension.swift ├── OTP.swift └── OTPAlgorithm.swift /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [sparrowcode] 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: ivanvorobei, svyatoynick 7 | --- 8 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: ivanvorobei, svyatoynick 7 | --- 8 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Goal 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # macOS Files 2 | .DS_Store 3 | .Trashes 4 | 5 | # Swift Package Manager 6 | .swiftpm 7 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | hello@ivanvorobei.io. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Here provided info about contribution process and recommendations. 4 | 5 | ## Codestyle 6 | 7 | ### Marks 8 | 9 | For clean struct code good is using marks. 10 | 11 | ```swift 12 | class Example { 13 | 14 | // MARK: - Init 15 | 16 | init() {} 17 | } 18 | ``` 19 | 20 | Here you find all which using in project: 21 | 22 | - // MARK: - Init 23 | - // MARK: - Lifecycle 24 | - // MARK: - Layout 25 | - // MARK: - Public 26 | - // MARK: - Private 27 | - // MARK: - Internal 28 | - // MARK: - Models 29 | - // MARK: - Ovveride 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Sparrow Code 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.3 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "OTP", 7 | platforms: [ 8 | .iOS(.v13), 9 | .tvOS(.v13), 10 | .watchOS(.v6) 11 | ], 12 | products: [ 13 | .library( 14 | name: "OTP", 15 | targets: ["OTP"] 16 | ) 17 | ], 18 | dependencies: [], 19 | targets: [ 20 | .target( 21 | name: "OTP", 22 | swiftSettings: [ 23 | .define("OTP_SPM") 24 | ] 25 | ) 26 | ], 27 | swiftLanguageVersions: [.v5] 28 | ) 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # One Time Password 2 | 3 |

4 | 5 | 6 | 7 | 8 | 9 | 10 |

11 | 12 | ## Navigate 13 | 14 | - [Installation](#installation) 15 | - [Swift Package Manager](#swift-package-manager) 16 | - [CocoaPods](#cocoapods) 17 | - [Manually](#manually) 18 | - [Usage](#usage) 19 | - [Apps Using](#apps-using) 20 | 21 | ## Installation 22 | 23 | Ready to use on iOS 13+, tvOS 13+ & watchOS 6+ 24 | 25 | ### Swift Package Manager 26 | 27 | In Xcode go to `File` -> `Packages` -> `Update to Latest Package Versions` and insert url: 28 | 29 | ``` 30 | https://github.com/sparrowcode/OTP 31 | ``` 32 | 33 | or adding it to the `dependencies` value of your `Package.swift`: 34 | 35 | ```swift 36 | dependencies: [ 37 | .package(url: "https://github.com/sparrowcode/OTP", .upToNextMajor(from: "1.0.0")) 38 | ] 39 | ``` 40 | 41 | ### CocoaPods: 42 | 43 | Specify it in your `Podfile`: 44 | 45 | ```ruby 46 | pod 'OTP' 47 | ``` 48 | 49 | ### Manually 50 | 51 | If you prefer not to use any of dependency managers, you can integrate manually. Put `Sources/OTP` folder in your Xcode project. Make sure to enable `Copy items if needed` and `Create groups`. 52 | 53 | ## Usage 54 | 55 | ```swift 56 | // With default parametrs 57 | let password = OTP.generateOTP(secret: "secret") 58 | 59 | // With custom values 60 | let password = OTP.generateOTP(secret: "secret", algorithm: OTPAlgorithm = .sha1, expirationTimeInSeconds: Int = 30, digits: Int = 6) 61 | ``` 62 | 63 | ## Apps Using 64 | 65 |

66 | 67 |

68 | 69 | If you use a `OTP`, add your application via Pull Request. 70 | -------------------------------------------------------------------------------- /Sources/OTP/Extensions/ArrayExtension.swift: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // Copyright © 2022 Sparrow Code LTD (https://sparrowcode.io, hello@sparrowcode.io) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in all 12 | // copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | // SOFTWARE. 21 | 22 | import Foundation 23 | 24 | extension Array where Element == UInt8 { 25 | 26 | init(reserveCapacity: Int) { 27 | self = Array() 28 | self.reserveCapacity(reserveCapacity) 29 | } 30 | 31 | public init(hex: String) { 32 | self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount) 33 | var buffer: UInt8? 34 | var skip = hex.hasPrefix("0x") ? 2 : 0 35 | for char in hex.unicodeScalars.lazy { 36 | guard skip == 0 else { 37 | skip -= 1 38 | continue 39 | } 40 | 41 | guard char.value >= 48 && char.value <= 102 else { 42 | removeAll() 43 | return 44 | } 45 | let v: UInt8 46 | let c: UInt8 = UInt8(char.value) 47 | 48 | switch c { 49 | case let c where c <= 57: 50 | v = c - 48 51 | case let c where c >= 65 && c <= 70: 52 | v = c - 55 53 | case let c where c >= 97: 54 | v = c - 87 55 | default: 56 | removeAll() 57 | return 58 | } 59 | 60 | if let b = buffer { 61 | append(b << 4 | v) 62 | buffer = nil 63 | } else { 64 | buffer = v 65 | } 66 | } 67 | 68 | if let b = buffer { 69 | append(b) 70 | } 71 | } 72 | 73 | public func toHexString() -> String { 74 | `lazy`.reduce(into: "") { 75 | var s = String($1, radix: 16) 76 | if s.count == 1 { 77 | s = "0" + s 78 | } 79 | $0 += s 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Sources/OTP/Extensions/DataExtension.swift: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // Copyright © 2022 Sparrow Code LTD (https://sparrowcode.io, hello@sparrowcode.io) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in all 12 | // copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | // SOFTWARE. 21 | 22 | import Foundation 23 | 24 | extension Data { 25 | 26 | public init(hex: String) { 27 | self.init(Array(hex: hex)) 28 | } 29 | 30 | public var bytes: Array { 31 | return Array(self) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Sources/OTP/Extensions/UInt64Extension.swift: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // Copyright © 2022 Sparrow Code LTD (https://sparrowcode.io, hello@sparrowcode.io) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in all 12 | // copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | // SOFTWARE. 21 | 22 | import Foundation 23 | 24 | extension UInt64 { 25 | 26 | var data: Data { 27 | var int = self 28 | let intData = Data(bytes: &int, count: MemoryLayout.size(ofValue: self)) 29 | return intData 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Sources/OTP/OTP.swift: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // Copyright © 2022 Sparrow Code LTD (https://sparrowcode.io, hello@sparrowcode.io) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in all 12 | // copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | // SOFTWARE. 21 | 22 | import Foundation 23 | import CryptoKit 24 | 25 | public enum OTP { 26 | 27 | public static func generateOTP(secret: Data, algorithm: OTPAlgorithm = .sha1, expirationTimeInSeconds: Int = 30, digits: Int = 6) -> String? { 28 | 29 | let secondsPast1970 = Int(floor(Date().timeIntervalSince1970)) 30 | 31 | let counter = UInt64(floor(Double(secondsPast1970) / Double(expirationTimeInSeconds))) 32 | 33 | // HMAC message data from counter as big endian 34 | let counterMessage = counter.bigEndian.data 35 | 36 | // HMAC hash counter data with secret key 37 | var hmac = Data() 38 | 39 | switch algorithm { 40 | case .sha1: 41 | hmac = Data(HMAC.authenticationCode(for: counterMessage, using: SymmetricKey(data: secret))) 42 | case .sha256: 43 | hmac = Data(HMAC.authenticationCode(for: counterMessage, using: SymmetricKey(data: secret))) 44 | case .sha512: 45 | hmac = Data(HMAC.authenticationCode(for: counterMessage, using: SymmetricKey(data: secret))) 46 | } 47 | 48 | 49 | // Get last 4 bits of hash as offset 50 | let offset = Int((hmac.last ?? 0x00) & 0x0f) 51 | 52 | // Get 4 bytes from the hash from [offset] to [offset + 3] 53 | let truncatedHMAC = Array(hmac[offset...offset + 3]) 54 | 55 | // Convert byte array of the truncated hash to data 56 | let data = Data(truncatedHMAC) 57 | 58 | // Convert data to UInt32 59 | var number = UInt32(strtoul(data.bytes.toHexString(), nil, 16)) 60 | 61 | // Mask most significant bit 62 | number &= 0x7fffffff 63 | 64 | // Modulo number by 10^(digits) 65 | number = number % UInt32(pow(10, Float(digits))) 66 | 67 | // Convert int to string 68 | let strNum = String(number) 69 | 70 | // Return string if adding leading zeros is not required 71 | if strNum.count == digits { 72 | return strNum 73 | } 74 | 75 | // Add zeros to start of string if not present and return 76 | let prefixedZeros = String(repeatElement("0", count: (digits - strNum.count))) 77 | return (prefixedZeros + strNum) 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Sources/OTP/OTPAlgorithm.swift: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // Copyright © 2022 Sparrow Code LTD (https://sparrowcode.io, hello@sparrowcode.io) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in all 12 | // copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | // SOFTWARE. 21 | 22 | import Foundation 23 | 24 | /** 25 | OTP: Hash algorithm to use for one time password generation 26 | */ 27 | public enum OTPAlgorithm: Codable { 28 | 29 | case sha1 30 | case sha256 31 | case sha512 32 | } 33 | --------------------------------------------------------------------------------