diff options
Diffstat (limited to 'http-server/cryptography.go')
| -rw-r--r-- | http-server/cryptography.go | 49 |
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 +} |