protection.py 869 B

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