├── .travis.yml ├── LICENSE ├── NOTICE ├── README.md ├── doc.go ├── example └── main.go ├── go.mod ├── go.sum ├── hotp ├── hotp.go └── hotp_test.go ├── internal └── encode.go ├── interop ├── go.mod ├── go.sum ├── interop.go └── twofactor_test.go ├── otp.go ├── otp_test.go └── totp ├── totp.go └── totp_test.go /.travis.yml: -------------------------------------------------------------------------------- 1 | arch: 2 | - amd64 3 | - ppc64le 4 | language: go 5 | 6 | env: 7 | - GO111MODULE=on 8 | 9 | go: 10 | - "1.15" 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | otp 2 | Copyright (c) 2014, Paul Querna 3 | 4 | This product includes software developed by 5 | Paul Querna (http://paul.querna.org/). 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # otp: One Time Password utilities Go / Golang 2 | 3 | [![PkgGoDev](https://pkg.go.dev/badge/github.com/pquerna/otp)](https://pkg.go.dev/github.com/pquerna/otp) [![Build Status](https://travis-ci.org/pquerna/otp.svg?branch=master)](https://travis-ci.org/pquerna/otp) 4 | 5 | # Why One Time Passwords? 6 | 7 | One Time Passwords (OTPs) are an mechanism to improve security over passwords alone. When a Time-based OTP (TOTP) is stored on a user's phone, and combined with something the user knows (Password), you have an easy on-ramp to [Multi-factor authentication](http://en.wikipedia.org/wiki/Multi-factor_authentication) without adding a dependency on a SMS provider. This Password and TOTP combination is used by many popular websites including Google, GitHub, Facebook, Salesforce and many others. 8 | 9 | The `otp` library enables you to easily add TOTPs to your own application, increasing your user's security against mass-password breaches and malware. 10 | 11 | Because TOTP is standardized and widely deployed, there are many [mobile clients and software implementations](http://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm#Client_implementations). 12 | 13 | ## `otp` Supports: 14 | 15 | * Generating QR Code images for easy user enrollment. 16 | * Time-based One-time Password Algorithm (TOTP) (RFC 6238): Time based OTP, the most commonly used method. 17 | * HMAC-based One-time Password Algorithm (HOTP) (RFC 4226): Counter based OTP, which TOTP is based upon. 18 | * Generation and Validation of codes for either algorithm. 19 | 20 | ## Implementing TOTP in your application: 21 | 22 | ### User Enrollment 23 | 24 | For an example of a working enrollment work flow, [GitHub has documented theirs](https://help.github.com/articles/configuring-two-factor-authentication-via-a-totp-mobile-app/ 25 | ), but the basics are: 26 | 27 | 1. Generate new TOTP Key for a User. `key,_ := totp.Generate(...)`. 28 | 1. Display the Key's Secret and QR-Code for the User. `key.Secret()` and `key.Image(...)`. 29 | 1. Test that the user can successfully use their TOTP. `totp.Validate(...)`. 30 | 1. Store TOTP Secret for the User in your backend. `key.Secret()` 31 | 1. Provide the user with "recovery codes". (See Recovery Codes bellow) 32 | 33 | ### Code Generation 34 | 35 | * In either TOTP or HOTP cases, use the `GenerateCode` function and a counter or 36 | `time.Time` struct to generate a valid code compatible with most implementations. 37 | * For uncommon or custom settings, or to catch unlikely errors, use `GenerateCodeCustom` 38 | in either module. 39 | 40 | ### Validation 41 | 42 | 1. Prompt and validate User's password as normal. 43 | 1. If the user has TOTP enabled, prompt for TOTP passcode. 44 | 1. Retrieve the User's TOTP Secret from your backend. 45 | 1. Validate the user's passcode. `totp.Validate(...)` 46 | 47 | 48 | ### Recovery Codes 49 | 50 | When a user loses access to their TOTP device, they would no longer have access to their account. Because TOTPs are often configured on mobile devices that can be lost, stolen or damaged, this is a common problem. For this reason many providers give their users "backup codes" or "recovery codes". These are a set of one time use codes that can be used instead of the TOTP. These can simply be randomly generated strings that you store in your backend. [Github's documentation provides an overview of the user experience]( 51 | https://help.github.com/articles/downloading-your-two-factor-authentication-recovery-codes/). 52 | 53 | 54 | ## Improvements, bugs, adding feature, etc: 55 | 56 | Please [open issues in Github](https://github.com/pquerna/otp/issues) for ideas, bugs, and general thoughts. Pull requests are of course preferred :) 57 | 58 | ## License 59 | 60 | `otp` is licensed under the [Apache License, Version 2.0](./LICENSE) 61 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Paul Querna 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | // Package otp implements both HOTP and TOTP based 19 | // one time passcodes in a Google Authenticator compatible manner. 20 | // 21 | // When adding a TOTP for a user, you must store the "secret" value 22 | // persistently. It is recommended to store the secret in an encrypted field in your 23 | // datastore. Due to how TOTP works, it is not possible to store a hash 24 | // for the secret value like you would a password. 25 | // 26 | // To enroll a user, you must first generate an OTP for them. Google 27 | // Authenticator supports using a QR code as an enrollment method: 28 | // 29 | // import ( 30 | // "github.com/pquerna/otp/totp" 31 | // 32 | // "bytes" 33 | // "image/png" 34 | // ) 35 | // 36 | // key, err := totp.Generate(totp.GenerateOpts{ 37 | // Issuer: "Example.com", 38 | // AccountName: "alice@example.com", 39 | // }) 40 | // 41 | // // Convert TOTP key into a QR code encoded as a PNG image. 42 | // var buf bytes.Buffer 43 | // img, err := key.Image(200, 200) 44 | // png.Encode(&buf, img) 45 | // 46 | // // display the QR code to the user. 47 | // display(buf.Bytes()) 48 | // 49 | // // Now Validate that the user's successfully added the passcode. 50 | // passcode := promptForPasscode() 51 | // valid := totp.Validate(passcode, key.Secret()) 52 | // 53 | // if valid { 54 | // // User successfully used their TOTP, save it to your backend! 55 | // storeSecret("alice@example.com", key.Secret()) 56 | // } 57 | // 58 | // Validating a TOTP passcode is very easy, just prompt the user for a passcode 59 | // and retrieve the associated user's previously stored secret. 60 | // 61 | // import "github.com/pquerna/otp/totp" 62 | // 63 | // passcode := promptForPasscode() 64 | // secret := getSecret("alice@example.com") 65 | // 66 | // valid := totp.Validate(passcode, secret) 67 | // 68 | // if valid { 69 | // // Success! continue login process. 70 | // } 71 | package otp 72 | -------------------------------------------------------------------------------- /example/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/pquerna/otp" 5 | "github.com/pquerna/otp/totp" 6 | 7 | "bufio" 8 | "bytes" 9 | "encoding/base32" 10 | "fmt" 11 | "image/png" 12 | "os" 13 | "time" 14 | ) 15 | 16 | func display(key *otp.Key, data []byte) { 17 | fmt.Printf("Issuer: %s\n", key.Issuer()) 18 | fmt.Printf("Account Name: %s\n", key.AccountName()) 19 | fmt.Printf("Secret: %s\n", key.Secret()) 20 | fmt.Println("Writing PNG to qr-code.png....") 21 | os.WriteFile("qr-code.png", data, 0644) 22 | fmt.Println("") 23 | fmt.Println("Please add your TOTP to your OTP Application now!") 24 | fmt.Println("") 25 | } 26 | 27 | func promptForPasscode() string { 28 | reader := bufio.NewReader(os.Stdin) 29 | fmt.Print("Enter Passcode: ") 30 | text, _ := reader.ReadString('\n') 31 | return text 32 | } 33 | 34 | // Demo function, not used in main 35 | // Generates Passcode using a UTF-8 (not base32) secret and custom parameters 36 | func GeneratePassCode(utf8string string) string{ 37 | secret := base32.StdEncoding.EncodeToString([]byte(utf8string)) 38 | passcode, err := totp.GenerateCodeCustom(secret, time.Now(), totp.ValidateOpts{ 39 | Period: 30, 40 | Skew: 1, 41 | Digits: otp.DigitsSix, 42 | Algorithm: otp.AlgorithmSHA512, 43 | }) 44 | if err != nil { 45 | panic(err) 46 | } 47 | return passcode 48 | } 49 | 50 | func main() { 51 | key, err := totp.Generate(totp.GenerateOpts{ 52 | Issuer: "Example.com", 53 | AccountName: "alice@example.com", 54 | }) 55 | if err != nil { 56 | panic(err) 57 | } 58 | // Convert TOTP key into a PNG 59 | var buf bytes.Buffer 60 | img, err := key.Image(200, 200) 61 | if err != nil { 62 | panic(err) 63 | } 64 | png.Encode(&buf, img) 65 | 66 | // display the QR code to the user. 67 | display(key, buf.Bytes()) 68 | 69 | // Now Validate that the user's successfully added the passcode. 70 | fmt.Println("Validating TOTP...") 71 | passcode := promptForPasscode() 72 | valid := totp.Validate(passcode, key.Secret()) 73 | if valid { 74 | println("Valid passcode!") 75 | os.Exit(0) 76 | } else { 77 | println("Invalid passcode!") 78 | os.Exit(1) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/pquerna/otp 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc 7 | github.com/stretchr/testify v1.3.0 8 | ) 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI= 2 | github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= 3 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 4 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 6 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 7 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 8 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= 9 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 10 | -------------------------------------------------------------------------------- /hotp/hotp.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Paul Querna 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package hotp 19 | 20 | import ( 21 | "github.com/pquerna/otp" 22 | "github.com/pquerna/otp/internal" 23 | "io" 24 | 25 | "crypto/hmac" 26 | "crypto/rand" 27 | "crypto/subtle" 28 | "encoding/base32" 29 | "encoding/binary" 30 | "fmt" 31 | "math" 32 | "net/url" 33 | "strings" 34 | ) 35 | 36 | const debug = false 37 | 38 | // Validate a HOTP passcode given a counter and secret. 39 | // This is a shortcut for ValidateCustom, with parameters that 40 | // are compataible with Google-Authenticator. 41 | func Validate(passcode string, counter uint64, secret string) bool { 42 | rv, _ := ValidateCustom( 43 | passcode, 44 | counter, 45 | secret, 46 | ValidateOpts{ 47 | Digits: otp.DigitsSix, 48 | Algorithm: otp.AlgorithmSHA1, 49 | }, 50 | ) 51 | return rv 52 | } 53 | 54 | // ValidateOpts provides options for ValidateCustom(). 55 | type ValidateOpts struct { 56 | // Digits as part of the input. Defaults to 6. 57 | Digits otp.Digits 58 | // Algorithm to use for HMAC. Defaults to SHA1. 59 | Algorithm otp.Algorithm 60 | // Encoder to use for output code. 61 | Encoder otp.Encoder 62 | } 63 | 64 | // GenerateCode creates a HOTP passcode given a counter and secret. 65 | // This is a shortcut for GenerateCodeCustom, with parameters that 66 | // are compataible with Google-Authenticator. 67 | func GenerateCode(secret string, counter uint64) (string, error) { 68 | return GenerateCodeCustom(secret, counter, ValidateOpts{ 69 | Digits: otp.DigitsSix, 70 | Algorithm: otp.AlgorithmSHA1, 71 | }) 72 | } 73 | 74 | // GenerateCodeCustom uses a counter and secret value and options struct to 75 | // create a passcode. 76 | func GenerateCodeCustom(secret string, counter uint64, opts ValidateOpts) (passcode string, err error) { 77 | //Set default value 78 | if opts.Digits == 0 { 79 | opts.Digits = otp.DigitsSix 80 | } 81 | // As noted in issue #10 and #17 this adds support for TOTP secrets that are 82 | // missing their padding. 83 | secret = strings.TrimSpace(secret) 84 | if n := len(secret) % 8; n != 0 { 85 | secret = secret + strings.Repeat("=", 8-n) 86 | } 87 | 88 | // As noted in issue #24 Google has started producing base32 in lower case, 89 | // but the StdEncoding (and the RFC), expect a dictionary of only upper case letters. 90 | secret = strings.ToUpper(secret) 91 | 92 | secretBytes, err := base32.StdEncoding.DecodeString(secret) 93 | if err != nil { 94 | return "", otp.ErrValidateSecretInvalidBase32 95 | } 96 | 97 | buf := make([]byte, 8) 98 | mac := hmac.New(opts.Algorithm.Hash, secretBytes) 99 | binary.BigEndian.PutUint64(buf, counter) 100 | if debug { 101 | fmt.Printf("counter=%v\n", counter) 102 | fmt.Printf("buf=%v\n", buf) 103 | } 104 | 105 | mac.Write(buf) 106 | sum := mac.Sum(nil) 107 | 108 | // "Dynamic truncation" in RFC 4226 109 | // http://tools.ietf.org/html/rfc4226#section-5.4 110 | offset := sum[len(sum)-1] & 0xf 111 | value := int64(((int(sum[offset]) & 0x7f) << 24) | 112 | ((int(sum[offset+1] & 0xff)) << 16) | 113 | ((int(sum[offset+2] & 0xff)) << 8) | 114 | (int(sum[offset+3]) & 0xff)) 115 | 116 | l := opts.Digits.Length() 117 | switch opts.Encoder { 118 | case otp.EncoderDefault: 119 | mod := int32(value % int64(math.Pow10(l))) 120 | 121 | if debug { 122 | fmt.Printf("offset=%v\n", offset) 123 | fmt.Printf("value=%v\n", value) 124 | fmt.Printf("mod'ed=%v\n", mod) 125 | } 126 | passcode = opts.Digits.Format(mod) 127 | case otp.EncoderSteam: 128 | // Define the character set used by Steam Guard codes. 129 | alphabet := []byte{ 130 | '2', '3', '4', '5', '6', '7', '8', '9', 'B', 'C', 131 | 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 132 | 'R', 'T', 'V', 'W', 'X', 'Y', 133 | } 134 | radix := int64(len(alphabet)) 135 | 136 | for i := 0; i < l; i++ { 137 | digit := value % radix 138 | value /= radix 139 | c := alphabet[digit] 140 | passcode += string(c) 141 | } 142 | } 143 | 144 | return 145 | } 146 | 147 | // ValidateCustom validates an HOTP with customizable options. Most users should 148 | // use Validate(). 149 | func ValidateCustom(passcode string, counter uint64, secret string, opts ValidateOpts) (bool, error) { 150 | passcode = strings.TrimSpace(passcode) 151 | 152 | if len(passcode) != opts.Digits.Length() { 153 | return false, otp.ErrValidateInputInvalidLength 154 | } 155 | 156 | otpstr, err := GenerateCodeCustom(secret, counter, opts) 157 | if err != nil { 158 | return false, err 159 | } 160 | 161 | if subtle.ConstantTimeCompare([]byte(otpstr), []byte(passcode)) == 1 { 162 | return true, nil 163 | } 164 | 165 | return false, nil 166 | } 167 | 168 | // GenerateOpts provides options for .Generate() 169 | type GenerateOpts struct { 170 | // Name of the issuing Organization/Company. 171 | Issuer string 172 | // Name of the User's Account (eg, email address) 173 | AccountName string 174 | // Size in size of the generated Secret. Defaults to 10 bytes. 175 | SecretSize uint 176 | // Secret to store. Defaults to a randomly generated secret of SecretSize. You should generally leave this empty. 177 | Secret []byte 178 | // Digits to request. Defaults to 6. 179 | Digits otp.Digits 180 | // Algorithm to use for HMAC. Defaults to SHA1. 181 | Algorithm otp.Algorithm 182 | // Reader to use for generating HOTP Key. 183 | Rand io.Reader 184 | } 185 | 186 | var b32NoPadding = base32.StdEncoding.WithPadding(base32.NoPadding) 187 | 188 | // Generate creates a new HOTP Key. 189 | func Generate(opts GenerateOpts) (*otp.Key, error) { 190 | // url encode the Issuer/AccountName 191 | if opts.Issuer == "" { 192 | return nil, otp.ErrGenerateMissingIssuer 193 | } 194 | 195 | if opts.AccountName == "" { 196 | return nil, otp.ErrGenerateMissingAccountName 197 | } 198 | 199 | if opts.SecretSize == 0 { 200 | opts.SecretSize = 10 201 | } 202 | 203 | if opts.Digits == 0 { 204 | opts.Digits = otp.DigitsSix 205 | } 206 | 207 | if opts.Rand == nil { 208 | opts.Rand = rand.Reader 209 | } 210 | 211 | // otpauth://hotp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example 212 | 213 | v := url.Values{} 214 | if len(opts.Secret) != 0 { 215 | v.Set("secret", b32NoPadding.EncodeToString(opts.Secret)) 216 | } else { 217 | secret := make([]byte, opts.SecretSize) 218 | _, err := io.ReadFull(opts.Rand, secret) 219 | if err != nil { 220 | return nil, err 221 | } 222 | v.Set("secret", b32NoPadding.EncodeToString(secret)) 223 | } 224 | 225 | v.Set("issuer", opts.Issuer) 226 | v.Set("algorithm", opts.Algorithm.String()) 227 | v.Set("digits", opts.Digits.String()) 228 | 229 | u := url.URL{ 230 | Scheme: "otpauth", 231 | Host: "hotp", 232 | Path: "/" + opts.Issuer + ":" + opts.AccountName, 233 | RawQuery: internal.EncodeQuery(v), 234 | } 235 | 236 | return otp.NewKeyFromURL(u.String()) 237 | } 238 | -------------------------------------------------------------------------------- /hotp/hotp_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Paul Querna 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package hotp 19 | 20 | import ( 21 | "github.com/pquerna/otp" 22 | "github.com/stretchr/testify/assert" 23 | "github.com/stretchr/testify/require" 24 | 25 | "encoding/base32" 26 | "testing" 27 | ) 28 | 29 | type tc struct { 30 | Counter uint64 31 | TOTP string 32 | Mode otp.Algorithm 33 | Secret string 34 | } 35 | 36 | var ( 37 | secSha1 = base32.StdEncoding.EncodeToString([]byte("12345678901234567890")) 38 | 39 | rfcMatrixTCs = []tc{ 40 | {0, "755224", otp.AlgorithmSHA1, secSha1}, 41 | {1, "287082", otp.AlgorithmSHA1, secSha1}, 42 | {2, "359152", otp.AlgorithmSHA1, secSha1}, 43 | {3, "969429", otp.AlgorithmSHA1, secSha1}, 44 | {4, "338314", otp.AlgorithmSHA1, secSha1}, 45 | {5, "254676", otp.AlgorithmSHA1, secSha1}, 46 | {6, "287922", otp.AlgorithmSHA1, secSha1}, 47 | {7, "162583", otp.AlgorithmSHA1, secSha1}, 48 | {8, "399871", otp.AlgorithmSHA1, secSha1}, 49 | {9, "520489", otp.AlgorithmSHA1, secSha1}, 50 | } 51 | ) 52 | 53 | // Test values from http://tools.ietf.org/html/rfc4226#appendix-D 54 | func TestValidateRFCMatrix(t *testing.T) { 55 | 56 | for _, tx := range rfcMatrixTCs { 57 | valid, err := ValidateCustom(tx.TOTP, tx.Counter, tx.Secret, 58 | ValidateOpts{ 59 | Digits: otp.DigitsSix, 60 | Algorithm: tx.Mode, 61 | }) 62 | require.NoError(t, err, 63 | "unexpected error totp=%s mode=%v counter=%v", tx.TOTP, tx.Mode, tx.Counter) 64 | require.True(t, valid, 65 | "unexpected totp failure totp=%s mode=%v counter=%v", tx.TOTP, tx.Mode, tx.Counter) 66 | } 67 | } 68 | 69 | func TestGenerateRFCMatrix(t *testing.T) { 70 | for _, tx := range rfcMatrixTCs { 71 | passcode, err := GenerateCodeCustom(tx.Secret, tx.Counter, 72 | ValidateOpts{ 73 | Digits: otp.DigitsSix, 74 | Algorithm: tx.Mode, 75 | }) 76 | assert.Nil(t, err) 77 | assert.Equal(t, tx.TOTP, passcode) 78 | } 79 | } 80 | 81 | func TestGenerateCodeCustom(t *testing.T){ 82 | secSha1 := base32.StdEncoding.EncodeToString([]byte("12345678901234567890")) 83 | 84 | code, err := GenerateCodeCustom("foo",1,ValidateOpts{}) 85 | print(code) 86 | require.Equal(t, otp.ErrValidateSecretInvalidBase32, err, "Decoding of secret as base32 failed.") 87 | require.Equal(t, "", code, "Code should be empty string when we have an error.") 88 | 89 | code, err = GenerateCodeCustom(secSha1,1,ValidateOpts{}) 90 | require.Equal(t, 6, len(code), "Code should be 6 digits when we have not an error.") 91 | require.NoError(t, err, "Expected no error.") 92 | } 93 | 94 | func TestValidateInvalid(t *testing.T) { 95 | secSha1 := base32.StdEncoding.EncodeToString([]byte("12345678901234567890")) 96 | 97 | valid, err := ValidateCustom("foo", 11, secSha1, 98 | ValidateOpts{ 99 | Digits: otp.DigitsSix, 100 | Algorithm: otp.AlgorithmSHA1, 101 | }) 102 | require.Equal(t, otp.ErrValidateInputInvalidLength, err, "Expected Invalid length error.") 103 | require.Equal(t, false, valid, "Valid should be false when we have an error.") 104 | 105 | valid, err = ValidateCustom("foo", 11, secSha1, 106 | ValidateOpts{ 107 | Digits: otp.DigitsEight, 108 | Algorithm: otp.AlgorithmSHA1, 109 | }) 110 | require.Equal(t, otp.ErrValidateInputInvalidLength, err, "Expected Invalid length error.") 111 | require.Equal(t, false, valid, "Valid should be false when we have an error.") 112 | 113 | valid, err = ValidateCustom("000000", 11, secSha1, 114 | ValidateOpts{ 115 | Digits: otp.DigitsSix, 116 | Algorithm: otp.AlgorithmSHA1, 117 | }) 118 | require.NoError(t, err, "Expected no error.") 119 | require.Equal(t, false, valid, "Valid should be false.") 120 | 121 | valid = Validate("000000", 11, secSha1) 122 | require.Equal(t, false, valid, "Valid should be false.") 123 | } 124 | 125 | // This tests for issue #10 - secrets without padding 126 | func TestValidatePadding(t *testing.T) { 127 | valid, err := ValidateCustom("831097", 0, "JBSWY3DPEHPK3PX", 128 | ValidateOpts{ 129 | Digits: otp.DigitsSix, 130 | Algorithm: otp.AlgorithmSHA1, 131 | }) 132 | require.NoError(t, err, "Expected no error.") 133 | require.Equal(t, true, valid, "Valid should be true.") 134 | } 135 | 136 | func TestValidateLowerCaseSecret(t *testing.T) { 137 | valid, err := ValidateCustom("831097", 0, "jbswy3dpehpk3px", 138 | ValidateOpts{ 139 | Digits: otp.DigitsSix, 140 | Algorithm: otp.AlgorithmSHA1, 141 | }) 142 | require.NoError(t, err, "Expected no error.") 143 | require.Equal(t, true, valid, "Valid should be true.") 144 | } 145 | 146 | func TestGenerate(t *testing.T) { 147 | k, err := Generate(GenerateOpts{ 148 | Issuer: "SnakeOil", 149 | AccountName: "alice@example.com", 150 | }) 151 | require.NoError(t, err, "generate basic HOTP") 152 | require.Equal(t, "SnakeOil", k.Issuer(), "Extracting Issuer") 153 | require.Equal(t, "alice@example.com", k.AccountName(), "Extracting Account Name") 154 | require.Equal(t, 16, len(k.Secret()), "Secret is 16 bytes long as base32.") 155 | 156 | k, err = Generate(GenerateOpts{ 157 | Issuer: "Snake Oil", 158 | AccountName: "alice@example.com", 159 | }) 160 | require.NoError(t, err, "issuer with a space in the name") 161 | require.Contains(t, k.String(), "issuer=Snake%20Oil") 162 | 163 | k, err = Generate(GenerateOpts{ 164 | Issuer: "SnakeOil", 165 | AccountName: "alice@example.com", 166 | SecretSize: 20, 167 | }) 168 | require.NoError(t, err, "generate larger HOTP") 169 | require.Equal(t, 32, len(k.Secret()), "Secret is 32 bytes long as base32.") 170 | 171 | k, err = Generate(GenerateOpts{ 172 | Issuer: "", 173 | AccountName: "alice@example.com", 174 | }) 175 | require.Equal(t, otp.ErrGenerateMissingIssuer, err, "generate missing issuer") 176 | require.Nil(t, k, "key should be nil on error.") 177 | 178 | k, err = Generate(GenerateOpts{ 179 | Issuer: "Foobar, Inc", 180 | AccountName: "", 181 | }) 182 | require.Equal(t, otp.ErrGenerateMissingAccountName, err, "generate missing account name.") 183 | require.Nil(t, k, "key should be nil on error.") 184 | 185 | k, err = Generate(GenerateOpts{ 186 | Issuer: "SnakeOil", 187 | AccountName: "alice@example.com", 188 | SecretSize: 17, // anything that is not divisible by 5, really 189 | }) 190 | require.NoError(t, err, "Secret size is valid when length not divisible by 5.") 191 | require.NotContains(t, k.Secret(), "=", "Secret has no escaped characters.") 192 | 193 | k, err = Generate(GenerateOpts{ 194 | Issuer: "SnakeOil", 195 | AccountName: "alice@example.com", 196 | Secret: []byte("helloworld"), 197 | }) 198 | require.NoError(t, err, "Secret generation failed") 199 | sec, err := b32NoPadding.DecodeString(k.Secret()) 200 | require.NoError(t, err, "Secret was not valid base32") 201 | require.Equal(t, sec, []byte("helloworld"), "Specified Secret was not kept") 202 | } 203 | -------------------------------------------------------------------------------- /internal/encode.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "net/url" 5 | "sort" 6 | "strings" 7 | ) 8 | 9 | // EncodeQuery is a copy-paste of url.Values.Encode, except it uses %20 instead 10 | // of + to encode spaces. This is necessary to correctly render spaces in some 11 | // authenticator apps, like Google Authenticator. 12 | func EncodeQuery(v url.Values) string { 13 | if v == nil { 14 | return "" 15 | } 16 | var buf strings.Builder 17 | keys := make([]string, 0, len(v)) 18 | for k := range v { 19 | keys = append(keys, k) 20 | } 21 | sort.Strings(keys) 22 | for _, k := range keys { 23 | vs := v[k] 24 | keyEscaped := url.PathEscape(k) // changed from url.QueryEscape 25 | for _, v := range vs { 26 | if buf.Len() > 0 { 27 | buf.WriteByte('&') 28 | } 29 | buf.WriteString(keyEscaped) 30 | buf.WriteByte('=') 31 | buf.WriteString(url.PathEscape(v)) // changed from url.QueryEscape 32 | } 33 | } 34 | return buf.String() 35 | } 36 | -------------------------------------------------------------------------------- /interop/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/pquerna/otp/interop 2 | 3 | go 1.12 4 | -------------------------------------------------------------------------------- /interop/go.sum: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pquerna/otp/5971b1ef1d6652fec2caed37f11e5cacd9249f78/interop/go.sum -------------------------------------------------------------------------------- /interop/interop.go: -------------------------------------------------------------------------------- 1 | package interop 2 | -------------------------------------------------------------------------------- /interop/twofactor_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 Paul Querna 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package interop_test 19 | 20 | import ( 21 | "testing" 22 | "time" 23 | 24 | "github.com/gokyle/twofactor" 25 | "github.com/pquerna/otp" 26 | "github.com/pquerna/otp/totp" 27 | "github.com/stretchr/testify/require" 28 | ) 29 | 30 | func TestTwoFactor(t *testing.T) { 31 | key, err := totp.Generate(totp.GenerateOpts{ 32 | Issuer: "Example.com", 33 | AccountName: "alice@example.com", 34 | Algorithm: otp.AlgorithmSHA512, 35 | }) 36 | require.NoError(t, err) 37 | require.NotNil(t, key) 38 | 39 | tf, label, err := twofactor.FromURL(key.URL()) 40 | require.NoError(t, err) 41 | require.NotNil(t, tf) 42 | require.Equal(t, "Example.com:alice@example.com", label) 43 | 44 | code := tf.OTP() 45 | require.NotEmpty(t, code) 46 | 47 | valid, err := totp.ValidateCustom(code, key.Secret(), 48 | time.Now().UTC(), 49 | totp.ValidateOpts{ 50 | Period: 30, 51 | Skew: 1, 52 | Digits: otp.DigitsSix, 53 | Algorithm: otp.AlgorithmSHA512, 54 | }, 55 | ) 56 | require.NoError(t, err) 57 | require.True(t, valid) 58 | } 59 | -------------------------------------------------------------------------------- /otp.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Paul Querna 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package otp 19 | 20 | import ( 21 | "crypto/md5" 22 | "crypto/sha1" 23 | "crypto/sha256" 24 | "crypto/sha512" 25 | "errors" 26 | "fmt" 27 | "hash" 28 | "image" 29 | "net/url" 30 | "strconv" 31 | "strings" 32 | 33 | "github.com/boombuler/barcode" 34 | "github.com/boombuler/barcode/qr" 35 | ) 36 | 37 | // Error when attempting to convert the secret from base32 to raw bytes. 38 | var ErrValidateSecretInvalidBase32 = errors.New("Decoding of secret as base32 failed.") 39 | 40 | // The user provided passcode length was not expected. 41 | var ErrValidateInputInvalidLength = errors.New("Input length unexpected") 42 | 43 | // When generating a Key, the Issuer must be set. 44 | var ErrGenerateMissingIssuer = errors.New("Issuer must be set") 45 | 46 | // When generating a Key, the Account Name must be set. 47 | var ErrGenerateMissingAccountName = errors.New("AccountName must be set") 48 | 49 | // Key represents an TOTP or HTOP key. 50 | type Key struct { 51 | orig string 52 | url *url.URL 53 | } 54 | 55 | // NewKeyFromURL creates a new Key from an TOTP or HOTP url. 56 | // 57 | // The URL format is documented here: 58 | // https://github.com/google/google-authenticator/wiki/Key-Uri-Format 59 | // 60 | func NewKeyFromURL(orig string) (*Key, error) { 61 | s := strings.TrimSpace(orig) 62 | 63 | u, err := url.Parse(s) 64 | if err != nil { 65 | return nil, err 66 | } 67 | 68 | return &Key{ 69 | orig: s, 70 | url: u, 71 | }, nil 72 | } 73 | 74 | func (k *Key) String() string { 75 | return k.orig 76 | } 77 | 78 | // Image returns an QR-Code image of the specified width and height, 79 | // suitable for use by many clients like Google-Authenricator 80 | // to enroll a user's TOTP/HOTP key. 81 | func (k *Key) Image(width int, height int) (image.Image, error) { 82 | b, err := qr.Encode(k.orig, qr.M, qr.Auto) 83 | if err != nil { 84 | return nil, err 85 | } 86 | 87 | b, err = barcode.Scale(b, width, height) 88 | 89 | if err != nil { 90 | return nil, err 91 | } 92 | 93 | return b, nil 94 | } 95 | 96 | // Type returns "hotp" or "totp". 97 | func (k *Key) Type() string { 98 | return k.url.Host 99 | } 100 | 101 | // Issuer returns the name of the issuing organization. 102 | func (k *Key) Issuer() string { 103 | q := k.url.Query() 104 | 105 | issuer := q.Get("issuer") 106 | 107 | if issuer != "" { 108 | return issuer 109 | } 110 | 111 | p := strings.TrimPrefix(k.url.Path, "/") 112 | i := strings.Index(p, ":") 113 | 114 | if i == -1 { 115 | return "" 116 | } 117 | 118 | return p[:i] 119 | } 120 | 121 | // AccountName returns the name of the user's account. 122 | func (k *Key) AccountName() string { 123 | p := strings.TrimPrefix(k.url.Path, "/") 124 | i := strings.Index(p, ":") 125 | 126 | if i == -1 { 127 | return p 128 | } 129 | 130 | return p[i+1:] 131 | } 132 | 133 | // Secret returns the opaque secret for this Key. 134 | func (k *Key) Secret() string { 135 | q := k.url.Query() 136 | 137 | return q.Get("secret") 138 | } 139 | 140 | // Period returns a tiny int representing the rotation time in seconds. 141 | func (k *Key) Period() uint64 { 142 | q := k.url.Query() 143 | 144 | if u, err := strconv.ParseUint(q.Get("period"), 10, 64); err == nil { 145 | return u 146 | } 147 | 148 | // If no period is defined 30 seconds is the default per (rfc6238) 149 | return 30 150 | } 151 | 152 | // Digits returns a tiny int representing the number of OTP digits. 153 | func (k *Key) Digits() Digits { 154 | q := k.url.Query() 155 | 156 | if u, err := strconv.ParseUint(q.Get("digits"), 10, 64); err == nil { 157 | return Digits(u) 158 | } 159 | 160 | // Six is the most common value. 161 | return DigitsSix 162 | } 163 | 164 | // Algorithm returns the algorithm used or the default (SHA1). 165 | func (k *Key) Algorithm() Algorithm { 166 | q := k.url.Query() 167 | 168 | a := strings.ToLower(q.Get("algorithm")) 169 | switch a { 170 | case "md5": 171 | return AlgorithmMD5 172 | case "sha256": 173 | return AlgorithmSHA256 174 | case "sha512": 175 | return AlgorithmSHA512 176 | default: 177 | return AlgorithmSHA1 178 | } 179 | } 180 | 181 | // Encoder returns the encoder used or the default ("") 182 | func (k *Key) Encoder() Encoder { 183 | q := k.url.Query() 184 | 185 | a := strings.ToLower(q.Get("encoder")) 186 | switch a { 187 | case "steam": 188 | return EncoderSteam 189 | default: 190 | return EncoderDefault 191 | } 192 | } 193 | 194 | // URL returns the OTP URL as a string 195 | func (k *Key) URL() string { 196 | return k.url.String() 197 | } 198 | 199 | // Algorithm represents the hashing function to use in the HMAC 200 | // operation needed for OTPs. 201 | type Algorithm int 202 | 203 | const ( 204 | // AlgorithmSHA1 should be used for compatibility with Google Authenticator. 205 | // 206 | // See https://github.com/pquerna/otp/issues/55 for additional details. 207 | AlgorithmSHA1 Algorithm = iota 208 | AlgorithmSHA256 209 | AlgorithmSHA512 210 | AlgorithmMD5 211 | ) 212 | 213 | func (a Algorithm) String() string { 214 | switch a { 215 | case AlgorithmSHA1: 216 | return "SHA1" 217 | case AlgorithmSHA256: 218 | return "SHA256" 219 | case AlgorithmSHA512: 220 | return "SHA512" 221 | case AlgorithmMD5: 222 | return "MD5" 223 | } 224 | panic("unreached") 225 | } 226 | 227 | func (a Algorithm) Hash() hash.Hash { 228 | switch a { 229 | case AlgorithmSHA1: 230 | return sha1.New() 231 | case AlgorithmSHA256: 232 | return sha256.New() 233 | case AlgorithmSHA512: 234 | return sha512.New() 235 | case AlgorithmMD5: 236 | return md5.New() 237 | } 238 | panic("unreached") 239 | } 240 | 241 | // Digits represents the number of digits present in the 242 | // user's OTP passcode. Six and Eight are the most common values. 243 | type Digits int 244 | 245 | const ( 246 | DigitsSix Digits = 6 247 | DigitsEight Digits = 8 248 | ) 249 | 250 | // Format converts an integer into the zero-filled size for this Digits. 251 | func (d Digits) Format(in int32) string { 252 | f := fmt.Sprintf("%%0%dd", d) 253 | return fmt.Sprintf(f, in) 254 | } 255 | 256 | // Length returns the number of characters for this Digits. 257 | func (d Digits) Length() int { 258 | return int(d) 259 | } 260 | 261 | func (d Digits) String() string { 262 | return fmt.Sprintf("%d", d) 263 | } 264 | 265 | type Encoder string 266 | 267 | const ( 268 | EncoderDefault Encoder = "" 269 | EncoderSteam Encoder = "steam" 270 | ) 271 | -------------------------------------------------------------------------------- /otp_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Paul Querna 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package otp 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/require" 24 | ) 25 | 26 | func TestKeyAllThere(t *testing.T) { 27 | k, err := NewKeyFromURL(`otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example&algorithm=sha256&digits=8`) 28 | require.NoError(t, err, "failed to parse url") 29 | require.Equal(t, "totp", k.Type(), "Extracting Type") 30 | require.Equal(t, "Example", k.Issuer(), "Extracting Issuer") 31 | require.Equal(t, "alice@google.com", k.AccountName(), "Extracting Account Name") 32 | require.Equal(t, "JBSWY3DPEHPK3PXP", k.Secret(), "Extracting Secret") 33 | require.Equal(t, AlgorithmSHA256, k.Algorithm()) 34 | require.Equal(t, DigitsEight, k.Digits()) 35 | } 36 | 37 | func TestKeyIssuerOnlyInPath(t *testing.T) { 38 | k, err := NewKeyFromURL(`otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP`) 39 | require.NoError(t, err, "failed to parse url") 40 | require.Equal(t, "Example", k.Issuer(), "Extracting Issuer") 41 | require.Equal(t, "alice@google.com", k.AccountName(), "Extracting Account Name") 42 | } 43 | 44 | func TestKeyNoIssuer(t *testing.T) { 45 | k, err := NewKeyFromURL(`otpauth://totp/alice@google.com?secret=JBSWY3DPEHPK3PXP`) 46 | require.NoError(t, err, "failed to parse url") 47 | require.Equal(t, "", k.Issuer(), "Extracting Issuer") 48 | require.Equal(t, "alice@google.com", k.AccountName(), "Extracting Account Name") 49 | } 50 | 51 | func TestKeyWithNewLine(t *testing.T) { 52 | w, err := NewKeyFromURL(`otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP 53 | `) 54 | require.NoError(t, err) 55 | sec := w.Secret() 56 | require.Equal(t, "JBSWY3DPEHPK3PXP", sec) 57 | } 58 | -------------------------------------------------------------------------------- /totp/totp.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Paul Querna 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package totp 19 | 20 | import ( 21 | "github.com/pquerna/otp" 22 | "github.com/pquerna/otp/hotp" 23 | "github.com/pquerna/otp/internal" 24 | "io" 25 | 26 | "crypto/rand" 27 | "encoding/base32" 28 | "math" 29 | "net/url" 30 | "strconv" 31 | "time" 32 | ) 33 | 34 | // Validate a TOTP using the current time. 35 | // A shortcut for ValidateCustom, Validate uses a configuration 36 | // that is compatible with Google-Authenticator and most clients. 37 | func Validate(passcode string, secret string) bool { 38 | rv, _ := ValidateCustom( 39 | passcode, 40 | secret, 41 | time.Now().UTC(), 42 | ValidateOpts{ 43 | Period: 30, 44 | Skew: 1, 45 | Digits: otp.DigitsSix, 46 | Algorithm: otp.AlgorithmSHA1, 47 | }, 48 | ) 49 | return rv 50 | } 51 | 52 | // GenerateCode creates a TOTP token using the current time. 53 | // A shortcut for GenerateCodeCustom, GenerateCode uses a configuration 54 | // that is compatible with Google-Authenticator and most clients. 55 | func GenerateCode(secret string, t time.Time) (string, error) { 56 | return GenerateCodeCustom(secret, t, ValidateOpts{ 57 | Period: 30, 58 | Skew: 1, 59 | Digits: otp.DigitsSix, 60 | Algorithm: otp.AlgorithmSHA1, 61 | }) 62 | } 63 | 64 | // ValidateOpts provides options for ValidateCustom(). 65 | type ValidateOpts struct { 66 | // Number of seconds a TOTP hash is valid for. Defaults to 30 seconds. 67 | Period uint 68 | // Periods before or after the current time to allow. Value of 1 allows up to Period 69 | // of either side of the specified time. Defaults to 0 allowed skews. Values greater 70 | // than 1 are likely sketchy. 71 | Skew uint 72 | // Digits as part of the input. Defaults to 6. 73 | Digits otp.Digits 74 | // Algorithm to use for HMAC. Defaults to SHA1. 75 | Algorithm otp.Algorithm 76 | // Encoder to use for output code. 77 | Encoder otp.Encoder 78 | } 79 | 80 | // GenerateCodeCustom takes a timepoint and produces a passcode using a 81 | // secret and the provided opts. (Under the hood, this is making an adapted 82 | // call to hotp.GenerateCodeCustom) 83 | func GenerateCodeCustom(secret string, t time.Time, opts ValidateOpts) (passcode string, err error) { 84 | if opts.Period == 0 { 85 | opts.Period = 30 86 | } 87 | counter := uint64(math.Floor(float64(t.Unix()) / float64(opts.Period))) 88 | passcode, err = hotp.GenerateCodeCustom(secret, counter, hotp.ValidateOpts{ 89 | Digits: opts.Digits, 90 | Algorithm: opts.Algorithm, 91 | Encoder: opts.Encoder, 92 | }) 93 | if err != nil { 94 | return "", err 95 | } 96 | return passcode, nil 97 | } 98 | 99 | // ValidateCustom validates a TOTP given a user specified time and custom options. 100 | // Most users should use Validate() to provide an interpolatable TOTP experience. 101 | func ValidateCustom(passcode string, secret string, t time.Time, opts ValidateOpts) (bool, error) { 102 | if opts.Period == 0 { 103 | opts.Period = 30 104 | } 105 | 106 | counters := []uint64{} 107 | counter := int64(math.Floor(float64(t.Unix()) / float64(opts.Period))) 108 | 109 | counters = append(counters, uint64(counter)) 110 | for i := 1; i <= int(opts.Skew); i++ { 111 | counters = append(counters, uint64(counter+int64(i))) 112 | counters = append(counters, uint64(counter-int64(i))) 113 | } 114 | 115 | for _, counter := range counters { 116 | rv, err := hotp.ValidateCustom(passcode, counter, secret, hotp.ValidateOpts{ 117 | Digits: opts.Digits, 118 | Algorithm: opts.Algorithm, 119 | Encoder: opts.Encoder, 120 | }) 121 | if err != nil { 122 | return false, err 123 | } 124 | 125 | if rv == true { 126 | return true, nil 127 | } 128 | } 129 | 130 | return false, nil 131 | } 132 | 133 | // GenerateOpts provides options for Generate(). The default values 134 | // are compatible with Google-Authenticator. 135 | type GenerateOpts struct { 136 | // Name of the issuing Organization/Company. 137 | Issuer string 138 | // Name of the User's Account (eg, email address) 139 | AccountName string 140 | // Number of seconds a TOTP hash is valid for. Defaults to 30 seconds. 141 | Period uint 142 | // Size in size of the generated Secret. Defaults to 20 bytes. 143 | SecretSize uint 144 | // Secret to store. Defaults to a randomly generated secret of SecretSize. You should generally leave this empty. 145 | Secret []byte 146 | // Digits to request. Defaults to 6. 147 | Digits otp.Digits 148 | // Algorithm to use for HMAC. Defaults to SHA1. 149 | Algorithm otp.Algorithm 150 | // Reader to use for generating TOTP Key. 151 | Rand io.Reader 152 | } 153 | 154 | var b32NoPadding = base32.StdEncoding.WithPadding(base32.NoPadding) 155 | 156 | // Generate a new TOTP Key. 157 | func Generate(opts GenerateOpts) (*otp.Key, error) { 158 | // url encode the Issuer/AccountName 159 | if opts.Issuer == "" { 160 | return nil, otp.ErrGenerateMissingIssuer 161 | } 162 | 163 | if opts.AccountName == "" { 164 | return nil, otp.ErrGenerateMissingAccountName 165 | } 166 | 167 | if opts.Period == 0 { 168 | opts.Period = 30 169 | } 170 | 171 | if opts.SecretSize == 0 { 172 | opts.SecretSize = 20 173 | } 174 | 175 | if opts.Digits == 0 { 176 | opts.Digits = otp.DigitsSix 177 | } 178 | 179 | if opts.Rand == nil { 180 | opts.Rand = rand.Reader 181 | } 182 | 183 | // otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example 184 | 185 | v := url.Values{} 186 | if len(opts.Secret) != 0 { 187 | v.Set("secret", b32NoPadding.EncodeToString(opts.Secret)) 188 | } else { 189 | secret := make([]byte, opts.SecretSize) 190 | _, err := io.ReadFull(opts.Rand, secret) 191 | if err != nil { 192 | return nil, err 193 | } 194 | v.Set("secret", b32NoPadding.EncodeToString(secret)) 195 | } 196 | 197 | v.Set("issuer", opts.Issuer) 198 | v.Set("period", strconv.FormatUint(uint64(opts.Period), 10)) 199 | v.Set("algorithm", opts.Algorithm.String()) 200 | v.Set("digits", opts.Digits.String()) 201 | 202 | u := url.URL{ 203 | Scheme: "otpauth", 204 | Host: "totp", 205 | Path: "/" + opts.Issuer + ":" + opts.AccountName, 206 | RawQuery: internal.EncodeQuery(v), 207 | } 208 | 209 | return otp.NewKeyFromURL(u.String()) 210 | } 211 | -------------------------------------------------------------------------------- /totp/totp_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Paul Querna 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package totp 19 | 20 | import ( 21 | "github.com/pquerna/otp" 22 | "github.com/stretchr/testify/assert" 23 | "github.com/stretchr/testify/require" 24 | 25 | "encoding/base32" 26 | "testing" 27 | "time" 28 | ) 29 | 30 | type tc struct { 31 | TS int64 32 | TOTP string 33 | Mode otp.Algorithm 34 | Secret string 35 | } 36 | 37 | var ( 38 | secSha1 = base32.StdEncoding.EncodeToString([]byte("12345678901234567890")) 39 | secSha256 = base32.StdEncoding.EncodeToString([]byte("12345678901234567890123456789012")) 40 | secSha512 = base32.StdEncoding.EncodeToString([]byte("1234567890123456789012345678901234567890123456789012345678901234")) 41 | 42 | rfcMatrixTCs = []tc{ 43 | {59, "94287082", otp.AlgorithmSHA1, secSha1}, 44 | {59, "46119246", otp.AlgorithmSHA256, secSha256}, 45 | {59, "90693936", otp.AlgorithmSHA512, secSha512}, 46 | {1111111109, "07081804", otp.AlgorithmSHA1, secSha1}, 47 | {1111111109, "68084774", otp.AlgorithmSHA256, secSha256}, 48 | {1111111109, "25091201", otp.AlgorithmSHA512, secSha512}, 49 | {1111111111, "14050471", otp.AlgorithmSHA1, secSha1}, 50 | {1111111111, "67062674", otp.AlgorithmSHA256, secSha256}, 51 | {1111111111, "99943326", otp.AlgorithmSHA512, secSha512}, 52 | {1234567890, "89005924", otp.AlgorithmSHA1, secSha1}, 53 | {1234567890, "91819424", otp.AlgorithmSHA256, secSha256}, 54 | {1234567890, "93441116", otp.AlgorithmSHA512, secSha512}, 55 | {2000000000, "69279037", otp.AlgorithmSHA1, secSha1}, 56 | {2000000000, "90698825", otp.AlgorithmSHA256, secSha256}, 57 | {2000000000, "38618901", otp.AlgorithmSHA512, secSha512}, 58 | {20000000000, "65353130", otp.AlgorithmSHA1, secSha1}, 59 | {20000000000, "77737706", otp.AlgorithmSHA256, secSha256}, 60 | {20000000000, "47863826", otp.AlgorithmSHA512, secSha512}, 61 | } 62 | ) 63 | 64 | // 65 | // Test vectors from http://tools.ietf.org/html/rfc6238#appendix-B 66 | // NOTE -- the test vectors are documented as having the SAME 67 | // secret -- this is WRONG -- they have a variable secret 68 | // depending upon the hmac algorithm: 69 | // http://www.rfc-editor.org/errata_search.php?rfc=6238 70 | // this only took a few hours of head/desk interaction to figure out. 71 | // 72 | func TestValidateRFCMatrix(t *testing.T) { 73 | for _, tx := range rfcMatrixTCs { 74 | valid, err := ValidateCustom(tx.TOTP, tx.Secret, time.Unix(tx.TS, 0).UTC(), 75 | ValidateOpts{ 76 | Digits: otp.DigitsEight, 77 | Algorithm: tx.Mode, 78 | }) 79 | require.NoError(t, err, 80 | "unexpected error totp=%s mode=%v ts=%v", tx.TOTP, tx.Mode, tx.TS) 81 | require.True(t, valid, 82 | "unexpected totp failure totp=%s mode=%v ts=%v", tx.TOTP, tx.Mode, tx.TS) 83 | } 84 | } 85 | 86 | func TestGenerateRFCTCs(t *testing.T) { 87 | for _, tx := range rfcMatrixTCs { 88 | passcode, err := GenerateCodeCustom(tx.Secret, time.Unix(tx.TS, 0).UTC(), 89 | ValidateOpts{ 90 | Digits: otp.DigitsEight, 91 | Algorithm: tx.Mode, 92 | }) 93 | assert.Nil(t, err) 94 | assert.Equal(t, tx.TOTP, passcode) 95 | } 96 | } 97 | 98 | func TestValidateSkew(t *testing.T) { 99 | secSha1 := base32.StdEncoding.EncodeToString([]byte("12345678901234567890")) 100 | 101 | tests := []tc{ 102 | {29, "94287082", otp.AlgorithmSHA1, secSha1}, 103 | {59, "94287082", otp.AlgorithmSHA1, secSha1}, 104 | {61, "94287082", otp.AlgorithmSHA1, secSha1}, 105 | } 106 | 107 | for _, tx := range tests { 108 | valid, err := ValidateCustom(tx.TOTP, tx.Secret, time.Unix(tx.TS, 0).UTC(), 109 | ValidateOpts{ 110 | Digits: otp.DigitsEight, 111 | Algorithm: tx.Mode, 112 | Skew: 1, 113 | }) 114 | require.NoError(t, err, 115 | "unexpected error totp=%s mode=%v ts=%v", tx.TOTP, tx.Mode, tx.TS) 116 | require.True(t, valid, 117 | "unexpected totp failure totp=%s mode=%v ts=%v", tx.TOTP, tx.Mode, tx.TS) 118 | } 119 | } 120 | 121 | func TestGenerate(t *testing.T) { 122 | k, err := Generate(GenerateOpts{ 123 | Issuer: "SnakeOil", 124 | AccountName: "alice@example.com", 125 | }) 126 | require.NoError(t, err, "generate basic TOTP") 127 | require.Equal(t, "SnakeOil", k.Issuer(), "Extracting Issuer") 128 | require.Equal(t, "alice@example.com", k.AccountName(), "Extracting Account Name") 129 | require.Equal(t, 32, len(k.Secret()), "Secret is 32 bytes long as base32.") 130 | 131 | k, err = Generate(GenerateOpts{ 132 | Issuer: "Snake Oil", 133 | AccountName: "alice@example.com", 134 | }) 135 | require.NoError(t, err, "issuer with a space in the name") 136 | require.Contains(t, k.String(), "issuer=Snake%20Oil") 137 | 138 | k, err = Generate(GenerateOpts{ 139 | Issuer: "SnakeOil", 140 | AccountName: "alice@example.com", 141 | SecretSize: 20, 142 | }) 143 | require.NoError(t, err, "generate larger TOTP") 144 | require.Equal(t, 32, len(k.Secret()), "Secret is 32 bytes long as base32.") 145 | 146 | k, err = Generate(GenerateOpts{ 147 | Issuer: "SnakeOil", 148 | AccountName: "alice@example.com", 149 | SecretSize: 13, // anything that is not divisible by 5, really 150 | }) 151 | require.NoError(t, err, "Secret size is valid when length not divisible by 5.") 152 | require.NotContains(t, k.Secret(), "=", "Secret has no escaped characters.") 153 | 154 | k, err = Generate(GenerateOpts{ 155 | Issuer: "SnakeOil", 156 | AccountName: "alice@example.com", 157 | Secret: []byte("helloworld"), 158 | }) 159 | require.NoError(t, err, "Secret generation failed") 160 | sec, err := b32NoPadding.DecodeString(k.Secret()) 161 | require.NoError(t, err, "Secret wa not valid base32") 162 | require.Equal(t, sec, []byte("helloworld"), "Specified Secret was not kept") 163 | } 164 | 165 | func TestGoogleLowerCaseSecret(t *testing.T) { 166 | w, err := otp.NewKeyFromURL(`otpauth://totp/Google%3Afoo%40example.com?secret=qlt6vmy6svfx4bt4rpmisaiyol6hihca&issuer=Google`) 167 | require.NoError(t, err) 168 | sec := w.Secret() 169 | require.Equal(t, "qlt6vmy6svfx4bt4rpmisaiyol6hihca", sec) 170 | 171 | n := time.Now().UTC() 172 | code, err := GenerateCode(w.Secret(), n) 173 | require.NoError(t, err) 174 | 175 | valid := Validate(code, w.Secret()) 176 | require.True(t, valid) 177 | } 178 | 179 | func TestSteamSecret(t *testing.T) { 180 | w, err := otp.NewKeyFromURL(`otpauth://totp/username%20steam:username?secret=qlt6vmy6svfx4bt4rpmisaiyol6hihca&period=30&digits=5&issuer=username%20steam&encoder=steam`) 181 | require.NoError(t, err) 182 | require.Equal(t, "qlt6vmy6svfx4bt4rpmisaiyol6hihca", w.Secret()) 183 | require.Equal(t, otp.EncoderSteam, w.Encoder()) 184 | require.Equal(t, 5, w.Digits().Length()) 185 | 186 | n := time.Now().UTC() 187 | opts := ValidateOpts{ 188 | Period: uint(w.Period()), 189 | Digits: w.Digits(), 190 | Encoder: w.Encoder(), 191 | } 192 | code, err := GenerateCodeCustom(w.Secret(), n, opts) 193 | require.NoError(t, err) 194 | 195 | require.Len(t, code, w.Digits().Length()) 196 | 197 | valid, err := ValidateCustom(code, w.Secret(), n, opts) 198 | require.NoError(t, err) 199 | require.True(t, valid) 200 | } 201 | --------------------------------------------------------------------------------