-
Notifications
You must be signed in to change notification settings - Fork 12
/
crypto.go
67 lines (56 loc) · 1.61 KB
/
crypto.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
package nthclient
import (
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
"time"
)
func CalculateAPIHostname(seed, tld string) string {
t := time.Now().Truncate(0).UTC().Format("2006-01-02")
digest := md5.Sum([]byte(seed + t))
return fmt.Sprintf("www.%s.%s",
hex.EncodeToString(digest[0:6]),
tld)
}
func VerifyResponse(response string, pubkey *rsa.PublicKey) ([]byte, error) {
parts := strings.SplitN(response, "*-*", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("data was not found in the response. parts found: %d, response: %q", len(parts), response)
}
signature, err := base64.StdEncoding.DecodeString(parts[0])
if err != nil {
return nil, fmt.Errorf("signature decoding failed: %w", err)
}
hashed := sha256.Sum256([]byte(parts[1]))
err = rsa.VerifyPKCS1v15(pubkey, crypto.SHA256, hashed[:], signature)
if err != nil {
return nil, fmt.Errorf("signature verification failed: %w", err)
}
return []byte(parts[1]), nil
}
func Decrypt(ciphertext, key string) ([]byte, error) {
bytes, err := hex.DecodeString(ciphertext)
if err != nil {
return nil, fmt.Errorf("ciphertexttext hex decoding failed: %w", err)
}
if len(bytes) < 16 {
return nil, fmt.Errorf("too short ciphertext bytes len: %d", len(bytes))
}
iv := bytes[0:16]
data := bytes[16:]
block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, fmt.Errorf("can't create block ciphertext: %w", err)
}
stream := cipher.NewCTR(block, iv)
plaintext := make([]byte, len(data))
stream.XORKeyStream(plaintext, data)
return plaintext, nil
}