diff options
| author | Andrew <saintruler@gmail.com> | 2021-05-13 22:02:27 +0400 |
|---|---|---|
| committer | Andrew <saintruler@gmail.com> | 2021-05-13 22:02:27 +0400 |
| commit | ee201b761f02c95e57e91528cf6060a55fd259d1 (patch) | |
| tree | 1b7f7d563a2f4800abbd55f9ff6d2ecd4bf3d036 /http-client/cryptography.go | |
| parent | 712c9f7153c59bc5487e781cdeab0a60dcfd6d6e (diff) | |
Added signature verification on client side.
Diffstat (limited to 'http-client/cryptography.go')
| -rw-r--r-- | http-client/cryptography.go | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/http-client/cryptography.go b/http-client/cryptography.go index 175e60b..135f6b2 100644 --- a/http-client/cryptography.go +++ b/http-client/cryptography.go @@ -9,6 +9,7 @@ import ( "encoding/base64" "encoding/json" "encoding/pem" + "errors" "fmt" ) @@ -17,6 +18,8 @@ const KeyBitSize = 4096 // Приватный ключ - отдаётся серверу // Публичный ключ - сохраняется на клиенте +// Функции для подписи сообщений + func signRequest(req Request, key *rsa.PublicKey) (string, error) { body, _ := json.Marshal(req) based := base64.StdEncoding.EncodeToString(body) @@ -58,3 +61,39 @@ func generateKeys() (private []byte, public []byte, err error) { bytePublic := pem.EncodeToMemory(publicKey) return bytePrivate, bytePublic, nil } + +// Функции для проверки подписи полученных сообщений + +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(payload string, signature string, key string) (bool, error) { + h := sha256.Sum256([]byte(payload)) + 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 +} |