List of usage examples for org.bouncycastle.cms.jcajce JcaSignerInfoGeneratorBuilder setSignedAttributeGenerator
public JcaSignerInfoGeneratorBuilder setSignedAttributeGenerator(CMSAttributeTableGenerator signedGen)
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
private static SMIMESignedGenerator makeSignerGentor(PrivateKey key, Certificate[] certs, SigningAlgo algo) throws CertStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, GeneralSecurityException, CertificateEncodingException { SMIMESignedGenerator gen = new SMIMESignedGenerator("base64"); List<Certificate> lst = asList(true, certs); ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); caps.addCapability(SMIMECapability.dES_CBC); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); X509Certificate x0 = (X509Certificate) certs[0]; X509Certificate issuer = x0;/*from w ww . j a va 2 s . co m*/ X500Principal issuerDN; if (certs.length > 1) { issuer = (X509Certificate) certs[1]; } issuerDN = issuer.getSubjectX500Principal(); x0 = (X509Certificate) certs[0]; // // add an encryption key preference for encrypted responses - // normally this would be different from the signing certificate... // IssuerAndSerialNumber issAndSer = new IssuerAndSerialNumber(X500Name.getInstance(issuerDN.getEncoded()), x0.getSerialNumber()); Provider prov = Crypto.getInstance().getProvider(); signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(issAndSer)); try { JcaSignerInfoGeneratorBuilder bdr = new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(prov).build()); bdr.setDirectSignature(true); ContentSigner cs = new JcaContentSignerBuilder(algo.toString()).setProvider(prov).build(key); bdr.setSignedAttributeGenerator( new DefaultSignedAttributeTableGenerator(new AttributeTable(signedAttrs))); gen.addSignerInfoGenerator(bdr.build(cs, x0)); gen.addCertificates(new JcaCertStore(lst)); return gen; } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } }
From source file:org.ejbca.core.protocol.scep.ScepResponseMessage.java
License:Open Source License
@Override public boolean create() throws CertificateEncodingException, CRLException { boolean ret = false; try {/* w w w . j a v a 2s. c o m*/ if (status.equals(ResponseStatus.SUCCESS)) { log.debug("Creating a STATUS_OK message."); } else { if (status.equals(ResponseStatus.FAILURE)) { log.debug("Creating a STATUS_FAILED message (or returning false)."); if (failInfo.equals(FailInfo.WRONG_AUTHORITY)) { return false; } if (failInfo.equals(FailInfo.INCORRECT_DATA)) { return false; } } else { log.debug("Creating a STATUS_PENDING message."); } } CMSTypedData msg; // Create encrypted response if this is success and NOT a CRL response message if (status.equals(ResponseStatus.SUCCESS)) { CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); // Add the issued certificate to the signed portion of the CMS (as signer, degenerate case) List<X509Certificate> certList = new ArrayList<X509Certificate>(); if (cert != null) { log.debug("Adding certificates to response message"); certList.add((X509Certificate) cert); // Add the CA cert, it's optional but Cisco VPN client complains if it isn't there if (includeCACert) { if (caCert != null) { // If we have an explicit CAcertificate log.debug("Including explicitly set CA certificate in SCEP response."); certList.add((X509Certificate) caCert); } else { // If we don't have an explicit caCert, we think that the signCert is the CA cert // If we have an explicit caCert, the signCert is probably the RA certificate, and we don't include that one log.debug("Including message signer certificate in SCEP response."); certList.add((X509Certificate) signCertChain.iterator().next()); } } } // Create the signed CMS message to be contained inside the envelope // this message does not contain any message, and no signerInfo CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(certList))); if (crl != null) { gen.addCRL(new JcaX509CRLHolder((X509CRL) crl)); } CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // Envelope the CMS message if (recipientKeyInfo != null) { try { X509Certificate rec = (X509Certificate) CertTools.getCertfromByteArray(recipientKeyInfo); log.debug("Added recipient information - issuer: '" + CertTools.getIssuerDN(rec) + "', serno: '" + CertTools.getSerialNumberAsString(rec)); edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(rec) .setProvider(BouncyCastleProvider.PROVIDER_NAME)); } catch (CertificateParsingException e) { throw new IllegalArgumentException("Can not decode recipients self signed certificate!", e); } } else { edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate) cert) .setProvider(BouncyCastleProvider.PROVIDER_NAME)); } try { JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder( SMIMECapability.dES_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME); CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(s.getEncoded()), jceCMSContentEncryptorBuilder.build()); if (log.isDebugEnabled()) { log.debug("Enveloped data is " + ed.getEncoded().length + " bytes long"); } msg = new CMSProcessableByteArray(ed.getEncoded()); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught", e); } } else { // Create an empty message here //msg = new CMSProcessableByteArray("PrimeKey".getBytes()); msg = new CMSProcessableByteArray(new byte[0]); } // Create the outermost signed data CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator(); // add authenticated attributes...status, transactionId, sender- and recipientNonce and more... Hashtable<ASN1ObjectIdentifier, Attribute> attributes = new Hashtable<ASN1ObjectIdentifier, Attribute>(); ASN1ObjectIdentifier oid; Attribute attr; DERSet value; // Message type (certrep) oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType); value = new DERSet(new DERPrintableString("3")); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); // TransactionId if (transactionId != null) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_transId); log.debug("Added transactionId: " + transactionId); value = new DERSet(new DERPrintableString(transactionId)); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // status oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus); value = new DERSet(new DERPrintableString(status.getStringValue())); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); if (status.equals(ResponseStatus.FAILURE)) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo); log.debug("Added failInfo: " + failInfo.getValue()); value = new DERSet(new DERPrintableString(failInfo.getValue())); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // senderNonce if (senderNonce != null) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce); log.debug("Added senderNonce: " + senderNonce); value = new DERSet(new DEROctetString(Base64.decode(senderNonce.getBytes()))); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // recipientNonce if (recipientNonce != null) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce); log.debug("Added recipientNonce: " + recipientNonce); value = new DERSet(new DEROctetString(Base64.decode(recipientNonce.getBytes()))); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // Add our signer info and sign the message Certificate cacert = signCertChain.iterator().next(); log.debug("Signing SCEP message with cert: " + CertTools.getSubjectDN(cacert)); String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digestAlg, signKey.getAlgorithm()); try { ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(provider).build(signKey); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); builder.setSignedAttributeGenerator( new DefaultSignedAttributeTableGenerator(new AttributeTable(attributes))); gen1.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) cacert)); } catch (OperatorCreationException e) { throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e); } // The un-encoded response message itself final CMSSignedData signedData = gen1.generate(msg, true); try { responseMessage = signedData.getEncoded(); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught.", e); } if (responseMessage != null) { ret = true; } } catch (CMSException e) { log.error("Error creating CMS message: ", e); } return ret; }
From source file:org.jscep.message.PkiMessageEncoder.java
License:Open Source License
private SignerInfoGenerator getSignerInfo(final PkiMessage<?> message) throws MessageEncodingException { JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder(getDigestCalculator()); signerInfoBuilder.setSignedAttributeGenerator(getTableGenerator(message)); SignerInfoGenerator signerInfo;// w w w. ja v a2 s . co m try { signerInfo = signerInfoBuilder.build(getContentSigner(), signerId); } catch (Exception e) { throw new MessageEncodingException(e); } return signerInfo; }
From source file:org.signserver.module.tsa.TimeStampSigner.java
License:Open Source License
private TimeStampTokenGenerator getTimeStampTokenGenerator(final ICryptoInstance crypto, final TimeStampRequest timeStampRequest, final LogMap logMap) throws IllegalRequestException, CryptoTokenOfflineException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, OperatorCreationException, SignServerException { TimeStampTokenGenerator timeStampTokenGen = null; try {//from ww w . j av a 2s. c o m ASN1ObjectIdentifier tSAPolicyOID = timeStampRequest.getReqPolicy(); if (tSAPolicyOID == null) { tSAPolicyOID = defaultTSAPolicyOID; } logMap.put(ITimeStampLogger.LOG_TSA_POLICYID, tSAPolicyOID.getId()); final X509Certificate signingCert = (X509Certificate) getSigningCertificate(crypto); if (signingCert == null) { throw new CryptoTokenOfflineException("No certificate for this signer"); } DigestCalculatorProvider calcProv = new BcDigestCalculatorProvider(); DigestCalculator calc = calcProv.get(new AlgorithmIdentifier(TSPAlgorithms.SHA1)); ContentSigner cs = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(crypto.getProvider()) .build(crypto.getPrivateKey()); JcaSignerInfoGeneratorBuilder sigb = new JcaSignerInfoGeneratorBuilder(calcProv); X509CertificateHolder certHolder = new X509CertificateHolder(signingCert.getEncoded()); // set signed attribute table generator based on property sigb.setSignedAttributeGenerator( new OptionalSigningTimeSignedAttributeTableGenerator(includeSigningTimeAttribute)); SignerInfoGenerator sig = sigb.build(cs, certHolder); timeStampTokenGen = new TimeStampTokenGenerator(calc, sig, tSAPolicyOID); if (config.getProperties().getProperty(ACCURACYMICROS) != null) { timeStampTokenGen .setAccuracyMicros(Integer.parseInt(config.getProperties().getProperty(ACCURACYMICROS))); } if (config.getProperties().getProperty(ACCURACYMILLIS) != null) { timeStampTokenGen .setAccuracyMillis(Integer.parseInt(config.getProperties().getProperty(ACCURACYMILLIS))); } if (config.getProperties().getProperty(ACCURACYSECONDS) != null) { timeStampTokenGen .setAccuracySeconds(Integer.parseInt(config.getProperties().getProperty(ACCURACYSECONDS))); } timeStampTokenGen.setOrdering(ordering); timeStampTokenGen.setIncludeOrdering(includeOrdering); if (tsaName != null) { final X500Name x500Name = new X500Name(tsaName); timeStampTokenGen.setTSA(new GeneralName(x500Name)); } else if (tsaNameFromCert) { final X500Name x500Name = new JcaX509CertificateHolder(signingCert).getSubject(); timeStampTokenGen.setTSA(new GeneralName(x500Name)); } timeStampTokenGen .addCertificates(getCertStoreWithChain(signingCert, getSigningCertificateChain(crypto))); } catch (IllegalArgumentException e) { LOG.error("IllegalArgumentException: ", e); throw new IllegalRequestException(e.getMessage()); } catch (TSPException e) { LOG.error("TSPException: ", e); throw new IllegalRequestException(e.getMessage()); } catch (CertificateEncodingException e) { LOG.error("CertificateEncodingException: ", e); throw new IllegalRequestException(e.getMessage()); } catch (IOException e) { LOG.error("IOException: ", e); throw new IllegalRequestException(e.getMessage()); } return timeStampTokenGen; }
From source file:org.xipki.pki.scep.message.NextCaMessage.java
License:Open Source License
public ContentInfo encode(final PrivateKey signingKey, final X509Certificate signerCert, final X509Certificate[] cmsCertSet) throws MessageEncodingException { ParamUtil.requireNonNull("signingKey", signingKey); ParamUtil.requireNonNull("signerCert", signerCert); try {//from www . j a va 2s .c o m byte[] degenratedSignedDataBytes; try { CMSSignedDataGenerator degenerateSignedData = new CMSSignedDataGenerator(); degenerateSignedData.addCertificate(new X509CertificateHolder(caCert.getEncoded())); if (raCerts != null && !raCerts.isEmpty()) { for (X509Certificate m : raCerts) { degenerateSignedData.addCertificate(new X509CertificateHolder(m.getEncoded())); } } degenratedSignedDataBytes = degenerateSignedData.generate(new CMSAbsentContent()).getEncoded(); } catch (CertificateEncodingException ex) { throw new MessageEncodingException(ex.getMessage(), ex); } CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); // I don't known which hash algorithm is supported by the client, use SHA-1 String signatureAlgo = getSignatureAlgorithm(signingKey, ScepHashAlgoType.SHA1); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgo).build(signingKey); // signerInfo JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder( new BcDigestCalculatorProvider()); signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator()); SignerInfoGenerator signerInfo = signerInfoBuilder.build(signer, signerCert); generator.addSignerInfoGenerator(signerInfo); CMSTypedData cmsContent = new CMSProcessableByteArray(CMSObjectIdentifiers.signedData, degenratedSignedDataBytes); // certificateSet ScepUtil.addCmsCertSet(generator, cmsCertSet); return generator.generate(cmsContent, true).toASN1Structure(); } catch (CMSException ex) { throw new MessageEncodingException(ex); } catch (CertificateEncodingException ex) { throw new MessageEncodingException(ex); } catch (IOException ex) { throw new MessageEncodingException(ex); } catch (OperatorCreationException ex) { throw new MessageEncodingException(ex); } }
From source file:org.xipki.pki.scep.message.PkiMessage.java
License:Open Source License
public ContentInfo encode(final ContentSigner signer, final X509Certificate signerCert, final X509Certificate[] cmsCertSet, final X509Certificate recipientCert, final ASN1ObjectIdentifier encAlgId) throws MessageEncodingException { ParamUtil.requireNonNull("signer", signer); ParamUtil.requireNonNull("signerCert", signerCert); ParamUtil.requireNonNull("recipientCert", recipientCert); ParamUtil.requireNonNull("encAlgId", encAlgId); CMSTypedData content;//from w ww . j a v a2 s . c om if (messageData == null) { content = new CMSAbsentContent(); } else { CMSEnvelopedData envelopedData = encrypt(recipientCert, encAlgId); byte[] encoded; try { encoded = envelopedData.getEncoded(); } catch (IOException ex) { throw new MessageEncodingException(ex); } content = new CMSProcessableByteArray(CMSObjectIdentifiers.envelopedData, encoded); } try { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); // signerInfo JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder( new BcDigestCalculatorProvider()); signerInfoBuilder .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(getSignedAttributes())); AttributeTable attrTable = getUnsignedAttributes(); if (attrTable != null) { signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(attrTable)); } // certificateSet ScepUtil.addCmsCertSet(generator, cmsCertSet); SignerInfoGenerator signerInfo; try { signerInfo = signerInfoBuilder.build(signer, signerCert); } catch (Exception ex) { throw new MessageEncodingException(ex); } generator.addSignerInfoGenerator(signerInfo); CMSSignedData signedData = generator.generate(content, true); return signedData.toASN1Structure(); } catch (CMSException ex) { throw new MessageEncodingException(ex); } catch (Exception ex) { throw new MessageEncodingException(ex); } }