[英]Encrypt a zip file with browserpgp javascript tool
我想使用 OpenPGP.js ( https://browserpgp.github.io/ ) 加密一個 zip 文件。 所有處理都需要在客戶端完成,不需要 Node.js 的參與。 使用基於 javascript 的 browserpgp.js,明文文件的加密很容易,但 zip 文件的加密具有挑戰性。 我附上了用於加密 zip 文件的代碼。 因為 zip 文件的內容不是文本,所以我使用了來自https://github.com/openpgpjs/openpgpjs的處理二進制數據的指南。 我相信 zip 文件加密后的結果文件應該是原始/二進制格式,並且從以下加密代碼保存的結果文件是二進制文件。 但是,我對其進行了驗證,並且無法解密。
我正在使用 Kleopatra 桌面 OpenPGP 工具 ( https://www.openpgp.org/software/kleopatra/ ) 來驗證生成的加密文件是否。 使用該工具,我測試了是否可以使用我的私鑰解密加密文件。 生成的二進制文件無法使用 Kleopatra 工具解密。 所以我想知道這段代碼有什么問題,因為生成的文件應該可以使用 Kleopatra 解密。
您可以在此處使用該工具創建兩個公鑰: https ://browserpgp.github.io
function openpgp_encryptZIPFile(){
var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
var img = zip.folder("images");
zip.generateAsync({type:"blob"})
.then(function(content) {
console.log('contents: ' + content);
encryptedZipFile = OpenPGPEncryptDataZipFile(content);
});
}
async function OpenPGPEncryptDataZipFile(zipBlob)
{
//This is my public key
const key1 = `somekey1`; //you would have to put a public key here
//This is the testuser public key
const key2 = `somekey2`; //you would have to put another public key here
const publicKeysArmored = [key1, key2];
//create a combined key
const publicKeys = await Promise.all(publicKeysArmored.map(armoredKey => openpgp.readKey({ armoredKey })));
var binaryData = new Uint8Array(zipBlob);
//https://github.com/openpgpjs/openpgpjs/blob/main/README.md
//For OpenPGP.js v4 syntax is: const message = openpgp.Message.fromBinary(binaryData);
//For OpenPGP.js v5 syntax is: const message2 = await openpgp.createMessage({ binary: binaryData });
//`const {data: encrypted}' OR `const { message }' OR just `const encrypted'
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ binary: binaryData }),
encryptionKeys: publicKeys,
//signingKeys: privateKey // optional
format: 'binary'
});
console.log('encrypted: ' + encrypted);
var encryptedBlob = new Blob([encrypted],{type: 'text/plain'});
//var encryptedBlob = new Blob([encrypted], {type: "octet/stream"});
saveAs(encryptedBlob, 'test.zip.enc' );
}
來自 OpenPGPjs github repo 的人回答了這個問題
new Uint8Array(zipBlob)
很可能不會像您認為的那樣做。 也許嘗試new Uint8Array(await zipBlob.arrayBuffer())
,或者首先向 JSZip 詢問 Uint8Array 而不是 Blob。
此外,八位字節/流不是有效的 MIME 類型。 也許您的意思是應用程序/八位字節流?
所以我將new Uint8Array(zipBlob)
更改為new Uint8Array(await zipBlob.arrayBuffer())
並且它起作用了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.