简体   繁体   中英

How to simply encrypt a string with OpenPGP.js?

I just want to be able to do something like this:

function encryptString(string, publicKey) {
    // do stuff....
    return encryptedString;
}

I had a look at OpenPGP and JSEncrypt. JSEncrypt doesn't seem to work at all. Just returns false. And OpenPHP requires asynchronous calls when I need a realtime synchronous calculation.

Any thoughts as to what I could be doing wrong?

For JSEncrypt, the false I am getting is most likely due to my key being very long. This library seems to support short strings.

Im a bit lost. Any nudges in the right direction would be appreciated?

This worked for me (although it's certainly not elegant):

function pgp_encryptValues(cvv, cc)
{
    var keyId = '{{ $keyId }}';
    var base64EncodedPublicKey = '{{ $publicKey }}';

    var CardDetails = {
        "number": cc,
        "cvv"   : cvv
       };
       const stringified      =  JSON.stringify(CardDetails);
       const pciEncryptionKey = base64EncodedPublicKey;
       const decodedPublicKey = atob(pciEncryptionKey)

        async function setPgpCode()
        {
            const options = {
             message: openpgp.message.fromText(stringified),
                publicKeys: (await openpgp.key.readArmored(decodedPublicKey)).keys
            }
            return openpgp.encrypt(options).then((ciphertext) =>
            {
                var cipherResultEncoded = btoa(ciphertext.data);
                jQuery("#encryptedData").val(cipherResultEncoded);
                jQuery("#keyID").val(keyId);
                return {
                    encryptedData: btoa(ciphertext.data),
                    keyId: keyId
                }
            })
        };

        if (promiseStarted) {
            while (promiseStarted)
            {
                // wait til its done...
            }
        }

        promiseStarted   = true;
        promiseEnded     = false;
        setPgpCode();
        promiseStarted   = false;
        promiseEnded     = true;

    }

Very hackey and I'll probably improve it over time, but at least it works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM