如何在java中加载PKCS7(.p7b)文件

时间:2015-06-29 14:54:42

标签: java security digital-signature pkcs#7

我有一个pkcs7文件,我想加载它并提取其内容。

我试过这两种方法:

byte[] bytes = Files.readAllBytes(Paths.get("myfile.p7b"));
FileInputStream fi = new FileInputStream(file);

//Creating PKCS7 object
PKCS7 pkcs7Signature = new PKCS7(bytes);

或者

FileInputStream fis = new FileInputStream(new File("myfile.p7b"));
PKCS7 pkcs7Signature = new PKCS7(fis);

但我得到了IOException: Sequence tag error

那么如何加载这个.p7b文件?

1 个答案:

答案 0 :(得分:2)

最后我用BouncyCastle库做了。

PKCS#7是一种复杂的格式,也称为CMS。 Sun JCE没有直接支持PKCS#7。

这是我用来提取内容的代码:

// Loading the file first
   File f = new File("myFile.p7b");
   byte[] buffer = new byte[(int) f.length()];
   DataInputStream in = new DataInputStream(new FileInputStream(f));
   in.readFully(buffer);
   in.close();

   //Corresponding class of signed_data is CMSSignedData
   CMSSignedData signature = new CMSSignedData(buffer);
   Store cs = signature.getCertificates();
   SignerInformationStore signers = signature.getSignerInfos();
   Collection c = signers.getSigners();
   Iterator it = c.iterator();

   //the following array will contain the content of xml document
   byte[] data = null;

   while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = cs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

        CMSProcessable sc = signature.getSignedContent();
        data = (byte[]) sc.getContent();
    }

如果要根据X509证书验证此PKCS7文件的签名,则必须将以下代码添加到while循环中:

// ************************************************************* //
// ********************* Verify signature ********************** //
//get CA public key
// Create a X509 certificat
CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");

// Open the certificate file
FileInputStream fileinputstream = new FileInputStream("myCA.cert");

//get CA public key
PublicKey pk = certificatefactory.generateCertificate(fileinputstream).getPublicKey();

X509Certificate myCA = new JcaX509CertificateConverter().setProvider("BC").getCertificate(cert);

myCA.verify(pk);
System.out.println("Verfication done successfully ");