/
digest_time_hmac_sha1.go
76 lines (64 loc) · 2.36 KB
/
digest_time_hmac_sha1.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Code generated by __generator__/interpreter.go at once
package builtin
import (
"crypto/sha1"
"encoding/base32"
"encoding/base64"
"time"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"github.com/ysugimoto/falco/interpreter/context"
"github.com/ysugimoto/falco/interpreter/function/errors"
"github.com/ysugimoto/falco/interpreter/value"
)
const Digest_time_hmac_sha1_Name = "digest.time_hmac_sha1"
var Digest_time_hmac_sha1_ArgumentTypes = []value.Type{value.StringType, value.IntegerType, value.IntegerType}
func Digest_time_hmac_sha1_Validate(args []value.Value) error {
if len(args) != 3 {
return errors.ArgumentNotEnough(Digest_time_hmac_sha1_Name, 3, args)
}
for i := range args {
if args[i].Type() != Digest_time_hmac_sha1_ArgumentTypes[i] {
return errors.TypeMismatch(Digest_time_hmac_sha1_Name, i+1, Digest_time_hmac_sha1_ArgumentTypes[i], args[i].Type())
}
}
return nil
}
// Fastly built-in function implementation of digest.time_hmac_sha1
// Arguments may be:
// - STRING, INTEGER, INTEGER
// Reference: https://developer.fastly.com/reference/vcl/functions/cryptographic/digest-time-hmac-sha1/
func Digest_time_hmac_sha1(ctx *context.Context, args ...value.Value) (value.Value, error) {
// Argument validations
if err := Digest_time_hmac_sha1_Validate(args); err != nil {
return value.Null, err
}
secret := value.Unwrap[*value.String](args[0])
interval := value.Unwrap[*value.Integer](args[1])
offset := value.Unwrap[*value.Integer](args[2])
return digest_time_hmac_sha1(time.Now(), secret, interval, offset)
}
func digest_time_hmac_sha1(baseTime time.Time, secret *value.String, interval, offset *value.Integer) (value.Value, error) {
dec, err := base64.StdEncoding.DecodeString(secret.Value)
if err != nil {
return value.Null, errors.New("digest.time_hmac_sha1", "Failed to base64 decode secret string")
}
var skew uint
if offset.Value >= 0 {
skew = uint(offset.Value)
}
key := base32.StdEncoding.EncodeToString(dec)
pass, err := totp.GenerateCodeCustom(key, baseTime, totp.ValidateOpts{
Period: uint(interval.Value),
Digits: otp.DigitsSix,
Algorithm: otp.AlgorithmSHA1,
Skew: skew,
})
if err != nil {
return value.Null, errors.New("digest.time_hmac_sha1", "Failed to generate TOTP password")
}
enc := sha1.Sum([]byte(pass))
return &value.String{
Value: base64.StdEncoding.EncodeToString(enc[:]),
}, nil
}