How to load PKCS7 (.p7b) file in java

独自空忆成欢 提交于 2019-12-24 05:33:33

问题


I have a pkcs7 file, and I want to load it and extract its contents.

I tried these two methods:

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

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

or this

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

but I got IOException: Sequence tag error

So how can I load this .p7b file ?


回答1:


Finally I did it with BouncyCastle library.

PKCS#7 is a complex format, also called CMS. Sun JCE has no direct support to PKCS#7.

This is the code that I used to extract my content:

// 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();
    }

If you want to verify the signature of this PKCS7 file against X509 certificate, you must add the following code to the while loop:

// ************************************************************* //
// ********************* 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 ");


来源:https://stackoverflow.com/questions/31118893/how-to-load-pkcs7-p7b-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!