欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Java CMSSignedData 类使用示例

最编程 2024-04-06 07:57:25
...

实例1: getSignersCertificates

import org.bouncycastle.cms.CMSSignedData; //导入依赖的package包/类
private Collection<X509Certificate> getSignersCertificates(CMSSignedData previewSignerData) {
	Collection<X509Certificate> result = new HashSet<X509Certificate>();
	Store<?> certStore = previewSignerData.getCertificates();
	SignerInformationStore signers = previewSignerData.getSignerInfos();
	Iterator<?> it = signers.getSigners().iterator();
	while (it.hasNext()) {
		SignerInformation signer = (SignerInformation) it.next();
		@SuppressWarnings("unchecked")
		Collection<?> certCollection = certStore.getMatches(signer.getSID());
		Iterator<?> certIt = certCollection.iterator();
		X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();
		try {
			result.add(new JcaX509CertificateConverter().getCertificate(certificateHolder));
		} catch (CertificateException error) {
		}
	}
	return result;

}
 

实例2: generateP7B

import org.bouncycastle.cms.CMSSignedData; //导入依赖的package包/类
public CMSSignedData generateP7B(X509CertificateHolder caCertificate, PrivateKey caPrivateKey) {
	try {
		List<X509CertificateHolder> certChain = new ArrayList<X509CertificateHolder>();
		certChain.add(caCertificate);

		Store certs = new JcaCertStore(certChain);

		CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator();
		ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BouncyCastleProvider.PROVIDER_NAME).build(caPrivateKey);

		cmsSignedDataGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
				new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
		.build(sha1Signer, caCertificate));
		cmsSignedDataGenerator.addCertificates(certs);

		CMSTypedData chainMessage = new CMSProcessableByteArray("chain".getBytes());
		CMSSignedData sigData = cmsSignedDataGenerator.generate(chainMessage, false);

		return sigData;
		
	} catch(Exception e) {
		throw new RuntimeException("Error while generating certificate chain: " + e.getMessage(), e);
	}
}
 

实例3: verifySignature

import org.bouncycastle.cms.CMSSignedData; //导入依赖的package包/类
public static boolean verifySignature(CMSSignedData cmsSignedData, X509Certificate cert) {
    try {
        if (Security.getProvider("BC") == null)
            Security.addProvider(new BouncyCastleProvider());

        Collection<SignerInformation> signers = cmsSignedData.getSignerInfos().getSigners();
        X509CertificateHolder ch = new X509CertificateHolder(cert.getEncoded());
        for (SignerInformation si : signers)
            if (si.getSID().match(ch))
                if (si.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(ch)))
                    return true;
    } catch (Exception e) {}
    return false;
}
 

实例4: generateSignatureBlock

import org.bouncycastle.cms.CMSSignedData; //导入依赖的package包/类
private static byte[] generateSignatureBlock(
        SignerConfig signerConfig, byte[] signatureFileBytes)
                throws InvalidKeyException, CertificateEncodingException, SignatureException {
    JcaCertStore certs = new JcaCertStore(signerConfig.certificates);
    X509Certificate signerCert = signerConfig.certificates.get(0);
    String jcaSignatureAlgorithm =
            getJcaSignatureAlgorithm(
                    signerCert.getPublicKey(), signerConfig.signatureDigestAlgorithm);
    try {
        ContentSigner signer =
                new JcaContentSignerBuilder(jcaSignatureAlgorithm)
                .build(signerConfig.privateKey);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        gen.addSignerInfoGenerator(
                new SignerInfoGeneratorBuilder(
                        new JcaDigestCalculatorProviderBuilder().build(),
                        SignerInfoSignatureAlgorithmFinder.INSTANCE)
                        .setDirectSignature(true)
                        .build(signer, new JcaX509CertificateHolder(signerCert)));
        gen.addCertificates(certs);

        CMSSignedData sigData =
                gen.generate(new CMSProcessableByteArray(signatureFileBytes), false);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
            DEROutputStream dos = new DEROutputStream(out);
            dos.writeObject(asn1.readObject());
        }
        return out.toByteArray();
    } catch (OperatorCreationException | CMSException | IOException e) {
        throw new SignatureException("Failed to generate signature", e);
    }
}
 

实例5: isValid

import org.bouncycastle.cms.CMSSignedData; //导入依赖的package包/类
/**
 * Take a CMS SignedData message and a trust anchor and determine if
 * the message is signed with a valid signature from a end entity
 * certificate recognized by the trust anchor rootCert.
 */
public static boolean isValid(CMSSignedData signedData,
                              X509Certificate rootCert)
    throws Exception
{
    CertStore certsAndCRLs = signedData.getCertificatesAndCRLs("Collection", "BC");
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator<?> it = signers.getSigners().iterator();

    while (it.hasNext())
    {
        SignerInformation signer = (SignerInformation)it.next();
        X509CertSelector signerConstraints = signer.getSID();
        
        signerConstraints.setKeyUsage(getKeyUsageForSignature());            
        PKIXCertPathBuilderResult result = buildPath(rootCert, signer.getSID(), certsAndCRLs);

        if (signer.verify(result.getPublicKey(), "BC"))
        	return true;
    }
    
    return false;
}
 

推荐阅读