-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
93 lines (87 loc) · 2.11 KB
/
utils.go
File metadata and controls
93 lines (87 loc) · 2.11 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package enablebankinggo
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"os"
"time"
)
// loadPrivateKeyFromFile loads an RSA private key from a PEM-encoded file.
func loadPrivateKeyFromFile(path string) (*rsa.PrivateKey, error) {
keyContent, err := os.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(keyContent)
if block == nil {
return nil, errors.New("failed to parse PEM private key")
}
switch block.Type {
case "RSA PRIVATE KEY":
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return privateKey, nil
case "PRIVATE KEY":
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return privateKey.(*rsa.PrivateKey), nil
default:
fmt.Println("Unsupported key type:", block.Type)
return nil, errors.New("failed to parse PEM private key")
}
}
func sign(privateKey *rsa.PrivateKey, data []byte) (string, error) {
hash := sha256.New()
hash.Write(data)
hashed := hash.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed)
if err != nil {
return "", err
}
encodedSignature := base64.RawURLEncoding.EncodeToString(signature)
return encodedSignature, nil
}
func getJwtHeader(applicationID string) (string, error) {
encodedHeader, err := json.Marshal(struct {
Alg string `json:"alg"`
Typ string `json:"typ"`
Kid string `json:"kid"`
}{
Alg: "RS256",
Typ: "JWT",
Kid: applicationID,
})
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(encodedHeader), nil
}
func getJwtBody(ttl int64) (string, time.Time, error) {
iat := time.Now().Unix()
encodedBody, err := json.Marshal(struct {
Iss string `json:"iss"`
Aud string `json:"aud"`
Iat int64 `json:"iat"`
Exp int64 `json:"exp"`
}{
Iss: "enablebanking.com",
Aud: "api.enablebanking.com",
Iat: iat,
Exp: iat + ttl,
})
if err != nil {
return "", time.Time{}, err
}
return base64.RawURLEncoding.EncodeToString(encodedBody), time.Unix(iat+ttl, 0), nil
}