本文整理匯總了Java中org.bouncycastle.cms.CMSSignedData類的典型用法代碼示例。如果您正苦於以下問題:Java CMSSignedData類的具體用法?Java CMSSignedData怎麽用?Java CMSSignedData使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
CMSSignedData類屬於org.bouncycastle.cms包,在下文中一共展示了CMSSignedData類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例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;
}
示例6: verifyRSASignatures
import org.bouncycastle.cms.CMSSignedData; //導入依賴的package包/類
private void verifyRSASignatures(CMSSignedData s, byte[] contentDigest)
throws Exception
{
Store certStore = s.getCertificates();
SignerInformationStore signers = s.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext())
{
SignerInformation signer = (SignerInformation)it.next();
Collection certCollection = certStore.getMatches(signer.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder cert = (X509CertificateHolder)certIt.next();
assertEquals(true, signer.verify(new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert)));
if (contentDigest != null)
{
assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest()));
}
}
}
示例7: verifyAllSignatures
import org.bouncycastle.cms.CMSSignedData; //導入依賴的package包/類
public static boolean verifyAllSignatures(CMSSignedData cmsSignedData) {
try {
if (Security.getProvider("BC") == null)
Security.addProvider(new BouncyCastleProvider());
Collection<SignerInformation> signers = cmsSignedData.getSignerInfos().getSigners();
for (SignerInformation si : signers) {
@SuppressWarnings("unchecked")
Collection<X509CertificateHolder> certList = cmsSignedData.getCertificates().getMatches(si.getSID());
if (certList.size() == 0)
throw new Exception("ERROR: Impossible to find a Certificate using the Signer ID: " + si.getSID());
X509CertificateHolder cert = certList.iterator().next(); // Take only the first certificate of the chain
if (!si.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
throw new Exception("ATTENTION: At least a signature is invalid!");
boolean certOK = true;
String msg = "";
try {
X509Utils.checkAllOnCertificate(X509Utils.getX509Certificate(cert.getEncoded()));
} catch (Exception ex) {
msg = ex.getMessage();
certOK = false;
}
if (!certOK)
throw new Exception("ATTENTION: The certificate is invalid:\n" + msg);
}
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
示例8: updateWithCounterSignature
import org.bouncycastle.cms.CMSSignedData; //導入依賴的package包/類
@SuppressWarnings("static-access")
private CMSSignedData updateWithCounterSignature(final CMSSignedData counterSignature,
final CMSSignedData originalSignature, SignerId selector) {
// Retrieve the SignerInformation from the countersigned signature
final SignerInformationStore originalSignerInfos = originalSignature.getSignerInfos();
// Retrieve the SignerInformation from the countersignature
final SignerInformationStore signerInfos = counterSignature.getSignerInfos();
// Add the countersignature
SignerInformation updatedSI = originalSignature.getSignerInfos().get(selector)
.addCounterSigners(originalSignerInfos.get(selector), signerInfos);
// Create updated SignerInformationStore
Collection<SignerInformation> counterSignatureInformationCollection = new ArrayList<SignerInformation>();
counterSignatureInformationCollection.add(updatedSI);
SignerInformationStore signerInformationStore = new SignerInformationStore(
counterSignatureInformationCollection);
// Return new, updated signature
return CMSSignedData.replaceSigners(originalSignature, signerInformationStore);
}
示例9: doCounterSign
import org.bouncycastle.cms.CMSSignedData; //導入依賴的package包/類
@Override
public byte[] doCounterSign(byte[] previewCMSSignature) {
try {
Security.addProvider(new BouncyCastleProvider());
// Reading a P7S file that is preview signature.
CMSSignedData cmsPreviewSignedData = new CMSSignedData(previewCMSSignature);
// Build BouncyCastle object that is a set of signatures
Collection<SignerInformation> previewSigners = cmsPreviewSignedData.getSignerInfos().getSigners();
for (SignerInformation previewSigner : previewSigners) {
// build a counter-signature per previewSignature
byte[] previewSignatureFromSigner = previewSigner.getSignature();
CMSSignedData cmsCounterSignedData = new CMSSignedData(this.doSign(previewSignatureFromSigner));
cmsPreviewSignedData = this.updateWithCounterSignature(cmsCounterSignedData, cmsPreviewSignedData,
previewSigner.getSID());
}
return cmsPreviewSignedData.getEncoded();
} catch (Throwable error) {
throw new SignerException(error);
}
}
示例10: getCertificateChain
import org.bouncycastle.cms.CMSSignedData; //導入依賴的package包/類
public CMSSignedData getCertificateChain(String subjectName) {
try {
CertificateAuthority ca = this.caRepository.findOneByName(subjectName + ROOT_CA);
if(ca == null) {
throw new RuntimeException("Unable to find Certificate Authority with name: " + subjectName);
}
X509CertificateHolder caCertificate = ca.getIdentityContainer().getCertificate();
PrivateKey caPrivateKey = ca.getIdentityContainer().getPrivateKey();
return this.p7bService.generateP7B(caCertificate, caPrivateKey);
} catch (Exception e) {
throw new RuntimeException("Error while getting certiticate chain : " + e.getMessage(), e);
}
}
示例11: 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);
}
}
示例12: testVerifySignature
import org.bouncycastle.cms.CMSSignedData; //導入依賴的package包/類
@Test(description = "This test case tests Signature verification of a Certificate against the keystore")
public void testVerifySignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException {
BASE64Encoder encoder = new BASE64Encoder();
//generate and save a certificate in the keystore
X509Certificate x509Certificate = managementService.generateX509Certificate();
//Generate CMSdata
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
List<X509Certificate> list = new ArrayList<>();
list.add(x509Certificate);
JcaCertStore store = new JcaCertStore(list);
generator.addCertificates(store);
CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
byte[] signature = degenerateSd.getEncoded();
boolean verifySignature = managementService.verifySignature(encoder.encode(signature));
Assert.assertNotNull(verifySignature);
Assert.assertTrue(verifySignature);
log.info("VerifySignature Test Successful");
}
示例13: testExtractCertificateFromSignature
import org.bouncycastle.cms.CMSSignedData; //導入依賴的package包/類
@Test(description = "This test case tests extracting Certificate from the header Signature")
public void testExtractCertificateFromSignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException {
BASE64Encoder encoder = new BASE64Encoder();
//generate and save a certificate in the keystore
X509Certificate x509Certificate = managementService.generateX509Certificate();
//Generate CMSdata
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
List<X509Certificate> list = new ArrayList<>();
list.add(x509Certificate);
JcaCertStore store = new JcaCertStore(list);
generator.addCertificates(store);
CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
byte[] signature = degenerateSd.getEncoded();
X509Certificate certificate = managementService.extractCertificateFromSignature(encoder.encode(signature));
Assert.assertNotNull(certificate);
Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509);
log.info("ExtractCertificateFromSignature Test Successful");
}
示例14: addTimestamp
import org.bouncycastle.cms.CMSSignedData; //導入依賴的package包/類
private static CMSSignedData addTimestamp(String tsaUrl, CMSSignedData signedData) throws IOException {
Collection<SignerInformation> signerInfos = signedData.getSignerInfos().getSigners();
// get signature of first signer (should be the only one)
SignerInformation si = signerInfos.iterator().next();
byte[] signature = si.getSignature();
// send request to TSA
byte[] token = TimeStampingClient.getTimeStampToken(tsaUrl, signature, DigestType.SHA1);
// create new SignerInformation with TS attribute
Attribute tokenAttr = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
new DERSet(ASN1Primitive.fromByteArray(token)));
ASN1EncodableVector timestampVector = new ASN1EncodableVector();
timestampVector.add(tokenAttr);
AttributeTable at = new AttributeTable(timestampVector);
si = SignerInformation.replaceUnsignedAttributes(si, at);
signerInfos.clear();
signerInfos.add(si);
SignerInformationStore newSignerStore = new SignerInformationStore(signerInfos);
// create new signed data
CMSSignedData newSignedData = CMSSignedData.replaceSigners(signedData, newSignerStore);
return newSignedData;
}
示例15: filterUnauthenticatedAttributes
import org.bouncycastle.cms.CMSSignedData; //導入依賴的package包/類
/**
* Remove any archive-timestamp-v2/3 attribute added after the
* timestampToken
*/
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes, TimestampToken timestampToken) {
ASN1EncodableVector result = new ASN1EncodableVector();
for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {
final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
final ASN1ObjectIdentifier attrType = attribute.getAttrType();
if (id_aa_ets_archiveTimestampV2.equals(attrType) || id_aa_ets_archiveTimestampV3.equals(attrType)) {
try {
TimeStampToken token = new TimeStampToken(
new CMSSignedData(DSSASN1Utils.getDEREncoded(attribute.getAttrValues().getObjectAt(0).toASN1Primitive())));
if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
continue;
}
} catch (Exception e) {
throw new DSSException(e);
}
}
result.add(unauthenticatedAttributes.getObjectAt(ii));
}
return new DERSequence(result);
}