SinricPro Library
SinricProSignature.h
1 /*
2  * Copyright (c) 2019 Sinric. All rights reserved.
3  * Licensed under Creative Commons Attribution-Share Alike (CC BY-SA)
4  *
5  * This file is part of the Sinric Pro (https://github.com/sinricpro/)
6  */
7 
8 #ifndef _SIGNATURE_H_
9 #define _SIGNATURE_H_
10 
11 #include "extralib/Crypto/Crypto.h"
12 #include "extralib/Crypto/Base64.h"
13 
14 String calculateSignature(const char* key, JsonDocument &jsonMessage) {
15  if (!jsonMessage.containsKey("payload")) return String("");
16  String jsonPayload; serializeJson(jsonMessage["payload"], jsonPayload);
17 
18  byte rawSigBuf[SHA256HMAC_SIZE];
19  String test;
20 
21 
22  SHA256HMAC hmac((byte*) key, strlen(key));
23  hmac.doUpdate(jsonPayload.c_str(), jsonPayload.length());
24  hmac.doFinal(rawSigBuf);
25 
26 
27  int b64_len = base64_enc_len(SHA256HMAC_SIZE);
28  char sigBuf[b64_len+1];
29  base64_encode(sigBuf, (char*) rawSigBuf, SHA256HMAC_SIZE);
30  sigBuf[b64_len] = 0;
31  String result = sigBuf;
32 
33  return result;
34 }
35 
36 bool verifyMessage(String key, JsonDocument &jsonMessage) {
37  String jsonHash = jsonMessage["signature"]["HMAC"];
38  String calculatedHash = calculateSignature(key.c_str(), jsonMessage);
39  return jsonHash == calculatedHash;
40 }
41 
42 String signMessage(String key, JsonDocument &jsonMessage) {
43  if (!jsonMessage.containsKey("signature")) jsonMessage.createNestedObject("signature");
44  jsonMessage["signature"]["HMAC"] = calculateSignature(key.c_str(), jsonMessage);
45  String signedMessageString;
46  serializeJson(jsonMessage, signedMessageString);
47  return signedMessageString;
48 }
49 
50 #endif // _SIGNATURE_H_