首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java中加载PKCS7 (.p7b)文件

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

Stack Overflow用户
提问于 2015-06-29 22:54:42
回答 1查看 5.8K关注 0票数 2

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

我尝试了这两种方法:

代码语言:javascript
复制
byte[] bytes = Files.readAllBytes(Paths.get("myfile.p7b"));
FileInputStream fi = new FileInputStream(file);

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

或者这个

代码语言:javascript
复制
FileInputStream fis = new FileInputStream(new File("myfile.p7b"));
PKCS7 pkcs7Signature = new PKCS7(fis);

但是我有IOException: Sequence tag error

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

EN

回答 1

Stack Overflow用户

发布于 2015-07-15 17:22:08

最后,我用BouncyCastle库做到了这一点。

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

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

代码语言:javascript
复制
// 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循环中:

代码语言:javascript
复制
// ************************************************************* //
// ********************* 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 ");
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31118893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档