Source code

Download source archive ↓

src/openpyxl/utils/protection.py

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