2017-10-04 329 views
0

我有一个PGP Public-Key Encrypted Session Packet,我想从中提取会话密钥,以便我可以分别解密会话密钥。我使用的BouncyCastle的图书馆,我提取这样的会话密钥:Bouncy Castle从公钥加密会话包中提取PGP会话密钥

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中的数据的公钥对应的私钥。在加密我的数据之前,我将RSA密钥对的公钥部分转换为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.

如何解决这个难题将任何意见非常感谢,谢谢!

+0

你是否分裂了数据包的头几个字节(或确保Bouncy Castle已经这么做)? 'pgpdump -pi'也应该将会话密钥打印为整数值,您应该能够将Java代码的结果与此结果进行比较。 –

+0

@JensErat事实证明,Bouncy Castle以MPI格式输出会话密钥,头两个字节表示总边。删除这些后,我能够解密会话密钥,但仍然无法从解码的原始字节中获取任何明智的密钥 –

回答

0

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

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