-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhmac.go
72 lines (64 loc) · 1.46 KB
/
hmac.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
package main
import (
"bufio"
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"fmt"
"os"
"strconv"
"strings"
)
var key = make([]byte, 64)
func testhmac() {
rand.Read(key)
fmt.Println("Enter your username")
s := bufio.NewScanner(os.Stdin)
s.Scan()
input := s.Bytes()
signedMessaged, _ := signMessage(input)
for {
fmt.Println("This is your Token. Keep it safe! -> ", signedMessaged)
fmt.Println("Did you note it down? YES or NO?")
s.Scan()
isnoted := strings.ToLower(s.Text())
if isnoted == "yes" {
break
}
}
fmt.Println("okay let me test you.... what is the token? ")
s.Scan()
inputeToken := getByteSlice(s.Text())
if ok, _ := validateMessage(inputeToken, input); ok {
fmt.Println("Nice !")
} else {
fmt.Println(" _|_")
}
}
func getByteSlice(s string) []byte {
var result []byte
stringnum := strings.Fields(s)
for _, is := range stringnum {
i, err := strconv.Atoi(is)
if err == nil {
result = append(result, byte(i))
}
}
return result
}
func signMessage(message []byte) ([]byte, error) {
h := hmac.New(sha512.New, key)
_, err := h.Write(message)
if err != nil {
return nil, fmt.Errorf("error in sighMessage function : %w", err)
}
return h.Sum(nil), nil
}
func validateMessage(signedMessaged, message []byte) (bool, error) {
correctSign, err := signMessage(message)
if err != nil {
return false, fmt.Errorf("error in validating message %w", err)
}
isvalid := hmac.Equal(correctSign, signedMessaged)
return isvalid, nil
}