protection.py 830 B

12345678910111213141516171819202122
  1. # Copyright (c) 2010-2024 openpyxl
  2. def hash_password(plaintext_password=''):
  3. """
  4. Create a password hash from a given string for protecting a worksheet
  5. only. This will not work for encrypting a workbook.
  6. This method is based on the algorithm provided by
  7. Daniel Rentz of OpenOffice and the PEAR package
  8. Spreadsheet_Excel_Writer by Xavier Noguer <xnoguer@rezebra.com>.
  9. See also http://blogs.msdn.com/b/ericwhite/archive/2008/02/23/the-legacy-hashing-algorithm-in-open-xml.aspx
  10. """
  11. password = 0x0000
  12. for idx, char in enumerate(plaintext_password, 1):
  13. value = ord(char) << idx
  14. rotated_bits = value >> 15
  15. value &= 0x7fff
  16. password ^= (value | rotated_bits)
  17. password ^= len(plaintext_password)
  18. password ^= 0xCE4B
  19. return str(hex(password)).upper()[2:]