1

I am trying to use the Encrypt and decrypt String data with PGP keys example from openpgp.js but I struggle to make it work inside Firefox. openpgp.js doc

I create a keypair.

const openpgp = window.openpgp; // use as CommonJS, AMD, ES6 module or via window.openpgp

 openpgp.config.compression = openpgp.enums.compression.zlib

var options = {
 userIds: [{ name: 'Alicee', email:     '[email protected]' }],
  numBits: 2048,
  passphrase: 'secretttoo'
};

var publicKeyAlice;
var privateKeyAlice;

 openpgp.generateKey(options).then(key     => {
privateKeyAlice = key.privateKeyArmored;
publicKeyAlice = key.publicKeyArmored;
console.log('Key generated');
console.log(privateKeyAlice);
 console.log(publicKeyAlice);

});

The keys I get consoled out are used for the example of string encryption by openpgp.js

const pubkey = '-----BEGIN PGP PUBLIC KEY BLOCK----- Version: OpenPGP.js v4.1.1'
const privkey = '-----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v4.1.1'
const passphrase = `secretttoo` //what the privKey is encrypted with


const encryptDecryptFunction = async() => {
const privKeyObj = (await openpgp.key.readArmored(privkey)).keys[0]
await privKeyObj.decrypt(passphrase)

const options = {
    message: openpgp.message.fromText('Hello, World!'),       // input as Message object
    publicKeys: (await openpgp.key.readArmored(pubkey)).keys, // for encryption
    privateKeys: [privKeyObj]                                 // for signing (optional)
}

openpgp.encrypt(options).then(ciphertext => {
    encrypted = ciphertext.data // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
    return encrypted
})
.then(encrypted => {
    const options = {
        message: await openpgp.message.readArmored(encrypted),    // parse armored message
        publicKeys: (await openpgp.key.readArmored(pubkey)).keys, // for verification (optional)
        privateKeys: [privKeyObj]                                 // for decryption
    }

    openpgp.decrypt(options).then(plaintext => {
        console.log(plaintext.data)
        return plaintext.data // 'Hello, World!'
    })

 })
}

encryptDecryptFunction();

I get the following error in browser console:

SyntaxError: missing } after property list[Learn More] openpgp testing.html:153:27 note: { opened at line 152, column 24

How does a simple pgp encryption of string work using openpgp.js?

2 Answers 2

2

To actually answer your question over suggesting another library, the fix is in changeing the syntax from

message: await openpgp.message.readArmored(encrypted),

to

message: openpgp.message.readArmored(encrypted),

Then it should works since that method is not async (anymore?)

Here your example modified for symetric encryption (that's why I couldn't use jsencrypt as Nikola suggested:

 <script lang="JavaScript" src="openpgp.js"></script>
 <script lang="JavaScript">
    const options = {
        message : window.openpgp.message.fromText('Hello, World!'),     
        passwords : ['pw'],
        armor : false
    }

    window.openpgp.encrypt(options).then(ciphertext => {
        encrypted = ciphertext.message 
        return encrypted
    }).then(encrypted => {
        const options = {
            message : encrypted,   
            passwords : ['pw']                               
        }
        window.openpgp.decrypt(options).then(plaintext => {
            console.log(plaintext.data)
            alert(plaintext.data)
            return plaintext.data 
        })
    })       
</script>
Sign up to request clarification or add additional context in comments.

Comments

2

The library you're trying to use doesn't look that promissing for asymetric cryptography. If you're open for suggestion try using this one.

Here is example code :

<div class="container">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/2.3.1/jsencrypt.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    <script type="text/javascript">
        // Call this code when the page is done loading.
        jQuery(function () {
            // Run a quick encryption/decryption when they click.
            jQuery('#testme').click(function () {
                // Encrypt with the public key...
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey($('#pubkey').val());
                var encrypted = encrypt.encrypt($('#input').val());
                console.log(encrypted);
                // Decrypt with the private key...
                var decrypt = new JSEncrypt();
                decrypt.setPrivateKey($('#privkey').val());
                var uncrypted = decrypt.decrypt(encrypted);
                // Now a simple check to see if the round-trip worked.
                if (uncrypted == $('#input').val()) {
                    alert('It works!!!');
                }
                else {
                    alert('Something went wrong....');
                }
            });
        });
    </script>
    <label for="privkey">Private Key</label><br/>
<textarea id="privkey" rows="15" cols="65">-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ
WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR
aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB
AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv
xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH
m7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd
8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF
z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5
rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM
V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe
aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil
psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz
uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876
-----END RSA PRIVATE KEY-----</textarea><br/>
    <label for="pubkey">Public Key</label><br/>
<textarea id="pubkey" rows="15" cols="65">-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtN
FOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76
xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4
gwQco1KRMDSmXSMkDwIDAQAB
-----END PUBLIC KEY-----</textarea><br/>
    <label for="input">Text to encrypt:</label><br/>
    <textarea id="input" name="input" type="text" rows=4 cols=70>This is a test!</textarea><br/>
    <input id="testme" type="button" value="Test Me!!!"/><br/>
</div>

3 Comments

Thanks for your suggestion. I am open to other libs as its just for my training. Do you the methods of this lib to create the keypairs inside the browser instead of using openssl genrsa -out rsa_1024_priv.pem 1024 ?
this one works well. Fast and easy to play around. Thnaks
encrypt.encrypt() returns false for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.