summaryrefslogtreecommitdiff
path: root/http-server/cryptography.go
diff options
context:
space:
mode:
authorAndrew <saintruler@gmail.com>2021-04-28 20:31:16 +0400
committerAndrew <saintruler@gmail.com>2021-04-28 20:31:16 +0400
commit8ebbdab5079f803567297af842c87ce012b7ea11 (patch)
treeffe28a45797dab60b036eb05e419532cae329171 /http-server/cryptography.go
parent7d6270f64b1dc00d91230b5c793bc49991f0fcf8 (diff)
Added cryptography functions and completed client and server.
Diffstat (limited to 'http-server/cryptography.go')
-rw-r--r--http-server/cryptography.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/http-server/cryptography.go b/http-server/cryptography.go
new file mode 100644
index 0000000..3340446
--- /dev/null
+++ b/http-server/cryptography.go
@@ -0,0 +1,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
+}