如果將 Hugo 文章加密?
Step1 修改 Single.html
在 layouts/_default/single.html 中找到{{- if .Content }}段落,將段落改成以下 code
{{- if .Content }}
<div class="post-content">
{{ if .Params.password }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<div id="protected">
<input type="password" id="postPassword" placeholder="輸入密碼" />
<button id="unlockBtn">解鎖</button>
</div>
<div id="postContent" style="display:none; margin-top:1rem;"></div>
<script>
const secret = "{{ .Params.password }}";
// ✅ 保留 HTML 標籤
const plaintext = {{ .Content | jsonify | safeJS }};
const ciphertext = CryptoJS.AES.encrypt(plaintext, secret).toString();
document.getElementById("unlockBtn").addEventListener("click", function () {
const pwd = document.getElementById("postPassword").value;
try {
const bytes = CryptoJS.AES.decrypt(ciphertext, pwd);
const decrypted = bytes.toString(CryptoJS.enc.Utf8);
if (decrypted) {
document.getElementById("protected").style.display = "none";
document.getElementById("postContent").innerHTML = decrypted;
document.getElementById("postContent").style.display = "block";
} else {
alert("密碼錯誤,請再試一次。");
}
} catch (e) {
alert("解密失敗。");
}
});
</script>
{{ else }}
{{- if not (.Param "disableAnchoredHeadings") }}
{{- partial "anchored_headings.html" .Content -}}
{{- else }}
{{ .Content }}
{{- end }}
{{ end }}
</div>
{{- end }}
Step2 文章 Front Matter
文章 Front Matter 加上以下
password: "mypassword"
Step3 首頁也顯示文章已加密
在 layouts/_default/list.html 找到 div class=“entry-content"段落,將段落改成以下 code
<div class="entry-content">
<p>
{{ if $page.Params.password }}
🔒 文章已加密,請點擊標題輸入密碼閱讀全文。
{{ else }}
{{ $page.Summary | plainify | htmlUnescape }}{{ if $page.Truncated }}...{{ end }}
{{ end }}
</p>
</div>
大功告成! 快來實作看看吧!!