| 1 |
package gotp |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto/hmac" |
| 5 |
"crypto/sha1" |
| 6 |
"encoding/base32" |
| 7 |
"fmt" |
| 8 |
"hash" |
| 9 |
"math" |
| 10 |
"strings" |
| 11 |
) |
| 12 |
|
| 13 |
type Hasher struct { |
| 14 |
HashName string |
| 15 |
Digest func() hash.Hash |
| 16 |
} |
| 17 |
|
| 18 |
type OTP struct { |
| 19 |
secret string |
| 20 |
digits int |
| 21 |
hasher *Hasher |
| 22 |
} |
| 23 |
|
| 24 |
func NewOTP(secret string, digits int, hasher *Hasher) OTP { |
| 25 |
if hasher == nil { |
| 26 |
hasher = &Hasher{ |
| 27 |
HashName: "sha1", |
| 28 |
Digest: sha1.New, |
| 29 |
} |
| 30 |
} |
| 31 |
return OTP{ |
| 32 |
secret: secret, |
| 33 |
digits: digits, |
| 34 |
hasher: hasher, |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
func (o *OTP) generateOTP(input int) string { |
| 43 |
if input < 0 { |
| 44 |
panic("input must be positive integer") |
| 45 |
} |
| 46 |
hasher := hmac.New(o.hasher.Digest, o.byteSecret()) |
| 47 |
hasher.Write(Itob(input)) |
| 48 |
hmacHash := hasher.Sum(nil) |
| 49 |
|
| 50 |
offset := int(hmacHash[len(hmacHash)-1] & 0xf) |
| 51 |
code := ((int(hmacHash[offset]) & 0x7f) << 24) | |
| 52 |
((int(hmacHash[offset+1] & 0xff)) << 16) | |
| 53 |
((int(hmacHash[offset+2] & 0xff)) << 8) | |
| 54 |
(int(hmacHash[offset+3]) & 0xff) |
| 55 |
|
| 56 |
code = code % int(math.Pow10(o.digits)) |
| 57 |
return fmt.Sprintf(fmt.Sprintf("%%0%dd", o.digits), code) |
| 58 |
} |
| 59 |
|
| 60 |
func (o *OTP) byteSecret() []byte { |
| 61 |
missingPadding := len(o.secret) % 8 |
| 62 |
if missingPadding != 0 { |
| 63 |
o.secret = o.secret + strings.Repeat("=", 8-missingPadding) |
| 64 |
} |
| 65 |
bytes, err := base32.StdEncoding.DecodeString(o.secret) |
| 66 |
if err != nil { |
| 67 |
panic("decode secret failed") |
| 68 |
} |
| 69 |
return bytes |
| 70 |
} |