hugo-encryptor.html 4.6 KB

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