test.cc 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright Materialize, Inc. and contributors. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License in the LICENSE file at the
  6. // root of this repository, or online at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. // Small C test that ensures our openssl is built correctly.
  16. #include <openssl/sha.h>
  17. #include <cassert>
  18. #include <iomanip>
  19. #include <sstream>
  20. #include <string>
  21. // Use (void) to silent unused warnings.
  22. #define assertm(exp, msg) assert(((void)msg, exp))
  23. // From https://stackoverflow.com/a/2262447/7768383
  24. bool simpleSHA256(const void* input, unsigned long length, unsigned char* md)
  25. {
  26. SHA256_CTX context;
  27. if (!SHA256_Init(&context))
  28. return false;
  29. if (!SHA256_Update(&context, (unsigned char*)input, length))
  30. return false;
  31. if (!SHA256_Final(md, &context))
  32. return false;
  33. return true;
  34. }
  35. // Convert an byte array into a string
  36. std::string fromByteArray(const unsigned char* data, unsigned long length)
  37. {
  38. std::stringstream shastr;
  39. shastr << std::hex << std::setfill('0');
  40. for (unsigned long i = 0; i < length; ++i)
  41. {
  42. shastr << std::setw(2) << static_cast<int>(data[i]);
  43. }
  44. return shastr.str();
  45. }
  46. std::string MESSAGE = "hello world";
  47. std::string MESSAGE_HASH = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9";
  48. int main(int argc, char* argv[])
  49. {
  50. unsigned char md[SHA256_DIGEST_LENGTH] = {};
  51. assertm(simpleSHA256(static_cast<const void*>(MESSAGE.data()), MESSAGE.size(), md), "Failed to generate hash");
  52. std::string hash = fromByteArray(md, SHA256_DIGEST_LENGTH);
  53. assertm(hash == MESSAGE_HASH, "Unexpected message hash");
  54. return 0;
  55. }