Java解密电子邮件附件(.p7m文件)

Java解密电子邮件附件(.p7m文件),java,encryption,openssl,cryptography,smime,Java,Encryption,Openssl,Cryptography,Smime,我有一个.p7m格式的电子邮件附件和一个包含私钥和证书的.pem文件。 使用OpenSSL,我可以使用以下命令解密文件: openssl smime -decrypt -inform DER -in fileToDecrypt.p7m -inkey privateKey.pem -out destinationFile 但是使用Java中的bouncycastle,我无法解密它。 我使用以下代码读取私钥: PEMReader pemReader = new PEMReader(new

我有一个.p7m格式的电子邮件附件和一个包含私钥和证书的.pem文件。 使用OpenSSL,我可以使用以下命令解密文件:

openssl smime -decrypt -inform DER -in fileToDecrypt.p7m -inkey privateKey.pem -out destinationFile
但是使用Java中的bouncycastle,我无法解密它。 我使用以下代码读取私钥:

    PEMReader pemReader = new PEMReader(new InputStreamReader(new FileInputStream(privateKeyName)));
    Object obj;
    PrivateKey key = null;
    X509Certificate cert1 = null;
    X509Certificate cert2 = null;

    obj = pemReader.readObject();
    if (obj instanceof PrivateKey) {
        key = (PrivateKey) obj;
        System.out.println("Private Key found");
    }
    obj = pemReader.readObject();
    if(obj instanceof X509Certificate){
        cert1 = (X509Certificate) obj;
        System.out.println("cert found");
    }
    obj = pemReader.readObject();
    if(obj instanceof X509Certificate){
        cert2 = (X509Certificate) obj;
        System.out.println("cert found");
    }
这将打印出:

Private Key Found
cert found
cert found
钥匙的类型为:

 System.out.println(key.getAlgorithm());
 System.out.println(cert1.getSigAlgName());
 System.out.println(cert2.getSigAlgName());

RSA
SHA256WithRSAEncryption
SHA256WithRSAEncryption
如果我尝试这样解密:

 Cipher cipher = Cipher.getInstance("RSA");
 cipher.init(Cipher.DECRYPT_MODE, key);
 Path path = Paths.get("fileToDecrypt.p7m");
 byte[] data = Files.readAllBytes(path);
 byte[] decryptedData = cipher.doFinal(data);
我得到:

javax.crypto.IllegalBlockSizeException:数据长度不得超过256字节

我有两个文件:

  • fileToDecrypt.p7m
  • privateKey.pem:包含RSA私钥和两个X508证书

  • 我不知道从哪里开始,用什么解密,如何解密?

    问题的解决方案:

    private static byte[] cmsDecrypt(byte[] message, PrivateKey key) throws
            Exception {
        CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(message);
        RecipientInformationStore recipients = ep.getRecipientInfos();
        Collection c = recipients.getRecipients();
        Iterator iter = c.iterator();
        RecipientInformation recipient = (RecipientInformation) iter.next();
        return recipient.getContent(key, new BouncyCastleProvider());
    }
    


    问题的解决办法:

    private static byte[] cmsDecrypt(byte[] message, PrivateKey key) throws
            Exception {
        CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(message);
        RecipientInformationStore recipients = ep.getRecipientInfos();
        Collection c = recipients.getRecipients();
        Iterator iter = c.iterator();
        RecipientInformation recipient = (RecipientInformation) iter.next();
        return recipient.getContent(key, new BouncyCastleProvider());
    }
    


    你可以回答你自己的问题;)你可以回答你自己的问题;)答案不完整,没有解释问题或解决方案是什么。答案不完整,没有解释问题或解决方案是什么