简体   繁体   English

在没有服务器的环境中,如何密码保护文件(html)?

[英]How do I password protect a file (html) in a server-less environment?

Is it possible to password protect a file without the use of .htaccess, php, or localhost. 是否可以使用.htaccess,php或localhost密码保护文件。 Maybe with some type of encryption or an other method. 也许使用某种类型的加密或其他方法。

Yes, you can achieve pretty decent front-side encryption, thanks to the SubtleCrypto API . 是的, 借助SubtleCrypto API ,您可以实现相当不错的前端加密。
There is even a js port of openpgp . 甚至还有一个js端口openpgp

So yes, you could ultimately encode whatever data you wish as pgp message for instance, then require a password to decrypt it and use it. 所以是的,例如,您最终可以将所需的任何数据编码为pgp消息,然后需要密码来解密和使用它。

If you need to encrypt your message: 如果您需要加密邮件:

 (async function() { const cleartext = 'alert("an useless message")'; const msg = openpgp.message.fromText(cleartext); const ciphertext = await openpgp.encrypt({ message: msg, passwords: ["mypassword"], armor: true }); // you'd be better saving as a text file though, // ecnoding and new line characters matter console.log(ciphertext.data); })() .catch(console.error); 
 <script src="https://cdn.jsdelivr.net/npm/openpgp@4.3.0/dist/openpgp.min.js"></script> 

And then to decrypt it: 然后解密:

 (async function() { const password = prompt('enter password ("mypassword")'); // one of the results of previous snippet const encrypted = `-----BEGIN PGP MESSAGE----- Version: OpenPGP.js v4.3.0 Comment: https://openpgpjs.org wy4ECQMI61wIzRzOswzg/j6zhPvasbu97nt+XeD23m3UNnc8J3SqAGiogvn8 zqKD0lMB49BViJ8gQ7E/6If6vaCv9NBojjVgS9P2E7mROtZrbz5Z150ohcKV kDncF//Io6sb/5L/5AcLXBxCJzhQKIYwtIdHu9paWGpEto1z5EzOGzpZgg== =hMhM -----END PGP MESSAGE-----`; const decrypted = await openpgp.decrypt({ message: await openpgp.message.readArmored(encrypted), passwords: [password] }) const cleartext = decrypted.data; console.log(cleartext); new Function(cleartext)(); })() .catch(console.error); 
 <script src="https://cdn.jsdelivr.net/npm/openpgp@4.3.0/dist/openpgp.min.js"></script> 

No. Well, not anything that offers anything remotely secure. 不会。没有提供远程安全保护的产品。 You could hide a password in the javascript, maybe encoded as base64 and then compare the value of an input field to the stored base64 code, but anyone that knows anything about "view source" or javascript would easily be able to circumvent this. 您可以在javascript中隐藏一个密码,也许将其编码为base64,然后将输入字段的值与存储的base64代码进行比较,但是任何对“查看源代码”或javascript有所了解的人都可以轻松绕开它。

Password authentication and other sensitive information must be processed on the server side, where users can't get to it! 密码验证和其他敏感信息必须在服务器端进行处理,否则用户将无法访问!

Inspired by @Kaiido I developed a JavaScript Bookmarklet. 受@Kaiido的启发,我开发了一个JavaScript书签。 So, add it as a new bookmark in your browser and click on it to encrypt the current page. 因此,将其添加为浏览器中的新书签,然后单击它以加密当前页面。 You will be asked to insert a password and choose a location where to save the encrypted HTML page. 系统将要求您输入密码并选择保存加密HTML页面的位置。

javascript:(function (doc) {
    var password = prompt('Enter a password to encrypt this page'),
        js = doc.createElement('script');

    js.onload = function () {
        /* Get current page HTML and use a dirty workaround to convert relative paths to full URLs */
        var page = doc.documentElement.cloneNode(true);
        for (var attr of ['src', 'href']) {
            page.querySelectorAll('[' + attr + ']').forEach(function (node) {
                node[attr] = node[attr];
            });
        }

        /* All the magic belongs to openpgpjs.org */
        openpgp.encrypt({
            message: openpgp.message.fromText(page.outerHTML),
            passwords: [password]
        }).then(function (ciphertext) {
            var link = doc.createElement('a'),
                html = [
                    '<!DOCTYPE html>',
                    '<head>',
                    '  <meta charset="utf-8" />',
                    '</head>',
                    '<body>',
                    '  <textarea id="encryptedMessage" style="display:none">' + ciphertext.data + '</textarea>',
                    '  <script src="' + js.src + '"></script>',
                    '  <script>',
                    '    var field=document.getElementById("encryptedMessage");',
                    '    openpgp.message.readArmored(field.value).then(function(message){',
                    '      var decrypter=openpgp.decrypt({message:message,passwords:[prompt("Enter the password to decrypt this page")]});',
                    '      decrypter.then(function(plaintext){document.documentElement.innerHTML=plaintext.data});',
                    '      decrypter.catch(function(e){alert(String(e))});',
                    '    });',
                    '  </script>',
                    '</body>'
                ].join('\n');

            doc.body.appendChild(link);
            link.download = 'protected.html';
            link.href = 'data:text/html;,' + encodeURIComponent(html);
            link.click();
            doc.body.removeChild(link);
        });
    };

    /* This will fail if Content Security Policy prohibits embedded scripts */
    js.src = 'https://cdnjs.cloudflare.com/ajax/libs/openpgp/4.3.0/compat/openpgp.min.js';
    doc.body.appendChild(js);
})(document);

An example of encrypted page can be found here: http://fiddle.jshell.net/yjLwq0mx/show/light/ 可以在此处找到加密页面的示例: http : //fiddle.jshell.net/yjLwq0mx/show/light/

Yes you can encrypt any message using only JS without backend and without store password in your JS code. 是的,您可以仅使用JS加密任何消息,而无需在后端使用JS代码并且无需在JS代码中存储密码。 I will describe simple theoretical approach without technical details: 我将描述没有技术细节的简单理论方法:

Encryption: 加密:

  1. Create password (but not store it anywhere) 创建密码(但不要将其存储在任何地方)
  2. generate long complicated hash from that password (eg bcrypt ) (same password should produce always same hash not store it anywhere; ) 从该密码生成长而复杂的哈希(例如bcrypt )(相同的密码应始终产生相同的哈希,而不是将其存储在任何地方;)
  3. use that hash as key for symetric-key algorithm (eg ciphers AES ) to code your message. 使用该哈希值作为对称密钥算法 (例如AES的密钥来编码您的消息。

Decryption: 解密:

  1. ask user to type password 要求用户输入密码
  2. generate hash from that password (in same way like for encryption) 从该密码生成哈希(以与加密相同的方式)
  3. use that hash as key in symetric-key algorithm to decode message. 使用该哈希作为symetric-key算法中的密钥来解码消息。

As you can see, you don't need to store password anywhere in this approach. 如您所见,这种方法不需要在任何地方存储密码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM