Bouncy Castle 从 Public-Key 加密会话数据包中提取 PGP 会话密钥

Bouncy Castle Extract PGP Session Key from Public-Key Encrypted Session Packet

我有一个 PGP Public-Key Encrypted Session Packet,我想从中提取会话密钥,以便我可以单独解密会话密钥。我正在使用 BouncyCastle 库并像这样提取会话密钥:

private static void outputSessionKey(String path) throws FileNotFoundException, IOException {
    BCPGInputStream input = new BCPGInputStream(PGPUtil.getDecoderStream(new FileInputStream(path)));
    Packet packet;
    while((packet = input.readPacket()) != null) {
        if (packet instanceof PublicKeyEncSessionPacket) {
            PublicKeyEncSessionPacket encPacket = (PublicKeyEncSessionPacket) packet;
            byte[] encKey = encPacket.getEncSessionKey()[0];
            FileOutputStream output = new FileOutputStream("session_key_enc.bin");
            output.write(encKey);
            output.close();
        }
    }
    
    input.close();
}

我期待能够使用 openssl 解密会话密钥:

openssl rsautl -decrypt -in session_key_enc.bin -out session_key_decoded.bin -inkey private.pem

其中 session_key_enc.bin 是我的二进制格式的加密会话密钥, private.pem 是相应的私钥到我用来在 GPG 中加密数据的 public 密钥。在加密我的数据之前,我将 RSA 密钥对的 public 密钥部分转换为 PGP 格式的密钥并将其导入 GPG。

当我 运行 OpenSSL 命令时,我得到这个错误:

RSA operation error
140624851898072:error:0406506C:rsa routines:RSA_EAY_PRIVATE_DECRYPT:data greater than mod len:rsa_eay.c:518:

检查 session_key_enc.bin 我发现该文件是 258 字节。考虑到我使用的是 2048 位 RSA 密钥并且规范表明加密的会话密钥由 n:

修改,这似乎不太可能

Algorithm Specific Fields for RSA encryption - multiprecision integer (MPI) of RSA encrypted value m**e mod n.

The value "m" in the above formulas is derived from the session key as follows. First, the session key is prefixed with a one-octet algorithm identifier that specifies the symmetric encryption algorithm used to encrypt the following Symmetrically Encrypted Data Packet. Then a two-octet checksum is appended, which is equal to the sum of the preceding session key octets, not including the algorithm identifier, modulo 65536. This value is then encoded as described in PKCS#1 block encoding EME-PKCS1-v1_5 in Section 7.2.1 of [RFC3447] to form the "m" value used in the formulas above. See Section 13.1 of this document for notes on OpenPGP's use of PKCS#1.

任何关于如何解决这个难题的建议将不胜感激,谢谢!

事实证明,Bouncy Castle 使用 MPI 格式导出加密的会话密钥,其中前 2 个字节是长度。这解决了我无法解密会话密钥的原始问题,因为它是 258 字节而不是 256。

尽管仍然无法使用 --override-session-key 和现在解密的会话密钥的原始字节解密文件,但我将此问题标记为已回答。