HMAC.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include "HMAC.hpp"
  28. #include <openssl/sha.h>
  29. namespace ZeroTier {
  30. void HMAC::sha256(const void *key,unsigned int klen,const void *message,unsigned int len,void *mac)
  31. throw()
  32. {
  33. union {
  34. uint64_t q[12];
  35. uint8_t b[96];
  36. } key2,opad,ipad;
  37. SHA256_CTX sha;
  38. if (klen == 32) { // this is what we use, so handle this quickly
  39. key2.q[0] = ((const uint64_t *)key)[0];
  40. key2.q[1] = ((const uint64_t *)key)[1];
  41. key2.q[2] = ((const uint64_t *)key)[2];
  42. key2.q[3] = ((const uint64_t *)key)[3];
  43. key2.q[4] = 0ULL;
  44. key2.q[5] = 0ULL;
  45. key2.q[6] = 0ULL;
  46. key2.q[7] = 0ULL;
  47. } else { // for correctness and testing against test vectors
  48. if (klen > 64) {
  49. SHA256_Init(&sha);
  50. SHA256_Update(&sha,key,klen);
  51. SHA256_Final(key2.b,&sha);
  52. klen = 32;
  53. } else {
  54. for(unsigned int i=0;i<klen;++i)
  55. key2.b[i] = ((const uint8_t *)key)[i];
  56. }
  57. while (klen < 64)
  58. key2.b[klen++] = (uint8_t)0;
  59. }
  60. for(unsigned int i=0;i<8;++i)
  61. opad.q[i] = 0x5c5c5c5c5c5c5c5cULL ^ key2.q[i];
  62. for(unsigned int i=0;i<8;++i)
  63. ipad.q[i] = 0x3636363636363636ULL ^ key2.q[i];
  64. SHA256_Init(&sha);
  65. SHA256_Update(&sha,(const unsigned char *)ipad.b,64);
  66. SHA256_Update(&sha,(const unsigned char *)message,len);
  67. SHA256_Final((unsigned char *)(opad.b + 64),&sha);
  68. SHA256_Init(&sha);
  69. SHA256_Update(&sha,opad.b,96);
  70. SHA256_Final((unsigned char *)mac,&sha);
  71. }
  72. } // namespace ZeroTier