sheet_protection.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright (c) 2014-2021 Thomas Fussell
  2. // Copyright (c) 2010-2015 openpyxl
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE
  21. //
  22. // @license: http://www.opensource.org/licenses/mit-license.php
  23. // @author: see AUTHORS file
  24. #include <algorithm>
  25. #include <locale>
  26. #include <sstream>
  27. #include <xlnt/worksheet/sheet_protection.hpp>
  28. namespace {
  29. template <typename T>
  30. std::string int_to_hex(T i)
  31. {
  32. std::stringstream stream;
  33. stream << std::hex << i;
  34. return stream.str();
  35. }
  36. } // namespace
  37. namespace xlnt {
  38. void sheet_protection::password(const std::string &password)
  39. {
  40. hashed_password_ = hash_password(password);
  41. }
  42. std::string sheet_protection::hashed_password() const
  43. {
  44. return hashed_password_;
  45. }
  46. std::string sheet_protection::hash_password(const std::string &plaintext_password)
  47. {
  48. int password = 0x0000;
  49. int i = 1;
  50. for (auto character : plaintext_password)
  51. {
  52. int value = character << i;
  53. int rotated_bits = value >> 15;
  54. value &= 0x7fff;
  55. password ^= (value | rotated_bits);
  56. i++;
  57. }
  58. password ^= plaintext_password.size();
  59. password ^= 0xCE4B;
  60. std::string hashed = int_to_hex(password);
  61. std::transform(hashed.begin(), hashed.end(), hashed.begin(),
  62. [](char c) { return std::toupper(c, std::locale::classic()); });
  63. return hashed;
  64. }
  65. } // namespace xlnt