hugo-encryptor.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # coding=utf-8
  2. import os
  3. import base64
  4. from bs4 import BeautifulSoup
  5. from Crypto.Cipher import AES
  6. class DESCrypt(object):
  7. LEN = 16
  8. def __init__(self, key: str):
  9. if len(key) > DESCrypt.LEN:
  10. raise ValueError('password too long')
  11. self.key = key.encode().ljust(DESCrypt.LEN, b'\x00')
  12. self.mode = AES.MODE_CBC
  13. def encrypt(self, text: bytes):
  14. cryptor = AES.new(self.key, self.mode, self.key)
  15. padlen = DESCrypt.LEN - len(text) % DESCrypt.LEN
  16. padlen = padlen if padlen != 0 else DESCrypt.LEN
  17. for i in range(padlen):
  18. text += chr(i+1).encode()
  19. return cryptor.encrypt(text)
  20. if __name__ == '__main__':
  21. for dirpath, dirnames, filenames in os.walk('.'):
  22. for filename in filenames:
  23. if not filename.lower().endswith('.html'):
  24. continue
  25. fullpath = os.path.join(dirpath, filename)
  26. soup = BeautifulSoup(open(fullpath), features="html5lib")
  27. block = soup.find('div', {'id': 'hugo-encryptor'})
  28. if block is None:
  29. pass
  30. else:
  31. print(fullpath)
  32. cryptor = DESCrypt(block['data-password'])
  33. text = ''.join(map(str, block.contents)).encode()
  34. written = base64.b64encode(cryptor.encrypt(text))
  35. del block['data-password']
  36. block.string = written.decode()
  37. with open(fullpath, 'w') as f:
  38. f.write(str(soup))