hugo-encryptor.py 1.4 KB

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