如何在 openpgp JS 中将参数消息作为文本传递

How to pass parameter message as text in openpgp JS

我想做什么:

公钥在文件 keys.js 中进行了硬编码,并像这样导出:

const publicKey = `-----BEGIN PGP PUBLIC KEY BLOCK-----

xsBNBGDgi3gBCADcZqIcczPDAx3+os5cCFVgaoT62Y+5rRvwPGPaPKKA1ajw
7NvoxS0RsJbqYAwNk0IEneoZvgSPpqkehGQCOBdsEhjcEgxVxaSlbbgPJkPh
avjTBDUhr6pIUc+MkSX7eh5LdkgWRSfzZdLXX2es5ycM5R1ZryzPTAenZh7D
l1g1x9TsyX+scI7gAtuyfbzAybYVqYMIvcHYZdIi8m6pGmxIqb0QW6sgO6nG
GyjVgxLDyMnHzYMInFRmKUV8XUUw9ECLZ6ioW4rthmpjoswh9vmP6vWI9OL/
Y7Zb3xY5XnIT6UFSpAHS5V/TNbEUD/EpoNtEI30bUl2X35UM277fUxetABEB
AAHNG0pvbiBTbWl0aCA8am9uQGV4YW1wbGUuY29tPsLAigQQAQgAHQUCYOCL
eAQLCQcIAxUICgQWAAIBAhkBAhsDAh4BACEJEGHAYnRSOf5GFiEExGMJvxnV
v1dXecI0YcBidFI5/kY5PAgAxL10QcUZIrxRXQIrqk04ZDhO4ehMirPqH/KT
L/MeHppHFqV06Fm4JDAOpGyh8lgleLwP4P9Lrod3AVSOKSX48u+UM/Bo4LtG
foAntS+tC9RjWlpR6PZ0aJA8SqHKLCnkaUvz7wv/M55fgGxeeQbhOLutNxN4
L8rCNhPo3UbWwoB+ifgQ9S4bv4kgyJxXYinyGYG0CD67YxQKxiAt58qjsdmK
x4uKCoFbHd1Oa4wfr6ezXet+2hCQvsf8eJV88+qL7TmpSe3ypiTWHNgxymNx
v77SlOkkzayJVWxrWtFU8ZoatlsfOP3A5tToio2rEhCHcnqYl4KtF1a0WUR8
KG+pJc7ATQRg4It4AQgA0Q2uZL9TIqGWtNzeAygdG0C3o+D+MoEYI/Qx0A6X
aZv7/1v84V++lRD0iuIMUlBgFEJWMsHF7cN1EMlUV1lRxOzyKTv+0FqyoSTr
bWexA+jG/Nb3Q8vSX1+eVHvm1+2H7AGhBH2szVmXeH15bGNaOaw03EmG5pCh
CIaCoXYUXKoavsa+C8827lGSuqLs1uRniCmIjQvkQSZg7a0IH6dpMIpxdHPh
h9Zyt8e74WwfmXW/be6cjWRI9FgBzl9U5EQEEVO1JdLvfzEEXkNthyAAhl+P
Z1oTR2PSs4ZUlYdb3MQrt7XoKeEOqCHHxoHB3gsj+75Jnc/aAbM+hb13imAJ
iwARAQABwsB2BBgBCAAJBQJg4It4AhsMACEJEGHAYnRSOf5GFiEExGMJvxnV
v1dXecI0YcBidFI5/kZYSQgAop0OsPV11O/fzbZ+oEabC3Ye9hNGapJQNdmJ
MJkiJg7Hnl1FO4MDtHK5OJ4YePFAqtlKRDIBCALPiN0E2v9+3yAafs6TQDc9
Lg3iIPDOnrXv7J7pv2WPnnue4o8Gkggpa+wEjbQJcUBLX311xJGBG4pSNIVN
FJcsl1fGoaxXB5ANPy/+UNMv0l/7cQWDzSw8V9WH10SO2Q4dQF7Zxw+UgBdb
mRVXWNHkcTs81WA/hYtAuLw0O5Q1QWfbXzlTJGNPy/lMMsxLF6La8fBPHlE0
CjYd4ZH9HgOvpCACjRtbc1jywaZJEisO2aJcO2BaozSzYUmkr5sH2wjSKcMS
nLviCw==
=Wg0i
-----END PGP PUBLIC KEY BLOCK-----`
const { BlobServiceClient } = require('@azure/storage-blob');
// const { v1: uuidv1 } = require('uuid');
// const stream = require('stream').promises
const openpgp = require('openpgp');
// import * as openpgp from 'openpgp'
const { publicKey } = require('./keys')





async function main() {

   const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;
   const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
   const containerClient = blobServiceClient.getContainerClient("uploadebs");
   const containerEncryptedFiles = blobServiceClient.getContainerClient("encrypted-dide");
   await containerEncryptedFiles.createIfNotExists("encrypted-dide") 
   
  // console.log(await openpgp.readKey({ armoredKey: publicKey })) <- THIS WORKS!
   for await (const blob of containerClient.listBlobsFlat()) {

       if (blob.name.match('^DIDE*')) {
           const blockBlobClient = containerClient.getBlockBlobClient(blob.name);
           const encryptedblockBlobClient = containerEncryptedFiles.getBlockBlobClient(blob.name)
           blockBlobClient.download(0)
           .then(downloadBlockBlobResponse => streamToString(downloadBlockBlobResponse.readableStreamBody))
           .then(blobAsString => openpgp.encrypt({
                   message:  openpgp.createMessage({ text: blobAsString }), // input as Message object
                   publicKeys: openpgp.readKey({ armoredKey: publicKey }), 
                   
               }))
            // BELOW LINE, SENDS TEXT IN BLOBS, ENCRYPTED OR NOT THROUGH FUNC UPLOAD
           .then(encrypted => {encryptedblockBlobClient.upload(encrypted, encrypted.length)})
       }
   }

}

async function streamToString(readableStream) {

 
   return new Promise((resolve, reject) => {
       const chunks = [];
       readableStream.on("data", (data) => {
           chunks.push(data.toString());
       });

       readableStream.on("end", () => {
           resolve(chunks.join(""));
       });
       readableStream.on("error", reject);
   });
}

main().then(() => console.log('Done')).catch((ex) => console.log(ex.message));

openpgp.createMessage returns 一个承诺。所以你需要做 .then 或在它之前添加 await.

penpgp.readKey。也是一种承诺。

例如来自 Doc:

const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });

const encrypted = await openpgp.encrypt({
    message: await openpgp.createMessage({ text: 'Hello, World!' }), // input as Message object
    publicKeys: publicKey, // for encryption
    privateKeys: privateKey // for signing (optional)
});

编辑2: 不使用等待。

.then(blobAsString => {
    return Promise.all([openpgp.createMessage({ text: blobAsString }), openpgp.readKey({ armoredKey: publicKey })])
    .then(([message, publicKeys ])=>{
        return openpgp.encrypt({
            message,
            publicKeys,
        });
    });    
})

这样使用:

            .then(blobAsString => {
                return Promise.all([openpgp.createMessage({ text: blobAsString }), openpgp.readKey({ armoredKey: publicKey })])
                .then(([message, publicKeys ])=>{
                    return openpgp.encrypt({
                        message,
                        publicKeys,
                    })                   
                })
                .then(encrypted => {encryptedblockBlobClient.upload(encrypted, encrypted.length)});;    
            })