crypto-helpers-mbedtls.cpp 808 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #include "crypto-helpers.hpp"
  2. #include "mbedtls/md.h"
  3. #include "mbedtls/pk.h"
  4. bool VerifySignature(const uint8_t *pubKey, const size_t pubKeyLen,
  5. const uint8_t *buf, const size_t len, const uint8_t *sig,
  6. const size_t sigLen)
  7. {
  8. bool result = false;
  9. int ret = 1;
  10. unsigned char hash[64];
  11. mbedtls_pk_context pk;
  12. mbedtls_pk_init(&pk);
  13. // Parse PEM key
  14. if ((ret = mbedtls_pk_parse_public_key(&pk, pubKey, pubKeyLen + 1)) !=
  15. 0) {
  16. goto exit;
  17. }
  18. // Hash input buffer
  19. if ((ret = mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), buf,
  20. len, hash)) != 0) {
  21. goto exit;
  22. }
  23. // Verify signautre
  24. if ((ret = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA512, hash, 64, sig,
  25. sigLen)) != 0) {
  26. goto exit;
  27. }
  28. result = true;
  29. exit:
  30. mbedtls_pk_free(&pk);
  31. return result;
  32. }