Debian Codegraph @

utils.go

raw symbols SCIP
1 package gotp
2
3 import (
4 "fmt"
5 "math/rand"
6 "net/url"
7 "strings"
8 "time"
9 )
10
11 const (
12 OtpTypeTotp = "totp"
13 OtpTypeHotp = "hotp"
14 )
15
16 /*
17 Returns the provisioning URI for the OTP; works for either TOTP or HOTP.
18 This can then be encoded in a QR Code and used to provision the Google Authenticator app.
19 For module-internal use.
20 See also:
21 https://github.com/google/google-authenticator/wiki/Key-Uri-Format
22
23 params:
24 otpType: otp type, must in totp/hotp
25 secret: the hotp/totp secret used to generate the URI
26 accountName: name of the account
27 issuerName: the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator
28 algorithm: the algorithm used in the OTP generation
29 initialCount: starting counter value. Only works for hotp
30 digits: the length of the OTP generated code.
31 period: the number of seconds the OTP generator is set to expire every code.
32
33 returns: provisioning uri
34 */
35 func BuildUri(otpType, secret, accountName, issuerName, algorithm string, initialCount, digits, period int) string {
36 if otpType != OtpTypeHotp && otpType != OtpTypeTotp {
37 panic("otp type error, got " + otpType)
38 }
39
40 urlParams := make([]string, 0)
41 urlParams = append(urlParams, "secret="+secret)
42 if otpType == OtpTypeHotp {
43 urlParams = append(urlParams, fmt.Sprintf("counter=%d", initialCount))
44 }
45 label := url.QueryEscape(accountName)
46 if issuerName != "" {
47 issuerNameEscape := url.QueryEscape(issuerName)
48 label = issuerNameEscape + ":" + label
49 urlParams = append(urlParams, "issuer="+issuerNameEscape)
50 }
51 if algorithm != "" && algorithm != "sha1" {
52 urlParams = append(urlParams, "algorithm="+strings.ToUpper(algorithm))
53 }
54 if digits != 0 && digits != 6 {
55 urlParams = append(urlParams, fmt.Sprintf("digits=%d", digits))
56 }
57 if period != 0 && period != 30 {
58 urlParams = append(urlParams, fmt.Sprintf("period=%d", period))
59 }
60 return fmt.Sprintf("otpauth://%s/%s?%s", otpType, label, strings.Join(urlParams, "&"))
61 }
62
63 // get current timestamp
64 func currentTimestamp() int {
65 return int(time.Now().Unix())
66 }
67
68 // integer to byte array
69 func Itob(integer int) []byte {
70 byteArr := make([]byte, 8)
71 for i := 7; i >= 0; i-- {
72 byteArr[i] = byte(integer & 0xff)
73 integer = integer >> 8
74 }
75 return byteArr
76 }
77
78 // generate a random secret of given length
79 func RandomSecret(length int) string {
80 rand.Seed(time.Now().UnixNano())
81 letterRunes := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")
82
83 bytes := make([]rune, length)
84
85 for i := range bytes {
86 bytes[i] = letterRunes[rand.Intn(len(letterRunes))]
87 }
88
89 return string(bytes)
90 }