OpenPGP.js将PGP块传递给javascript变量

时间:2015-08-15 12:11:25

标签: javascript gnupg pgp openpgp openpgp.js

我使用OpenPGP.js设置了一个加密邮件的文件。我需要将PGP块设置为javascript变量,以便将其传递给加密/解密函数。当我正常粘贴它时,它会将脚本作为多行分解。我尝试过使用php json_encode - 这会传递给encrypt函数,但是readArmored会出现错误"未知的ASCII装甲类型"。

将此变量从php传递到javascript的最佳方法是什么,或者如何正确解码以便在javascript中使用?

以下是代码:

<!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 个答案:

答案 0 :(得分:0)

删除&#39; &#39;解决了这个问题:

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

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