hugo-encrypt.html 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. {{/*
  2. ## Hugo Encrypt
  3. ### Params:
  4. - `password`:
  5. require param
  6. - Simple
  7. {{< hugo-encrypt "your password" >}}
  8. your content
  9. {{< /hugo-encrypt >}}
  10. */}}
  11. {{/* DEFAULTS */}}
  12. {{ $_hugo_config := `{ "version": 1 }` }}
  13. <hugo-encrypt>
  14. {{ if .Get 0 }}
  15. {{- $password := $.Scratch.Set "password" (.Get 0) -}}
  16. {{ else if .Site.Params.Passwoird }}
  17. {{- $password := $.Scratch.Set "password" .Site.Params.Password -}}
  18. {{ else }}
  19. {{- $password -}}
  20. {{ end }}
  21. <p>{{ i18n "protectedbypwd" }}</p>
  22. <div class='hugo-encrypt-form'>
  23. <input
  24. class="hugo-encrypt-input"
  25. id="hugo-encrypt-password"
  26. placeholder='{{ i18n "inputpassword" }}'
  27. />
  28. <input
  29. class="hugo-encrypt-button"
  30. type="button"
  31. value='{{ i18n "decrypt" }}'
  32. id="button" onclick="hugoDecrypt(document.getElementById('hugo-encrypt-password').value,'input')"
  33. />
  34. </div>
  35. <cipher-text data-password="{{ $password }}" style="display:none;">
  36. <!-- Do not indent the following two lines -->
  37. <p id="verifyText" style="display:none;">The quick brown fox jumps over the lazy dog</p>
  38. {{ .Inner }}
  39. </cipher-text>
  40. <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script>
  41. <script>
  42. let cipher = document.getElementsByTagName("cipher-text")[0];
  43. const storageKey = location.pathname + "password";
  44. const userStorage = {{ if .Site.Params.hugoEncryptStorage }} window['{{.Site.Params.hugoEncryptStorage}}Storage'] {{ else }} localStorage {{ end }};
  45. /**
  46. * Encodes a utf8 string as a byte array.
  47. * @param {String} str
  48. * @returns {Uint8Array}
  49. */
  50. function str2buf(str) {
  51. return new TextEncoder("utf-8").encode(str);
  52. }
  53. /**
  54. * Decodes a byte array as a utf8 string.
  55. * @param {Uint8Array} buffer
  56. * @returns {String}
  57. */
  58. function buf2str(buffer) {
  59. return new TextDecoder("utf-8").decode(buffer);
  60. }
  61. /**
  62. * Decodes a string of hex to a byte array.
  63. * @param {String} hexStr
  64. * @returns {Uint8Array}
  65. */
  66. function hex2buf(hexStr) {
  67. return new Uint8Array(hexStr.match(/.{2}/g).map(h => parseInt(h, 16)));
  68. }
  69. /**
  70. * Given a passphrase, this generates a crypto key
  71. * using `PBKDF2` with SHA256 and 1000 iterations.
  72. * If no salt is given, a new one is generated.
  73. * The return value is an array of `[key, salt]`.
  74. * @param {String} passphrase
  75. * @param {UInt8Array} salt [salt=random bytes]
  76. * @returns {Promise<[CryptoKey,UInt8Array]>}
  77. */
  78. function deriveKey(passphrase, salt) {
  79. salt = salt || crypto.getRandomValues(new Uint8Array(8));
  80. return crypto.subtle
  81. .importKey("raw", str2buf(passphrase), "PBKDF2", false, ["deriveKey"])
  82. .then(key =>
  83. crypto.subtle.deriveKey(
  84. { name: "PBKDF2", salt, iterations: 1000, hash: "SHA-256" },
  85. key,
  86. { name: "AES-GCM", length: 256 },
  87. false,
  88. ["encrypt", "decrypt"],
  89. ),
  90. )
  91. .then(key => [key, salt]);
  92. }
  93. /**
  94. * Given a key and ciphertext (in the form of a string) as given by `encrypt`,
  95. * this decrypts the ciphertext and returns the original plaintext
  96. * @param {String} passphrase
  97. * @param {String} saltIvCipherHex
  98. * @returns {Promise<String>}
  99. */
  100. function decrypt(passphrase, saltIvCipherHex) {
  101. const [salt, iv, data] = saltIvCipherHex.split("-").map(hex2buf);
  102. return deriveKey(passphrase, salt)
  103. .then(([key]) => crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, data))
  104. .then(v => buf2str(new Uint8Array(v)));
  105. }
  106. /**
  107. * The html entities in the decrypted text need to be decoded
  108. * before converting any markdown to html
  109. */
  110. function htmlDecode(input){
  111. var doc = new DOMParser().parseFromString(input, "text/html");
  112. return doc.documentElement.textContent;
  113. }
  114. /**
  115. * Needed to convert markdown within the decrypted text to html
  116. */
  117. function interpreteMarkdown(input) {
  118. var converter = new showdown.Converter()
  119. return converter.makeHtml(input)
  120. }
  121. /**
  122. * @name:hugoDecrypt
  123. * @description: judge the password ,and decrypt post
  124. * @param {String} password
  125. * @param {String} type
  126. */
  127. const hugoDecrypt = function(password, type) {
  128. try {
  129. decrypt(password, cipher.innerText).then(function(res) {
  130. if ( res.includes("The quick brown fox jumps over the lazy dog") ) {
  131. cipher.parentElement.outerHTML = interpreteMarkdown(htmlDecode(res));
  132. userStorage.setItem(storageKey, password);
  133. document.getElementById("verifyText").outerHTML = "";
  134. } else {
  135. if (type === "input") {
  136. alert('{{ i18n "wrongpwd" }}');
  137. } else if (type === "storage") {
  138. userStorage.removeItem(storageKey);
  139. }
  140. }
  141. });
  142. } catch (error) {
  143. if (type === "input") {
  144. alert('{{ i18n "wrongpwd" }}');
  145. } else if (type === "storage") {
  146. userStorage.removeItem(location.pathname + "password");
  147. }
  148. }
  149. };
  150. </script>
  151. <script>
  152. window.onload = () => {
  153. if (userStorage.getItem(storageKey)) {
  154. hugoDecrypt(userStorage.getItem(storageKey), "storage");
  155. }
  156. };
  157. </script>
  158. </hugo-encrypt>