无需Node.js,能否在浏览器中使用OpenPGP.js?求实现示例
Can You Use OpenPGP.js Without Node.js?
Absolutely! That claim is totally accurate — OpenPGP.js is built to work smoothly in browser environments, no Node.js required at all. You just need the library files, a modern browser (like Firefox, Chrome, etc.), and a basic HTML file to get started.
Here's a step-by-step breakdown with a working example:
How to Set It Up
- First, grab the OpenPGP.js package you mentioned. Inside the zip file, look for the
distfolder — it contains pre-built browser-ready scripts likeopenpgp.min.js(the minified version perfect for production use). - Create a simple
index.htmlfile, and include the library using a standard<script>tag pointing to the localopenpgp.min.jsfile.
Working Example Code
Here’s a minimal, runnable example that generates a key pair, encrypts a message, then decrypts it — all directly in the browser:
<!DOCTYPE html> <html> <head> <title>OpenPGP.js Browser Demo</title> <!-- Include the local OpenPGP.js script --> <script src="./openpgp.min.js"></script> </head> <body> <button onclick="runDemo()">Run Demo</button> <pre id="output"></pre> <script> async function runDemo() { const output = document.getElementById('output'); output.textContent = 'Generating key pair...'; // Generate an RSA key pair const { privateKey, publicKey } = await openpgp.generateKey({ type: 'rsa', rsaBits: 2048, userIDs: [{ name: 'Test User', email: 'test@example.com' }], passphrase: 'your-strong-passphrase' // Optional but highly recommended for private key protection }); output.textContent += '\nKey pair generated!\nEncrypting message...'; // Encrypt a message with the public key const encrypted = await openpgp.encrypt({ message: await openpgp.createMessage({ text: 'Hello, OpenPGP.js in browser!' }), encryptionKeys: publicKey }); output.textContent += '\nEncrypted message:\n' + encrypted + '\n\nDecrypting message...'; // Decrypt the message with the private key const decrypted = await openpgp.decrypt({ message: await openpgp.readMessage({ armoredMessage: encrypted }), decryptionKeys: await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: privateKey }), passphrase: 'your-strong-passphrase' }) }); output.textContent += '\nDecrypted message:\n' + decrypted.data; } </script> </body> </html>
Quick Notes
- Ensure the
openpgp.min.jsfile is in the same folder as yourindex.html, or adjust thesrcpath to match where you stored the library. - The example uses async/await, which works in all modern browsers. If you need to support older browsers, you can rewrite it using promise chains with
.then(). - Always treat your private key like sensitive data — if you use a passphrase, make sure it’s strong and only shared with trusted parties.
内容的提问来源于stack exchange,提问作者Anware
相关产品推荐
相关产品推荐

