-
Notifications
You must be signed in to change notification settings - Fork 7
/
crypto.go
101 lines (77 loc) · 2.28 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
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
94
95
96
97
98
99
100
101
package bunq
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/pkg/errors"
)
// CreateNewKeyPair creates a new RSA key pair that can be used for signing requests.
func CreateNewKeyPair() (*rsa.PrivateKey, error) {
reader := rand.Reader
bitSize := 2048
key, err := rsa.GenerateKey(reader, bitSize)
if err != nil {
return nil, errors.Wrap(err, "bunq: could not generate key pair")
}
return key, nil
}
func (c *Client) addSignatureHeader(r *http.Request) error {
var err error
var body io.ReadCloser
if r.Body != nil {
body, err = r.GetBody()
}
if err != nil {
return errors.Wrap(err, "bunq: could not get request body")
}
stringToSign := createStringToSign(body)
h := sha256.New()
_, err = h.Write([]byte(stringToSign))
if err != nil {
return errors.Wrap(err, "bunq: could not encode string to sign to sha256")
}
signature, err := rsa.SignPKCS1v15(rand.Reader, c.privateKey, crypto.SHA256, h.Sum(nil))
if err != nil {
return errors.Wrap(err, "bunq: could not sign request")
}
r.Header.Set("X-Bunq-Client-Signature", base64.StdEncoding.EncodeToString(signature))
return nil
}
func (c *Client) verifySignature(r *http.Response) (bool, error) {
bodyBytes, _ := ioutil.ReadAll(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
stringToVerify := createStringToVerify(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
h := sha256.New()
_, err := h.Write([]byte(stringToVerify))
if err != nil {
return false, errors.Wrap(err, "bunq: writing string to verify to sha failed")
}
sigString := r.Header.Get("X-Bunq-Server-Signature")
sig, _ := base64.StdEncoding.DecodeString(sigString)
err = rsa.VerifyPKCS1v15(c.serverPublicKey, crypto.SHA256, h.Sum(nil), sig)
return err == nil, errors.Wrap(err, "bunq: request validation failed.")
}
func createStringToVerify(body io.ReadCloser) string {
defer body.Close()
rawBody, _ := ioutil.ReadAll(body)
stringToVerify := string(rawBody)
stringToVerify = strings.TrimSuffix(stringToVerify, "\n")
return stringToVerify
}
func createStringToSign(body io.ReadCloser) string {
if body != nil {
defer body.Close()
rawBody, _ := ioutil.ReadAll(body)
return fmt.Sprintf("%s", rawBody)
}
return "\n"
}