OpenPGP.js passing PGP block to javascript variable

517 Views Asked by At

I have setup a file using OpenPGP.js which encrypts a message. I need to set the PGP blocks to a javascript variable so i can pass it to the encrypt/decrypt functions. When I paste it in normally it breaks the script as its multiple lines. I have tried using php json_encode - this passes to the encrypt function but readArmored gets an error "Unknown ASCII armor type".

What is the best way to pass this variable from php to javascript, or how can i decode it properly for use in javascript?

Here is the code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="jquery.min.js"></script>
    <script src="openpgp.js"></script>
</head>
<body>

<p>
    Private:<br>
    <textarea id="private" style="width: 500px; height: 100px;"></textarea>
</p>
<p>
    Passphrase:<br>
    <input id="passphrase" style="width: 500px;">
</p>
<p>
    Public:<br>
    <textarea id="public" style="width: 500px; height: 100px;"></textarea>
</p>
<p>
    Encrypted:<br>
    <textarea id="encrypted" style="width: 500px; height: 100px;"></textarea>
</p>
<p>
    Decrypted:<br>
    <textarea id="decrypted" style="width: 500px; height: 100px;"></textarea>
</p>

<?php
$privateKey = "-----BEGIN PGP PRIVATE KEY BLOCK-----
...
-----END PGP PRIVATE KEY BLOCK-----";
$privateKey = json_encode($privateKey);

$publicKey = "-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----";
$publicKey = json_encode($publicKey);
?>
<script>

var privateKey = '<?php echo $privateKey; ?>';
var publicKey = '<?php echo $publicKey; ?>';
var passcode = 'pass1234';
$('#passphrase').val(passcode);
$('#private').val(privateKey);
$('#public').val(publicKey);
encrypt(publicKey, 'Hello!!!');

function encrypt(pubkey, message){
    var publicKey = openpgp.key.readArmored(pubkey);
    console.log(publicKey);
    openpgp.encryptMessage(publicKey.keys, message).then(function(pgpMessage) {
        // success
        $('#encrypted').val(pgpMessage);

    }).catch(function(error) {
        // failure
        console.log(error);
    });
}

</script>
</body>
</html>
1

There are 1 best solutions below

0
On BEST ANSWER

Removing the ' ' solved the issue:

var privateKey = '<?php echo $privateKey; ?>';
var publicKey = '<?php echo $publicKey; ?>';

To

var privateKey = <?php echo $privateKey; ?>;
var publicKey = <?php echo $publicKey; ?>;