List of usage examples for org.bouncycastle.cms CMSSignedData getEncoded
public byte[] getEncoded() throws IOException
From source file:org.bitrepository.protocol.security.BasicMessageSigner.java
License:Open Source License
/** * Creates the CMS signature for a message. * @param messageData the message data that is to be signed. * @return the CMS signature for the message. * @throws MessageSigningException in case signing fails. *//*from www . j av a 2 s . c om*/ @Override public byte[] signMessage(byte[] messageData) throws MessageSigningException { if (privateKeyEntry == null) { throw new MessageSigningException("Private key entry has not been initialized.", null); } try { CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSignerInfoGenerator( builder.build(sha512Signer, (X509Certificate) privateKeyEntry.getCertificate())); CMSSignedData signedData = gen.generate(new CMSProcessableByteArray(messageData), USE_ATTACHED_MODE); return signedData.getEncoded(); } catch (Exception e) { throw new MessageSigningException(e.getMessage(), e); } }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
@Override public byte[] createPKCS7(CryptoToken cryptoToken, Certificate cert, boolean includeChain) throws SignRequestSignatureException { // First verify that we signed this certificate try {//from w w w.j a v a2 s.co m if (cert != null) { final PublicKey verifyKey; final X509Certificate cacert = (X509Certificate) getCACertificate(); if (cacert != null) { verifyKey = cacert.getPublicKey(); } else { verifyKey = cryptoToken .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); } cert.verify(verifyKey); } } catch (CryptoTokenOfflineException e) { throw new SignRequestSignatureException("The cryptotoken was not available, could not create a PKCS7", e); } catch (InvalidKeyException e) { throw new SignRequestSignatureException("The specified certificate contains the wrong public key.", e); } catch (CertificateException e) { throw new SignRequestSignatureException("An encoding error was encountered.", e); } catch (NoSuchAlgorithmException e) { throw new SignRequestSignatureException( "The certificate provided was signed with an invalid algorithm.", e); } catch (NoSuchProviderException e) { throw new SignRequestSignatureException( "The crypto provider was not found for verification of the certificate.", e); } catch (SignatureException e) { throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?", e); } Collection<Certificate> chain = getCertificateChain(); ArrayList<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>(); try { if (cert != null) { certList.add(new JcaX509CertificateHolder((X509Certificate) cert)); } if (includeChain) { for (Certificate certificate : chain) { certList.add(new JcaX509CertificateHolder((X509Certificate) certificate)); } } } catch (CertificateEncodingException e) { throw new SignRequestSignatureException("Could not encode certificate", e); } try { CMSTypedData msg = new CMSProcessableByteArray("EJBCA".getBytes()); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); final PrivateKey privateKey = cryptoToken .getPrivateKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); if (privateKey == null) { String msg1 = "createPKCS7: Private key does not exist!"; log.debug(msg1); throw new SignRequestSignatureException(msg1); } String signatureAlgorithmName = AlgorithmTools .getAlgorithmNameFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privateKey.getAlgorithm()); try { ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(cryptoToken.getSignProviderName()).build(privateKey); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); gen.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) getCACertificate())); } catch (OperatorCreationException e) { throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e); } gen.addCertificates(new CollectionStore(certList)); CMSSignedData s = null; CAToken catoken = getCAToken(); if (catoken != null && !(cryptoToken instanceof NullCryptoToken)) { log.debug("createPKCS7: Provider=" + cryptoToken.getSignProviderName() + " using algorithm " + privateKey.getAlgorithm()); s = gen.generate(msg, true); } else { String msg1 = "CA Token does not exist!"; log.debug(msg); throw new SignRequestSignatureException(msg1); } return s.getEncoded(); } catch (CryptoTokenOfflineException e) { throw new RuntimeException(e); } catch (Exception e) { //FIXME: This right here is just nasty throw new RuntimeException(e); } }
From source file:org.cryptoworkshop.ximix.node.crypto.service.NodeShuffledBoardDecryptionService.java
License:Apache License
private Map<String, byte[]> createSeedCommitmentMap(SignedDataVerifier verifier, File[] fileList) { final Map<String, byte[]> transcripts = new TreeMap<>(); for (File file : fileList) { String name = file.getName(); int beginIndex = name.indexOf('.') + 1; String nodeName = name.substring(beginIndex, name.indexOf('.', beginIndex)); try {/*w w w . ja v a 2 s. c om*/ BufferedInputStream sigData = new BufferedInputStream(new FileInputStream(file)); CMSSignedData cmsSignedData = new CMSSignedData(sigData); if (verifier.signatureVerified(cmsSignedData)) { transcripts.put(nodeName, cmsSignedData.getEncoded()); } else { nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR, "Signature check failed: " + file.getPath()); } sigData.close(); } catch (Exception e) { nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR, "Signature check failed on " + file.getPath() + ": " + e.getMessage(), e); } } return transcripts; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
private byte[] doSign(byte[] content, byte[] previewSignature) { try {// www . j a va 2 s. c o m Security.addProvider(new BouncyCastleProvider()); // Completa os certificados ausentes da cadeia, se houver if (this.certificate == null && this.certificateChain != null && this.certificateChain.length > 0) { this.certificate = (X509Certificate) this.certificateChain[0]; } this.certificateChain = CAManager.getInstance().getCertificateChainArray(this.certificate); if (this.certificateChain.length < 3) { throw new SignerException( cadesMessagesBundle.getString("error.no.ca", this.certificate.getIssuerDN())); } Certificate[] certStore = new Certificate[] {}; CMSSignedData cmsPreviewSignedData = null; // Caso seja co-assinatura ou contra-assinatura // Importar todos os certificados da assinatura anterior if (previewSignature != null && previewSignature.length > 0) { cmsPreviewSignedData = new CMSSignedData(new CMSAbsentContent(), previewSignature); Collection<X509Certificate> previewCerts = this.getSignersCertificates(cmsPreviewSignedData); //previewCerts.add(this.certificate); certStore = previewCerts.toArray(new Certificate[] {}); } setCertificateManager(new CertificateManager(this.certificate)); // Recupera a lista de algoritmos da politica e o tamanho minimo da // chave List<AlgAndLength> listOfAlgAndLength = new ArrayList<AlgAndLength>(); for (AlgAndLength algLength : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy() .getCommonRules().getAlgorithmConstraintSet().getSignerAlgorithmConstraints() .getAlgAndLengths()) { listOfAlgAndLength.add(algLength); } AlgAndLength algAndLength = null; // caso o algoritmo tenha sido informado como parmetro ir // verificar se o mesmo permitido pela politica if (this.pkcs1.getAlgorithm() != null) { String varSetedAlgorithmOID = AlgorithmNames.getOIDByAlgorithmName(this.pkcs1.getAlgorithm()); for (AlgAndLength algLength : listOfAlgAndLength) { if (algLength.getAlgID().getValue().equalsIgnoreCase(varSetedAlgorithmOID)) { algAndLength = algLength; SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum .valueOf(this.pkcs1.getAlgorithm()); String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash(); ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg() .getAlgorithm(); varObjectIdentifier.setValue(varOIDAlgorithmHash); AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg(); varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier); signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier); } } } else { algAndLength = listOfAlgAndLength.get(1); this.pkcs1.setAlgorithm(AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue())); SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm()); String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash(); ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg().getAlgorithm(); varObjectIdentifier.setValue(varOIDAlgorithmHash); AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg(); varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier); signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier); } if (algAndLength == null) { throw new SignerException(cadesMessagesBundle.getString("error.no.algorithm.policy")); } logger.info(cadesMessagesBundle.getString("info.algorithm.id", algAndLength.getAlgID().getValue())); logger.info(cadesMessagesBundle.getString("info.algorithm.name", AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue()))); logger.info(cadesMessagesBundle.getString("info.min.key.length", algAndLength.getMinKeyLength())); // Recupera o tamanho minimo da chave para validacao logger.info(cadesMessagesBundle.getString("info.validating.key.length")); int keyLegth = ((RSAKey) certificate.getPublicKey()).getModulus().bitLength(); if (keyLegth < algAndLength.getMinKeyLength()) { throw new SignerException(cadesMessagesBundle.getString("error.min.key.length", algAndLength.getMinKeyLength().toString(), keyLegth)); } AttributeFactory attributeFactory = AttributeFactory.getInstance(); // Consulta e adiciona os atributos assinados ASN1EncodableVector signedAttributes = new ASN1EncodableVector(); logger.info(cadesMessagesBundle.getString("info.signed.attribute")); if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules() .getMandatedSignedAttr().getObjectIdentifiers()) { SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory .factory(objectIdentifier.getValue()); signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, content, signaturePolicy, this.hash); signedAttributes.add(signedOrUnsignedAttribute.getValue()); } } // Monta a tabela de atributos assinados AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); // Create the table table generator that will added to the Signer // builder CMSAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator( signedAttributesTable); // Recupera o(s) certificado(s) de confianca para validacao Collection<X509Certificate> trustedCAs = new HashSet<X509Certificate>(); Collection<CertificateTrustPoint> ctp = signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSigningCertTrustCondition() .getSignerTrustTrees().getCertificateTrustPoints(); for (CertificateTrustPoint certificateTrustPoint : ctp) { logger.info(cadesMessagesBundle.getString("info.trust.point", certificateTrustPoint.getTrustpoint().getSubjectDN().toString())); trustedCAs.add(certificateTrustPoint.getTrustpoint()); } // Efetua a validacao das cadeias do certificado baseado na politica Collection<X509Certificate> certificateChainTrusted = new HashSet<X509Certificate>(); for (Certificate certCA : certificateChain) { certificateChainTrusted.add((X509Certificate) certCA); } X509Certificate rootOfCertificate = null; for (X509Certificate tcac : certificateChainTrusted) { logger.info(tcac.getIssuerDN().toString()); if (CAManager.getInstance().isRootCA(tcac)) { rootOfCertificate = tcac; } } if (trustedCAs.contains(rootOfCertificate)) { logger.info(cadesMessagesBundle.getString("info.trust.in.point", rootOfCertificate.getSubjectDN())); } else { // No encontrou na poltica, verificar nas cadeias do // componente chain-icp-brasil provavelmente certificado de // homologao. logger.warn(cadesMessagesBundle.getString("info.trust.poin.homolog")); CAManager.getInstance().validateRootCAs(certificateChainTrusted, certificate); } // validade da politica logger.info(cadesMessagesBundle.getString("info.policy.valid.period")); PolicyValidator pv = new PolicyValidator(this.signaturePolicy, this.policyName); pv.validate(); // Realiza a assinatura do conteudo CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificates(this.generatedCertStore(certStore)); String algorithmOID = algAndLength.getAlgID().getValue(); logger.info(cadesMessagesBundle.getString("info.algorithm.id", algorithmOID)); SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder() .setSignedAttributeGenerator(signedAttributeGenerator).setUnsignedAttributeGenerator(null) .build(AlgorithmNames.getAlgorithmNameByOID(algorithmOID), this.pkcs1.getPrivateKey(), this.certificate); gen.addSignerInfoGenerator(signerInfoGenerator); CMSTypedData cmsTypedData; // para assinatura do hash, content nulo if (content == null) { cmsTypedData = new CMSAbsentContent(); } else { cmsTypedData = new CMSProcessableByteArray(content); } // Efetua a assinatura digital do contedo CMSSignedData cmsSignedData = gen.generate(cmsTypedData, this.attached); setAttached(false); // Consulta e adiciona os atributos no assinados// ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector(); logger.info(cadesMessagesBundle.getString("info.unsigned.attribute")); Collection<SignerInformation> vNewSigners = cmsSignedData.getSignerInfos().getSigners(); Iterator<SignerInformation> it = vNewSigners.iterator(); SignerInformation oSi = it.next(); if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules() .getMandatedUnsignedAttr().getObjectIdentifiers()) { SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory .factory(objectIdentifier.getValue()); if (signedOrUnsignedAttribute.getOID() .equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) { signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, oSi.getSignature(), signaturePolicy, this.hash); } if (signedOrUnsignedAttribute.getOID().equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) //EscTimeStamp { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(oSi.getSignature()); AttributeTable varUnsignedAttributes = oSi.getUnsignedAttributes(); Attribute varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier( PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())); outputStream.write(varAttribute.getAttrType().getEncoded()); outputStream.write(varAttribute.getAttrValues().getEncoded()); varAttribute = varUnsignedAttributes.get( new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_certificateRefs.getId())); outputStream.write(varAttribute.getAttrType().getEncoded()); outputStream.write(varAttribute.getAttrValues().getEncoded()); varAttribute = varUnsignedAttributes.get( new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_revocationRefs.getId())); outputStream.write(varAttribute.getAttrType().getEncoded()); outputStream.write(varAttribute.getAttrValues().getEncoded()); escTimeStampContent = outputStream.toByteArray(); signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, escTimeStampContent, signaturePolicy, this.hash); } else { signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, oSi.getSignature(), signaturePolicy, this.hash); } unsignedAttributes.add(signedOrUnsignedAttribute.getValue()); AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes); vNewSigners.remove(oSi); oSi = SignerInformation.replaceUnsignedAttributes(oSi, unsignedAttributesTable); vNewSigners.add(oSi); } } //TODO Estudar este mtodo de contra-assinatura posteriormente if (previewSignature != null && previewSignature.length > 0) { vNewSigners.addAll(cmsPreviewSignedData.getSignerInfos().getSigners()); } SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners); CMSSignedData oSignedData = cmsSignedData; cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore); byte[] result = cmsSignedData.getEncoded(); logger.info(cadesMessagesBundle.getString("info.signature.ok")); return result; } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) { throw new SignerException(ex); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
@Override public byte[] doCounterSign(byte[] previewCMSSignature) { try {/* w w w . ja v a 2s . c o m*/ 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); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESTimeStampSigner.java
License:Open Source License
@Override public byte[] doTimeStampForSignature(byte[] signature) throws SignerException { try {// w w w . j av a2 s . com Security.addProvider(new BouncyCastleProvider()); CMSSignedData cmsSignedData = new CMSSignedData(signature); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); SignerInformation signer = (SignerInformation) it.next(); AttributeFactory attributeFactory = AttributeFactory.getInstance(); ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector(); SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory .factory(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()); signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.getCertificateChain(), signer.getSignature(), signaturePolicy, null); unsignedAttributes.add(signedOrUnsignedAttribute.getValue()); AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes); List<SignerInformation> vNewSigners = new ArrayList<SignerInformation>(); vNewSigners.add(SignerInformation.replaceUnsignedAttributes(signer, unsignedAttributesTable)); SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners); CMSSignedData oSignedData = cmsSignedData; cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore); byte[] result = cmsSignedData.getEncoded(); return result; } catch (CMSException ex) { throw new SignerException(ex.getMessage()); } catch (IOException ex) { throw new SignerException(ex.getMessage()); } }
From source file:org.demoiselle.signer.timestamp.signer.RequestSigner.java
License:Open Source License
/** * Signs a time stamp request/* ww w . j a va 2 s.c o m*/ * * @param privateKey private key to sign with * @param certificates certificate chain * @param request request to be signed * @return The signed request */ public byte[] signRequest(PrivateKey privateKey, Certificate[] certificates, byte[] request, String algorithm) { try { logger.info(timeStampMessagesBundle.getString("info.timestamp.sign.request")); Security.addProvider(new BouncyCastleProvider()); X509Certificate signCert = (X509Certificate) certificates[0]; List<X509Certificate> certList = new ArrayList<>(); certList.add(signCert); // setup the generator CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); String varAlgorithm = null; if (algorithm != null && !algorithm.isEmpty()) { varAlgorithm = algorithm; } else { // If is WINDOWS, is ONLY WORKS with SHA256 if (Configuration.getInstance().getSO().toLowerCase().indexOf("indows") > 0) { logger.info(timeStampMessagesBundle.getString("info.timestamp.winhash")); varAlgorithm = "SHA256withRSA"; } else { logger.info(timeStampMessagesBundle.getString("info.timestamp.linuxhash")); varAlgorithm = "SHA512withRSA"; } } SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder().build(varAlgorithm, privateKey, signCert); generator.addSignerInfoGenerator(signerInfoGenerator); Store<?> certStore = new JcaCertStore(certList); generator.addCertificates(certStore); // Store crlStore = new JcaCRLStore(crlList); // generator.addCRLs(crlStore); // Create the signed data object CMSTypedData data = new CMSProcessableByteArray(request); CMSSignedData signed = generator.generate(data, true); return signed.getEncoded(); } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) { logger.info(ex.getMessage()); } return null; }
From source file:org.eclipse.andmore.android.certmanager.packaging.sign.SignatureBlockFile.java
License:Apache License
/** * Writes this file to an output stream//w ww.j av a2s . com * * @param outputStream * the output stream to write the file * @throws IOException * if an I/O error occurs during the signing process * @throws SignException * if a processing error occurs during the signing process * @throws KeyStoreManagerException * @throws KeyStoreException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws CertificateEncodingException * @throws OperatorCreationException * @throws CMSException */ public void write(OutputStream outputStream) throws IOException, SignException, UnrecoverableKeyException, KeyStoreException, KeyStoreManagerException, NoSuchAlgorithmException, InvalidKeyException, CertificateEncodingException, OperatorCreationException, CMSException { // get certificate from entry X509Certificate[] certChain = { keystoreEntry.getX509Certificate() }; if (certChain.length > 0) { X509Certificate publicKey = certChain[0]; PrivateKey privateKey = keystoreEntry.getPrivateKey(keyEntryPassword); String blockalgorithm = getBlockAlgorithm(); if (!blockalgorithm.equalsIgnoreCase(ISignConstants.DSA) && !blockalgorithm.equalsIgnoreCase(ISignConstants.RSA)) { AndmoreLogger.error(SignatureBlockFile.class, "Signing block algorithm not supported. Key algorithm must be DSA or RSA"); throw new SignException("Signing block algorithm not supported"); } String signatureAlgorithm = ISignConstants.SHA1 + ISignConstants.ALGORITHM_CONNECTOR + blockalgorithm; Security.addProvider(new BouncyCastleProvider()); ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .setDirectSignature(true).build(signer, publicKey)); generator.addCertificates(certs); ByteArrayOutputStream baos = new ByteArrayOutputStream(); signatureFile.write(baos); CMSTypedData cmsdata = new CMSProcessableByteArray(baos.toByteArray()); CMSSignedData signeddata = generator.generate(cmsdata, false); ASN1InputStream asn1 = new ASN1InputStream(signeddata.getEncoded()); DEROutputStream dos = new DEROutputStream(outputStream); dos.writeObject(asn1.readObject()); dos.flush(); dos.close(); asn1.close(); } AndmoreLogger.info(SignatureBlockFile.class, "Created signature block file"); }
From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java
License:Open Source License
@Override public ExtendedCAServiceResponse extendedService(final CryptoToken cryptoToken, final ExtendedCAServiceRequest request) throws ExtendedCAServiceRequestException, IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException { if (log.isTraceEnabled()) { log.trace(">extendedService"); }/*from w w w.j a v a 2s. co m*/ if (!(request instanceof CmsCAServiceRequest)) { throw new IllegalExtendedCAServiceRequestException(); } if (getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) { final String msg = intres.getLocalizedMessage("caservice.notactive", "CMS"); log.error(msg); throw new ExtendedCAServiceNotActiveException(msg); } ExtendedCAServiceResponse returnval = null; final X509Certificate signerCert = (X509Certificate) certificatechain.get(0); final CmsCAServiceRequest serviceReq = (CmsCAServiceRequest) request; // Create the signed data final CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator(); try { byte[] resp = serviceReq.getDoc(); // Add our signer info and sign the message if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_SIGN) != 0) { final List<X509Certificate> x509CertChain = new ArrayList<X509Certificate>(); for (Certificate certificate : certificatechain) { x509CertChain.add((X509Certificate) certificate); } gen1.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(x509CertChain))); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); ASN1ObjectIdentifier oid = AlgorithmTools .getSignAlgOidFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privKey.getAlgorithm()); String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(BouncyCastleProvider.PROVIDER_NAME); ContentSigner contentSigner = signerBuilder.build(privKey); gen1.addSignerInfoGenerator(builder.build(contentSigner, signerCert)); final CMSTypedData msg = new CMSProcessableByteArray(resp); final CMSSignedData s = gen1.generate(msg, true); resp = s.getEncoded(); } if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_ENCRYPT) != 0) { CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(getCMSCertificate()) .setProvider(BouncyCastleProvider.PROVIDER_NAME)); JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder( PKCSObjectIdentifiers.des_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME); CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(resp), jceCMSContentEncryptorBuilder.build()); resp = ed.getEncoded(); } if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_DECRYPT) != 0) { final CMSEnvelopedData ed = new CMSEnvelopedData(resp); final RecipientInformationStore recipients = ed.getRecipientInfos(); final X500Name issuer = X500Name .getInstance(getCMSCertificate().getIssuerX500Principal().getEncoded()); final KeyTransRecipientId id = new KeyTransRecipientId(issuer, getCMSCertificate().getSerialNumber()); final RecipientInformation recipient = recipients.get(id); if (recipient != null) { JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(this.privKey); // Provider for decrypting the symmetric key rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME); rec.setProvider(cryptoToken.getSignProviderName()); // We can use a different provider for decrypting the content, for example of we used a PKCS#11 provider above we could use the BC provider below resp = recipient.getContent(rec); } } returnval = new CmsCAServiceResponse(resp); } catch (CMSException e) { log.error("Error in CmsCAService", e); throw new ExtendedCAServiceRequestException(e); } catch (IOException e) { log.error("Error in CmsCAService", e); throw new ExtendedCAServiceRequestException(e); } catch (OperatorCreationException e) { log.error("Error in CmsCAService", e); throw new ExtendedCAServiceRequestException(e); } catch (CertificateEncodingException e) { log.error("Error in CmsCAService", e); throw new ExtendedCAServiceRequestException(e); } if (log.isTraceEnabled()) { log.trace("<extendedService"); } return returnval; }
From source file:org.ejbca.core.model.ca.caadmin.X509CA.java
License:Open Source License
public byte[] createPKCS7(Certificate cert, boolean includeChain) throws SignRequestSignatureException { // Verify using the CA certificate before returning // If we can not verify the issued certificate using the CA certificate we don't want to issue this certificate // because something is wrong... try {//w ww.ja v a 2 s .c o m if (cert != null) { PublicKey verifyKey; X509Certificate cacert = (X509Certificate) getCACertificate(); if (cacert != null) { verifyKey = cacert.getPublicKey(); } else { verifyKey = getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN); } cert.verify(verifyKey); } } catch (Exception e) { throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?"); } Collection<Certificate> chain = getCertificateChain(); ArrayList<Certificate> certList = new ArrayList<Certificate>(); if (cert != null) { certList.add(cert); } if (includeChain) { certList.addAll(chain); } try { CMSProcessable msg = new CMSProcessableByteArray("EJBCA".getBytes()); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); if (getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN) == null) { String msg1 = "createPKCS7: Private key does not exist!"; log.debug(msg1); throw new SignRequestSignatureException(msg1); } gen.addSigner(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), (X509Certificate) getCACertificate(), CMSSignedGenerator.DIGEST_SHA1); gen.addCertificatesAndCRLs(certs); CMSSignedData s = null; CATokenContainer catoken = getCAToken(); CATokenInfo tokeninfo = getCAInfo().getCATokenInfo(); if (catoken != null && !(tokeninfo instanceof NullCATokenInfo)) { log.debug("createPKCS7: Provider=" + catoken.getProvider() + " using algorithm " + getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN).getAlgorithm()); s = gen.generate(msg, true, catoken.getProvider()); } else { String msg1 = "CA Token does not exist!"; log.debug(msg); throw new SignRequestSignatureException(msg1); } return s.getEncoded(); } catch (CATokenOfflineException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }