Selaa lähdekoodia

feat: 1.0 Beta!

Support to choose the encryptor's language
Li4n0 6 vuotta sitten
vanhempi
commit
47335c0a69
2 muutettua tiedostoa jossa 76 lisäystä ja 64 poistoa
  1. 10 10
      hugo-encryptor.py
  2. 66 54
      shortcodes/hugo-encryptor.html

+ 10 - 10
hugo-encryptor.py

@@ -1,22 +1,20 @@
 # coding=utf-8
 import os
 import base64
+import hashlib
 
 from bs4 import BeautifulSoup
 from Crypto.Cipher import AES
 
 
 class AESCrypt(object):
-    LEN = 16
+    LEN = 32
     def __init__(self, key: str):
-        if len(key) > AESCrypt.LEN:
-            raise ValueError('password too long')
-
-        self.key = key.encode().ljust(AESCrypt.LEN, b'\x00')
+        self.key = key.encode()
         self.mode = AES.MODE_CBC
 
     def encrypt(self, text: bytes):
-        cryptor = AES.new(self.key, self.mode, self.key)
+        cryptor = AES.new(self.key, self.mode, self.key[16:])
         padlen = AESCrypt.LEN - len(text) % AESCrypt.LEN
         padlen = padlen if padlen != 0 else AESCrypt.LEN
         text += chr(padlen)*padlen
@@ -25,6 +23,7 @@ class AESCrypt(object):
 
 
 if __name__ == '__main__':
+    md5 = hashlib.md5()
     for dirpath, dirnames, filenames in os.walk('./public/post'):
         for filename in filenames:
             if not filename.lower().endswith('.html'):
@@ -32,16 +31,17 @@ if __name__ == '__main__':
 
             fullpath = os.path.join(dirpath, filename)
 
-            soup = BeautifulSoup(open(fullpath))
-            block = soup.find('div', {'id': 'hugo-encryptor'})
+            soup = BeautifulSoup(open(fullpath),'lxml')
+            block = soup.find('cipher-text')
 
             if block is None:
                 pass
 
             else:
                 print(fullpath)
-
-                cryptor = AESCrypt(block['data-password'])
+                md5.update(block['data-password'].encode('utf-8'))
+                key = md5.hexdigest()
+                cryptor = AESCrypt(key)
                 text = ''.join(map(str, block.contents))
                 written = base64.b64encode(cryptor.encrypt(text))
 

+ 66 - 54
shortcodes/hugo-encryptor.html

@@ -14,13 +14,24 @@ your content
 {{/* DEFAULTS */}}
 
 <hugo-encryptor>
+  {{ if eq .Site.Params.hugoEncryptorLanguage "en-us" }}
+  <p>The following content is password protected.</p>
+  {{ else }}
   <p>以下内容被密码保护</p>
-  <input id="hugo-encryptor-password" placeholder="请输入密码" />
-  <input
-    type="button"
-    value="提交"
-    onclick="hugoDecrypt(document.getElementById('hugo-encryptor-password').value,'input')"
-  />
+  {{ end }}
+  <div class='hugo-encryptor-form'>
+    <input
+      class="hugo-encryptor-input"
+      id="hugo-encryptor-password"
+      placeholder='{{ if eq .Site.Params.hugoEncryptorLanguage "en-us" }}Please input the password{{ else }}请输入密码{{ end }}'
+    />
+    <input
+      class="hugo-encryptor-button"
+      type="button"
+      value='{{ if eq .Site.Params.hugoEncryptorLanguage "en-us" }}Submit{{ else }}提交{{ end }}'
+      onclick="hugoDecrypt(CryptoJS.MD5(document.getElementById('hugo-encryptor-password').value).toString(),'input')"
+    />
+  </div>
   <cipher-text data-password="{{ .Get 0 }}" style="display:none;">
     <p id="verifyText" style="display:none;">
       The quick brown fox jumps over the lazy dog
@@ -29,58 +40,59 @@ your content
   </cipher-text>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js"></script>
   <script>
-    let cipher = document.getElementsByTagName("cipher-text")[0];
-    const storageKey = location.pathname + "password";
-    const userStorage = {{ if .Site.Params.hugoEncryptorStorage }} window['{{.Site.Params.hugoEncryptorStorage}}Storage'] {{ else }} localStorage {{ end }};
-    /**
-     * @name: decrypt
-     * @description: decrypt cipher text by password
-     * @param {String} cipher_text
-     * @param {String} password
-     * @return:{String} decryptedData
-     */
-    const decrypt = function(cipher_text, password) {
-      password = password.padEnd(16, "\0");
-      let key = CryptoJS.enc.Utf8.parse(password);
-      let decryptedData = CryptoJS.AES.decrypt(cipher_text, key, {
-        iv: key,
-        mode: CryptoJS.mode.CBC,
-        padding: CryptoJS.pad.Pkcs7
-      });
-      return decryptedData.toString(CryptoJS.enc.Utf8);
-    };
-    /**
-     * @name:hugoDecrypt
-     * @description: judge the password ,and decrypt post
-     * @param {String} password
-     * @param {String} type
-     */
-    const hugoDecrypt = function(password, type) {
-      try {
-        let cipher_text = cipher.innerText;
-        let decrypted_text = decrypt(cipher_text, password);
-        if (
-          decrypted_text.includes("The quick brown fox jumps over the lazy dog")
-        ) {
-          cipher.parentElement.outerHTML = decrypted_text;
-          userStorage.setItem(storageKey, password);
-        } else {
+      let cipher = document.getElementsByTagName("cipher-text")[0];
+      const storageKey = location.pathname + "password";
+      const userStorage = {{ if .Site.Params.hugoEncryptorStorage }} window['{{.Site.Params.hugoEncryptorStorage}}Storage'] {{ else }} localStorage {{ end }};
+      /**
+       * @name: decrypt
+       * @description: decrypt cipher text by password
+       * @param {String} cipher_text
+       * @param {String} password
+       * @return:{String} decryptedData
+       */
+      const decrypt = function(cipher_text, password) {
+        let key = CryptoJS.enc.Utf8.parse(password);
+        let iv = CryptoJS.enc.Utf8.parse(password.substr(16));
+
+        let decryptedData = CryptoJS.AES.decrypt(cipher_text, key, {
+          iv: iv,
+          mode: CryptoJS.mode.CBC,
+          padding: CryptoJS.pad.Pkcs7
+        });
+        return decryptedData.toString(CryptoJS.enc.Utf8);
+      };
+      /**
+       * @name:hugoDecrypt
+       * @description: judge the password ,and decrypt post
+       * @param {String} password
+       * @param {String} type
+       */
+      const hugoDecrypt = function(password, type) {
+        try {
+          let cipher_text = cipher.innerText;
+          let decrypted_text = decrypt(cipher_text, password);
+          if (
+            decrypted_text.includes("The quick brown fox jumps over the lazy dog")
+          ) {
+            cipher.parentElement.outerHTML = decrypted_text;
+            userStorage.setItem(storageKey, password);
+          } else {
+            if (type === "input") {
+              alert('{{ if eq .Site.Params.hugoEncryptorLanguage "en-us" }}wrong password{{ else }}密码错误{{ end }}');
+            } else if (type === "storage") {
+              userStorage.removeItem(storageKey);
+            }
+          }
+          document.getElementById("verifyText").outerHTML = "";
+        } catch (error) {
+          // console.log(error);
           if (type === "input") {
-            alert("密码错误!");
+            alert('{{ if eq .Site.Params.hugoEncryptorLanguage "en-us" }}wrong password{{ else }}密码错误{{ end }}');
           } else if (type === "storage") {
-            userStorage.removeItem(storageKey);
+            userStorage.removeItem(location.pathname + "password");
           }
         }
-        document.getElementById("verifyText").outerHTML = "";
-      } catch (error) {
-        console.log(error);
-        if (type === "input") {
-          alert("密码错误!");
-        } else if (type === "storage") {
-          userStorage.removeItem(location.pathname + "password");
-        }
-      }
-    };
+      };
   </script>
   <script>
     window.onload = () => {