summaryrefslogtreecommitdiff
path: root/http-server/cryptography.go
blob: 334044654d66b70e24f576540bfb096147c78e12 (plain)
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
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"errors"
	"fmt"
)

func decodeMessage(ciphertext []byte, stringKey string) ([]byte, error) {
	block, _ := pem.Decode([]byte(stringKey))
	if block == nil {
		return nil, errors.New("key is not found in given string")
	}

	key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, key, ciphertext)
	if err != nil {
		return nil, err
	}
	return plaintext, err
}

func checkSignature(req Request, signature string, key string) (bool, error) {
	reqBytes, _ := json.Marshal(req)
	req64 := base64.StdEncoding.EncodeToString(reqBytes)
	h := sha256.Sum256([]byte(req64))
	requestHash := fmt.Sprintf("%x", h)

	decodedSign, err := base64.StdEncoding.DecodeString(signature)
	if err != nil {
		return false, err
	}
	signHash, err := decodeMessage(decodedSign, key)
	if err != nil {
		return false, err
	}

	return requestHash == string(signHash), nil
}