hugo-encrypt.html 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. {{- $passphrase := $.Scratch.Set "passphrase" (.Get 0) -}}
  16. {{ else if .Site.Params.Password }}
  17. {{- $passphrase := $.Scratch.Set "passphrase" .Site.Params.Password -}}
  18. {{ else }}
  19. {{- $passphrase -}}
  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="{{ $.Scratch.Get "passphrase" }}" style="display:none;">
  36. <!-- Do not indent the following two lines -->
  37. {{ .Inner }}
  38. </cipher-text>
  39. <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/core.js"></script>
  40. <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/hmac.js"></script>
  41. <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/sha1.js"></script>
  42. <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script>
  43. <script>
  44. let cipher = document.getElementsByTagName("cipher-text")[0];
  45. const storageKey = location.pathname + "password";
  46. const userStorage = {{ if .Site.Params.hugoEncryptStorage }} window['{{.Site.Params.hugoEncryptStorage}}Storage'] {{ else }} localStorage {{ end }};
  47. /**
  48. * Encodes a utf8 string as a byte array.
  49. * @param {String} str
  50. * @returns {Uint8Array}
  51. */
  52. function str2buf(str) {
  53. return new TextEncoder("utf-8").encode(str);
  54. }
  55. /**
  56. * Decodes a byte array as a utf8 string.
  57. * @param {Uint8Array} buffer
  58. * @returns {String}
  59. */
  60. function buf2str(buffer) {
  61. return new TextDecoder("utf-8").decode(buffer);
  62. }
  63. /**
  64. * Decodes a string of hex to a byte array.
  65. * @param {String} hexStr
  66. * @returns {Uint8Array}
  67. */
  68. function hex2buf(hexStr) {
  69. return new Uint8Array(hexStr.match(/.{2}/g).map(h => parseInt(h, 16)));
  70. }
  71. /**
  72. * Given a passphrase, this generates a crypto key
  73. * using `PBKDF2` with SHA256 and 1000 iterations.
  74. * If no salt is given, a new one is generated.
  75. * The return value is an array of `[key, salt]`.
  76. * @param {String} passphrase
  77. * @param {UInt8Array} salt [salt=random bytes]
  78. * @returns {Promise<[CryptoKey,UInt8Array]>}
  79. */
  80. function deriveKey(passphrase, salt) {
  81. salt = salt || crypto.getRandomValues(new Uint8Array(8));
  82. return crypto.subtle
  83. .importKey("raw", str2buf(passphrase), "PBKDF2", false, ["deriveKey"])
  84. .then(key =>
  85. crypto.subtle.deriveKey(
  86. { name: "PBKDF2", salt, iterations: 1000, hash: "SHA-256" },
  87. key,
  88. { name: "AES-GCM", length: 256 },
  89. false,
  90. ["encrypt", "decrypt"],
  91. ),
  92. )
  93. .then(key => [key, salt]);
  94. }
  95. /**
  96. * Given a key and ciphertext (in the form of a string) as given by `encrypt`,
  97. * this decrypts the ciphertext and returns the original plaintext
  98. * @param {String} passphrase
  99. * @param {String} saltIvCipherHex
  100. * @returns {Promise<String>}
  101. */
  102. function decrypt(passphrase, saltIvCipherHex) {
  103. const [salt, iv, data] = saltIvCipherHex.split("-").map(hex2buf);
  104. return deriveKey(passphrase, salt)
  105. .then(([key]) => crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, data))
  106. .then(v => buf2str(new Uint8Array(v)));
  107. }
  108. /**
  109. * Needed to convert markdown within the decrypted text to html
  110. */
  111. function interpreteMarkdown(input) {
  112. var converter = new showdown.Converter()
  113. return converter.makeHtml(input)
  114. }
  115. /**
  116. * @name:hugoDecrypt
  117. * @description: judge the password ,and decrypt post
  118. * @param {String} password
  119. * @param {String} type
  120. */
  121. const hugoDecrypt = function(password, type) {
  122. try {
  123. decrypt(password, cipher.innerText).then(function(res) {
  124. /**
  125. * calculate sha1 of decrypted text and check if it
  126. * matches the sha1 at the bottom of the decrypted text
  127. * to get the same hash that was added during encryption we
  128. * need to remove the last line
  129. */
  130. var hash = CryptoJS.SHA1(res.replace(/\r?\n?[^\r\n]*$/, ""));
  131. var result = CryptoJS.enc.Hex.stringify(hash);
  132. if ( res.includes(result) ) {
  133. cipher.parentElement.outerHTML = interpreteMarkdown(res);
  134. userStorage.setItem(storageKey, password);
  135. document.getElementById("sha1sum").innerHTML = "sha1: " + result;
  136. } else {
  137. if (type === "input") {
  138. alert('{{ i18n "wrongpwd" }}');
  139. } else if (type === "storage") {
  140. userStorage.removeItem(storageKey);
  141. }
  142. }
  143. });
  144. } catch (error) {
  145. if (type === "input") {
  146. alert('{{ i18n "wrongpwd" }}');
  147. } else if (type === "storage") {
  148. userStorage.removeItem(location.pathname + "password");
  149. }
  150. }
  151. };
  152. </script>
  153. <script>
  154. window.onload = () => {
  155. if (userStorage.getItem(storageKey)) {
  156. hugoDecrypt(userStorage.getItem(storageKey), "storage");
  157. }
  158. };
  159. </script>
  160. </hugo-encrypt>