You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenPGP加密:Node.js结果与GPG CLI不一致及等效代码需求

OpenPGP加密结果不一致问题及GPG命令的Node.js等效实现

问题描述

尝试使用OpenPGP库加密文本时,生成的加密结果与GPG CLI命令输出不一致,同时需要实现对应GPG命令的Node.js等效代码。

目标GPG命令

gpg --recipient <Hex_Key_Id> --armor --always-trust --encrypt test_pwd.txt; rm -f test_pwd.txt

当前Node.js代码

const publicKey = await openpgp.readKey({armoredKey: publicKeyArmored}); 
const encryptedSecret = await openpgp.encrypt({ 
     message: await openpgp.createMessage({text: plainSecret}), 
     encryptionKeys: publicKey, 
});

差异原因与修正方案

加密结果不一致主要是当前Node.js代码未匹配GPG命令的关键参数:

  1. 缺失--armor对应配置:GPG命令生成ASCII装甲格式的加密内容,OpenPGP默认输出二进制格式
  2. 未实现--always-trust等效逻辑:GPG跳过密钥信任验证,OpenPGP默认会验证密钥信任状态
  3. 文件内容处理不一致:GPG直接加密文件原始内容,需确保Node.js读取文件的编码、换行符逻辑与GPG对齐

修正后的Node.js等效代码

const fs = require('fs/promises');
const openpgp = require('openpgp');

async function encryptFileGpgEquivalent(publicKeyArmored, filePath) {
    // 读取目标文件内容,匹配GPG原始处理逻辑
    const fileContent = await fs.readFile(filePath, 'utf8');
    // 解析公钥
    const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
    // 创建待加密消息
    const message = await openpgp.createMessage({ text: fileContent });
    // 执行加密,完全对齐GPG参数
    const encryptedContent = await openpgp.encrypt({
        message,
        encryptionKeys: publicKey,
        armor: true, // 对应--armor,生成ASCII装甲格式
        trustAllKeys: true // 对应--always-trust,跳过密钥信任验证
    });
    // 加密完成后删除源文件
    await fs.unlink(filePath);
    return encryptedContent;
}

// 使用示例
// encryptFileGpgEquivalent('你的装甲公钥内容', './test_pwd.txt');

关键参数对应说明

  • armor: true:开启ASCII装甲编码,与GPG的--armor行为完全一致
  • trustAllKeys: true:禁用密钥信任验证,匹配GPG的--always-trust逻辑
  • 文件读取用utf8编码:确保和GPG处理文本文件的编码逻辑对齐(若处理二进制文件,需改为buffer模式)

内容的提问来源于stack exchange,提问作者Mohammed Adil Yousuf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:03:25