I am in the process of creating a simple chrome extension that can encrypt and decrypt strings using openPGP's library. However, I can't seem to define openGPG and constantly get the error:
ReferenceError: openpgp is not defined
I have defined the openGPG library in my HTML file which I would think makes it globally available right?
My HTML & JS code is below
JS file with my encryption. Very early version, but just wanted to run it before define the keys and add that logic.
document.getElementById("encryptTest").addEventListener('click', () => {
console.log("Popup DOM fully loaded and parsed");
async function encryptString() {
// put keys in backtick (``) to avoid errors caused by spaces or tabs
const publicKeyArmored = `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`;
const privateKeyArmored = `-----BEGIN PGP PRIVATE KEY BLOCK-----
...
-----END PGP PRIVATE KEY BLOCK-----`; // encrypted private key
const passphrase = `yourPassphrase`; // what the private key is encrypted with
const { keys: [privateKey] } = await openpgp.key.readArmored(privateKeyArmored);
await privateKey.decrypt(passphrase);
const { data: encrypted } = await openpgp.encrypt({
message: openpgp.message.fromText('Hello, World!'), // input as Message object
publicKeys: (await openpgp.key.readArmored(publicKeyArmored)).keys, // for encryption
privateKeys: [privateKey] // for signing (optional)
});
console.log(encrypted); // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
const { data: decrypted } = await openpgp.decrypt({
message: await openpgp.message.readArmored(encrypted), // parse armored message
publicKeys: (await openpgp.key.readArmored(publicKeyArmored)).keys, // for verification (optional)
privateKeys: [privateKey] // for decryption
});
console.log(decrypted); // 'Hello, World!'
}
//We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
chrome.tabs.executeScript({
code: '(' + encryptString + ')();' //argument here is a string but function.toString() returns function's code
});
});
HTML File
<!DOCTYPE html>
<html>
<head>
<style>
body {
width: 350px;
height: 500px;
}
button {
height: 50px;
width: 150px;
outline: none;
}
input {
width: 95%;
padding: 5px;
margin-right: 15px;
margin-top: 50px;
}
.decrypt {
margin-top: 10px;
width: 150px;
height: 35px;
}
</style>
</head>
<body>
<h1>AIS PGP Exam Encryption</h1>
<button id="generateKey">Generate Key</button>
<button id="htmlGrabber">Get HTML</button>
<input placeholder="Private Key"></input>
<input placeholder="Message to Decrypt"></input>
<button class="decrypt">Decrypt Message</button>
<button id="encryptTest">Test</button>
</body>
<script src="../js/jquery-3.5.1.min.js"></script>
<script src="../js/openpgp.min.js"></script>
<script src="../js/encrypt.js"></script>
<script src="../js/htmlGrabber.js"></script>
</html>
I think the problem is that the function is isolated in your code. Also make sure to define it properly in your HTML file. Welcome to Stack Overflow :) !