-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrypto_cookie.go
56 lines (47 loc) · 1.57 KB
/
crypto_cookie.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
// Copyright (c) 2024 H0llyW00dz All rights reserved.
//
// License: BSD 3-Clause License
package twofa
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"fmt"
"strconv"
"strings"
"time"
)
// GenerateCookieValue generates a signed cookie value using HMAC.
//
// TODO: Implement an extra layer of cookie value (in addition to the current timestamp)
// and enhance security by using custom cryptography for encryption and decryption value.
// Use a user secret derived from 2FA for encryption/decryption and bind it to a UUID for identification purposes.
// This will replace the current implementation that uses HMAC.
func (m *Middleware) GenerateCookieValue(expirationTime time.Time) string {
data := fmt.Sprintf("%d", expirationTime.Unix())
hash := hmac.New(sha256.New, []byte(m.Config.Secret))
hash.Write([]byte(data))
signature := base64.RawURLEncoding.EncodeToString(hash.Sum(nil))
return fmt.Sprintf("%s.%s", data, signature)
}
// validateCookie validates the cookie value using HMAC.
func (m *Middleware) validateCookie(cookie string) bool {
parts := strings.Split(cookie, ".")
if len(parts) != 2 {
return false
}
data := parts[0]
signature := parts[1]
hash := hmac.New(sha256.New, []byte(m.Config.Secret))
hash.Write([]byte(data))
expectedSignature := base64.RawURLEncoding.EncodeToString(hash.Sum(nil))
if subtle.ConstantTimeCompare([]byte(signature), []byte(expectedSignature)) != 1 {
return false
}
expirationTime, err := strconv.ParseInt(data, 10, 64)
if err != nil {
return false
}
return time.Now().Unix() <= expirationTime
}