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

如何用Java代码解密.p7s加密文件?求BouncyCastle库使用方法

Decrypting .p7s Encrypted Files with Java & BouncyCastle

Absolutely! You can absolutely decrypt .p7s (PKCS#7 EnvelopedData) files using Java with the BouncyCastle library. Let's break down the process clearly, including code examples and key notes.

Prerequisites

First, add the BouncyCastle dependencies to your project. If you're using Maven, add these to your pom.xml:

<dependencies>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk18on</artifactId>
        <version>1.77</version> <!-- Use the latest stable version -->
    </dependency>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcpkix-jdk18on</artifactId>
        <version>1.77</version>
    </dependency>
</dependencies>

Step-by-Step Implementation

1. Register BouncyCastle as a Security Provider

BouncyCastle adds support for PKCS#7 operations that aren't fully covered by the default Java security providers. You need to register it first:

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security;

// Register the provider once at app startup
Security.addProvider(new BouncyCastleProvider());

2. Load Your Decryption Private Key

You'll need the private key corresponding to the public key used to encrypt the .p7s file. Most often, this key is stored in a PKCS#12 keystore (.pfx/.p12):

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;

private static PrivateKey loadPrivateKey(String keystorePath, String keystorePassword, String alias) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
    try (FileInputStream fis = new FileInputStream(keystorePath)) {
        keyStore.load(fis, keystorePassword.toCharArray());
        return (PrivateKey) keyStore.getKey(alias, keystorePassword.toCharArray());
    }
}

3. Decrypt the .p7s File

Now, let's parse the PKCS#7 EnvelopedData structure, use your private key to decrypt the symmetric key, then decrypt the actual content:

import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.RecipientInformation;
import org.bouncycastle.cms.RecipientInformationStore;
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Collection;

public static void decryptP7s(String p7sFilePath, PrivateKey privateKey, String outputFilePath) throws Exception {
    // Read the .p7s file
    try (FileInputStream fis = new FileInputStream(p7sFilePath)) {
        CMSEnvelopedData envelopedData = new CMSEnvelopedData(fis);
        
        // Get the recipient info (matches your private key)
        RecipientInformationStore recipientStore = envelopedData.getRecipientInfos();
        Collection<RecipientInformation> recipients = recipientStore.getRecipients();
        
        // Find the recipient that matches your private key and decrypt
        for (RecipientInformation recipient : recipients) {
            byte[] decryptedContent = recipient.getContent(new JceKeyTransEnvelopedRecipient(privateKey).setProvider("BC"));
            
            // Save the decrypted content to a file
            try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
                fos.write(decryptedContent);
            }
            break; // Exit after successful decryption
        }
    } catch (CMSException e) {
        throw new RuntimeException("Failed to decrypt .p7s file: " + e.getMessage(), e);
    }
}

4. Putting It All Together

Call the methods above in your main logic:

public static void main(String[] args) {
    try {
        // Register BouncyCastle
        Security.addProvider(new BouncyCastleProvider());
        
        // Load private key from PKCS#12 keystore
        PrivateKey privateKey = loadPrivateKey(
            "path/to/your/keystore.p12",
            "your-keystore-password",
            "key-alias"
        );
        
        // Decrypt the .p7s file
        decryptP7s(
            "path/to/encrypted/file.p7s",
            privateKey,
            "path/to/save/decrypted/content.txt"
        );
        
        System.out.println("Decryption completed successfully!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Key Notes

  • What if it's a signed .p7s instead of encrypted? If your .p7s is a PKCS#7 signature file (not encrypted), you'd use CMSSignedData instead of CMSEnvelopedData to verify the signature and extract the original content. Let me know if you need that workflow!
  • Algorithm Support: BouncyCastle handles most common encryption algorithms used in PKCS#7 (like AES, 3DES, RSA).
  • Error Handling: Add more specific error checks (e.g., no recipient found for your key, invalid keystore) based on your use case.
  • Latest Version: Always use the latest stable BouncyCastle version to get security fixes and new features.

内容的提问来源于stack exchange,提问作者Leontin Lemnaru

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:04:07