hugo-encryptor.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # coding=utf-8
  2. import os
  3. import base64
  4. import hashlib
  5. from bs4 import BeautifulSoup
  6. from Crypto.Cipher import AES
  7. class AESCrypt(object):
  8. LEN = 32
  9. def __init__(self, key: str):
  10. self.key = key.encode()
  11. self.mode = AES.MODE_CBC
  12. def encrypt(self, text: bytes):
  13. cryptor = AES.new(self.key, self.mode, self.key[16:])
  14. padlen = AESCrypt.LEN - len(text) % AESCrypt.LEN
  15. padlen = padlen if padlen != 0 else AESCrypt.LEN
  16. text += (chr(padlen)*padlen).encode('utf8')
  17. return cryptor.encrypt(text)
  18. if __name__ == '__main__':
  19. for dirpath, dirnames, filenames in os.walk('./public'):
  20. for filename in filenames:
  21. if not filename.lower().endswith('.html'):
  22. continue
  23. fullpath = os.path.join(dirpath, filename)
  24. soup = BeautifulSoup(open(fullpath),'lxml')
  25. block = soup.find('cipher-text')
  26. if block is None:
  27. pass
  28. else:
  29. print(fullpath)
  30. md5 = hashlib.md5()
  31. md5.update(block['data-password'].encode('utf-8'))
  32. key = md5.hexdigest()
  33. cryptor = AESCrypt(key)
  34. text = ''.join(map(str, block.contents))
  35. written = base64.b64encode(cryptor.encrypt(text.encode('utf8')))
  36. del block['data-password']
  37. block.string = written.decode()
  38. with open(fullpath, 'w') as f:
  39. f.write(str(soup))