List of usage examples for org.bouncycastle.operator.jcajce JcaDigestCalculatorProviderBuilder JcaDigestCalculatorProviderBuilder
public JcaDigestCalculatorProviderBuilder()
From source file:net.solarnetwork.pki.bc.BCCertificateService.java
License:Open Source License
@Override public X509Certificate signCertificate(String csrPEM, X509Certificate caCert, PrivateKey privateKey) throws CertificateException { if (!csrPEM.matches("(?is)^\\s*-----BEGIN.*")) { // let's throw in the guards csrPEM = "-----BEGIN CERTIFICATE REQUEST-----\n" + csrPEM + "\n-----END CERTIFICATE REQUEST-----\n"; }/*from w w w .j a v a2 s . c o m*/ PemReader reader = null; try { reader = new PemReader(new StringReader(csrPEM)); PemObject pemObj = reader.readPemObject(); log.debug("Parsed PEM type {}", pemObj.getType()); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(pemObj.getContent()); Date now = new Date(); Date expire = new Date(now.getTime() + (1000L * 60L * 60L * 24L * certificateExpireDays)); X509v3CertificateBuilder builder = new X509v3CertificateBuilder(JcaX500NameUtil.getIssuer(caCert), new BigInteger(String.valueOf(counter.incrementAndGet())), now, expire, csr.getSubject(), csr.getSubjectPublicKeyInfo()); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm); ContentSigner signer; DefaultDigestAlgorithmIdentifierFinder digestAlgFinder = new DefaultDigestAlgorithmIdentifierFinder(); try { DigestCalculatorProvider digestCalcProvider = new JcaDigestCalculatorProviderBuilder() .setProvider(new BouncyCastleProvider()).build(); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils( digestCalcProvider.get(digestAlgFinder.find("SHA-256"))); builder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); builder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(csr.getSubjectPublicKeyInfo())); builder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert)); signer = signerBuilder.build(privateKey); } catch (OperatorException e) { log.error("Error signing CSR {}", csr.getSubject(), e); throw new CertificateException("Error signing CSR" + csr.getSubject() + ": " + e.getMessage()); } catch (CertificateEncodingException e) { log.error("Error signing CSR {}", csr.getSubject().toString(), e); throw new CertificateException("Error signing CSR" + csr.getSubject() + ": " + e.getMessage()); } X509CertificateHolder holder = builder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); try { return converter.getCertificate(holder); } catch (java.security.cert.CertificateException e) { throw new CertificateException("Error creating certificate", e); } } catch (IOException e) { throw new CertificateException("Error signing CSR", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e2) { log.warn("IOException closing PemReader", e2); } } } }
From source file:no.difi.oxalis.as2.util.SignedMimeMessage.java
License:EUPL
void parseSignedMessage() { SMIMESignedParser smimeSignedParser; try {//from w w w.j a v a2 s. co m // MimeMessageHelper.dumpMimePartToFile("/tmp/parseSignedMessage.txt", mimeMessage); smimeSignedParser = new SMIMESignedParser(new JcaDigestCalculatorProviderBuilder().build(), (MimeMultipart) mimeMessage.getContent()); } catch (MessagingException | CMSException | IOException | OperatorCreationException e) { throw new IllegalStateException("Unable to create SMIMESignedParser: " + e.getMessage(), e); } Store certs; try { certs = smimeSignedParser.getCertificates(); } catch (CMSException e) { throw new IllegalStateException("Unable to retrieve the certificates from signed message."); } // // SignerInfo blocks which contain the signatures // SignerInformationStore signerInfos; try { signerInfos = smimeSignedParser.getSignerInfos(); } catch (CMSException e) { throw new IllegalStateException("Unable to get the Signer information from message. " + e.getMessage(), e); } Collection signers = signerInfos.getSigners(); Iterator signersIterator = signers.iterator(); // // Only a single signer, get the first and only certificate // if (signersIterator.hasNext()) { // Retrieves information on first and only signer SignerInformation signer = (SignerInformation) signersIterator.next(); // Retrieves the collection of certificates for first and only signer @SuppressWarnings("unchecked") Collection certCollection = certs.getMatches(signer.getSID()); // Retrieve the first certificate Iterator certIt = certCollection.iterator(); if (certIt.hasNext()) { try { signersX509Certificate = new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate((X509CertificateHolder) certIt.next()); } catch (CertificateException e) { throw new IllegalStateException("Unable to fetch certificate for signer. " + e.getMessage(), e); } } else { throw new IllegalStateException( "Signers certificate was not found, unable to verify the signature"); } // Verify that the signature is correct and that signersIterator was generated when the certificate was current /* try { if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(signersX509Certificate))) { throw new IllegalStateException("Verification of signer failed"); } } catch (CMSException | OperatorCreationException e) { throw new IllegalStateException("Unable to verify the signer. " + e.getMessage(), e); } */ String issuerDN = signersX509Certificate.getIssuerDN().toString(); log.debug("Certificate issued by: " + issuerDN); } else { throw new IllegalStateException("There is no signer information available"); } }
From source file:no.difi.oxalis.as2.util.SMimeBC.java
License:EUPL
public static byte[] createSignature(byte[] digest, SMimeDigestMethod digestMethod, PrivateKey privateKey, X509Certificate certificate) throws OxalisSecurityException { try {/*from w w w.ja va2s . c o m*/ ASN1EncodableVector signedAttributes = new ASN1EncodableVector(); signedAttributes.add(new Attribute(CMSAttributes.contentType, new DERSet(digestMethod.getOid()))); signedAttributes .add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digest)))); signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date())))); AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); signedAttributesTable.toASN1EncodableVector(); DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator( signedAttributesTable); /* Build the SignerInfo generator builder, that will build the generator... that will generate the SignerInformation... */ SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME) .build()); signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(digestMethod.getMethod()) .setProvider(BouncyCastleProvider.PROVIDER_NAME); generator.addSignerInfoGenerator(signerInfoBuilder.build(contentSigner.build(privateKey), new X509CertificateHolder(certificate.getEncoded()))); generator.addCertificates(new JcaCertStore(Collections.singletonList(certificate))); return generator.generate(new CMSAbsentContent()).getEncoded(); } catch (CMSException | IOException | CertificateEncodingException | OperatorCreationException e) { throw new OxalisSecurityException(e.getMessage(), e); } }
From source file:nu.yona.server.subscriptions.rest.AppleMobileConfigSigner.java
License:Mozilla Public License
private SignerInfoGenerator createSignerInfoGenerator() { try {/*from ww w. j a v a2 s.c om*/ ContentSigner sha1Signer = createContentSigner(); JcaDigestCalculatorProviderBuilder digestProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider("BC"); JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder( digestProviderBuilder.build()); return signerInfoGeneratorBuilder.build(sha1Signer, signerCertificate); } catch (CertificateException | OperatorCreationException e) { throw YonaException.unexpected(e); } }
From source file:org.apache.felix.deploymentadmin.itest.util.DPSigner.java
License:Apache License
private byte[] calculateSignatureBlock(PrivateKey privKey, X509Certificate cert, byte[] sfRawBytes) throws Exception { String signatureAlgorithm = getSignatureAlgorithm(privKey); DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().build(); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privKey); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider).build(signer, cert)); gen.addCertificates(new JcaCertStore(Arrays.asList(cert))); CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(sfRawBytes)); return sigData.getEncoded(); }
From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java
License:Apache License
/** * Gets the OCSP status for the specified subject and issuer certificates. * * @param ocspStatusKey status key// w ww . j a v a 2s. c om * @return ocsp status */ private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) { final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate(); final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate(); // initialize the default status final OcspStatus ocspStatus = new OcspStatus(); ocspStatus.setVerificationStatus(VerificationStatus.Unknown); ocspStatus.setValidationStatus(ValidationStatus.Unknown); try { // prepare the request final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber(); final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider("BC").build(); final CertificateID certificateId = new CertificateID( calculatorProviderBuilder.get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber); // generate the request final OCSPReqBuilder requestGenerator = new OCSPReqBuilder(); requestGenerator.addRequest(certificateId); // Create a nonce to avoid replay attack BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, new DEROctetString(nonce.toByteArray())); requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext })); final OCSPReq ocspRequest = requestGenerator.build(); // perform the request final Response response = getClientResponse(ocspRequest); // ensure the request was completed successfully if (Response.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) { logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus())); return ocspStatus; } // interpret the response OCSPResp ocspResponse = new OCSPResp(response.readEntity(InputStream.class)); // verify the response status switch (ocspResponse.getStatus()) { case OCSPRespBuilder.SUCCESSFUL: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful); break; case OCSPRespBuilder.INTERNAL_ERROR: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError); break; case OCSPRespBuilder.MALFORMED_REQUEST: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest); break; case OCSPRespBuilder.SIG_REQUIRED: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired); break; case OCSPRespBuilder.TRY_LATER: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater); break; case OCSPRespBuilder.UNAUTHORIZED: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized); break; default: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown); break; } // only proceed if the response was successful if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) { logger.warn(String.format("OCSP request was unsuccessful (%s).", ocspStatus.getResponseStatus().toString())); return ocspStatus; } // ensure the appropriate response object final Object ocspResponseObject = ocspResponse.getResponseObject(); if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) { logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject)); return ocspStatus; } // get the response object final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); // attempt to locate the responder certificate final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts(); if (responderCertificates.length != 1) { logger.warn(String.format("Unexpected number of OCSP responder certificates: %s", responderCertificates.length)); return ocspStatus; } // get the responder certificate final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate( responderCertificates[0], issuerCertificate); if (trustedResponderCertificate != null) { // verify the response if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC") .build(trustedResponderCertificate.getPublicKey()))) { ocspStatus.setVerificationStatus(VerificationStatus.Verified); } else { ocspStatus.setVerificationStatus(VerificationStatus.Unverified); } } else { ocspStatus.setVerificationStatus(VerificationStatus.Unverified); } // validate the response final SingleResp[] responses = basicOcspResponse.getResponses(); for (SingleResp singleResponse : responses) { final CertificateID responseCertificateId = singleResponse.getCertID(); final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber(); if (responseSerialNumber.equals(subjectSerialNumber)) { Object certStatus = singleResponse.getCertStatus(); // interpret the certificate status if (CertificateStatus.GOOD == certStatus) { ocspStatus.setValidationStatus(ValidationStatus.Good); } else if (certStatus instanceof RevokedStatus) { ocspStatus.setValidationStatus(ValidationStatus.Revoked); } else { ocspStatus.setValidationStatus(ValidationStatus.Unknown); } } } } catch (final OCSPException | IOException | ProcessingException | OperatorCreationException e) { logger.error(e.getMessage(), e); } catch (CertificateException e) { e.printStackTrace(); } return ocspStatus; }
From source file:org.apache.poi.poifs.crypt.PkiTestUtils.java
License:Apache License
static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, Date notBefore, Date notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage) throws IOException, OperatorCreationException, CertificateException { String signatureAlgorithm = "SHA1withRSA"; X500Name issuerName;/*from w w w .ja va 2 s. c om*/ if (issuerCertificate != null) { issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer(); } else { issuerName = new X500Name(subjectDn); } RSAPublicKey rsaPubKey = (RSAPublicKey) subjectPublicKey; RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(), rsaPubKey.getPublicExponent()); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec); DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build() .get(CertificateID.HASH_SHA1); X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(issuerName, new BigInteger(128, new SecureRandom()), notBefore, notAfter, new X500Name(subjectDn), subjectPublicKeyInfo); X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc); SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo); AuthorityKeyIdentifier autKeyId = (issuerCertificate != null) ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded())) : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo); certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId); certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId); if (caFlag) { BasicConstraints bc; if (-1 == pathLength) { bc = new BasicConstraints(true); } else { bc = new BasicConstraints(pathLength); } certificateGenerator.addExtension(Extension.basicConstraints, false, bc); } if (null != crlUri) { int uri = GeneralName.uniformResourceIdentifier; DERIA5String crlUriDer = new DERIA5String(crlUri); GeneralName gn = new GeneralName(uri, crlUriDer); DERSequence gnDer = new DERSequence(gn); GeneralNames gns = GeneralNames.getInstance(gnDer); DistributionPointName dpn = new DistributionPointName(0, gns); DistributionPoint distp = new DistributionPoint(dpn, null, null); DERSequence distpDer = new DERSequence(distp); certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer); } if (null != ocspUri) { int uri = GeneralName.uniformResourceIdentifier; GeneralName ocspName = new GeneralName(uri, ocspUri); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } if (null != keyUsage) { certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage); } JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm); signerBuilder.setProvider("BC"); X509CertificateHolder certHolder = certificateGenerator.build(signerBuilder.build(issuerPrivateKey)); /* * Next certificate factory trick is needed to make sure that the * certificate delivered to the caller is provided by the default * security provider instead of BouncyCastle. If we don't do this trick * we might run into trouble when trying to use the CertPath validator. */ // CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // certificate = (X509Certificate) certificateFactory // .generateCertificate(new ByteArrayInputStream(certificate // .getEncoded())); return new JcaX509CertificateConverter().getCertificate(certHolder); }
From source file:org.apache.poi.poifs.crypt.PkiTestUtils.java
License:Apache License
public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception { DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build() .get(CertificateID.HASH_SHA1); X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded()); CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber()); // request// w w w .jav a 2 s.c o m //create a nonce to avoid replay attack BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis); DEROctetString nonceDer = new DEROctetString(nonce.toByteArray()); Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer); Extensions exts = new Extensions(ext); OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); ocspReqBuilder.addRequest(certId); ocspReqBuilder.setRequestExtensions(exts); OCSPReq ocspReq = ocspReqBuilder.build(); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded()); BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc); basicOCSPRespBuilder.setResponseExtensions(exts); // request processing Req[] requestList = ocspReq.getRequestList(); for (Req ocspRequest : requestList) { CertificateID certificateID = ocspRequest.getCertID(); CertificateStatus certificateStatus = CertificateStatus.GOOD; if (revoked) { certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn); } basicOCSPRespBuilder.addResponse(certificateID, certificateStatus); } // basic response generation X509CertificateHolder[] chain = null; if (!ocspResponderCertificate.equals(issuerCertificate)) { // TODO: HorribleProxy can't convert array input params yet chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder }; } ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC") .build(ocspResponderPrivateKey); BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis)); OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder(); OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp); return ocspResp; }
From source file:org.apache.tika.parser.crypto.Pkcs7Parser.java
License:Apache License
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { try {//from w w w . java2s . c o m DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder() .setProvider("BC").build(); CMSSignedDataParser parser = new CMSSignedDataParser(digestCalculatorProvider, new CloseShieldInputStream(stream)); try { CMSTypedStream content = parser.getSignedContent(); if (content == null) { throw new TikaException("cannot parse detached pkcs7 signature (no signed data to parse)"); } try (InputStream input = content.getContentStream()) { Parser delegate = context.get(Parser.class, EmptyParser.INSTANCE); delegate.parse(input, handler, metadata, context); } } finally { parser.close(); } } catch (OperatorCreationException e) { throw new TikaException("Unable to create DigestCalculatorProvider", e); } catch (CMSException e) { throw new TikaException("Unable to parse pkcs7 signed data", e); } }
From source file:org.bitrepository.protocol.security.BasicMessageSigner.java
License:Open Source License
/** * Sets the privateKeyEntry member and initializes the objects that's needed for signing messages. * @param privateKeyEntry the PrivatKeyEntry holding the private key and certificate needed for creating a signature. */// w w w .jav a2 s. c om public void setPrivateKeyEntry(PrivateKeyEntry privateKeyEntry) { if (privateKeyEntry == null) { return; } this.privateKeyEntry = privateKeyEntry; try { sha512Signer = new JcaContentSignerBuilder(SecurityModuleConstants.SignatureType) .setProvider(SecurityModuleConstants.BC).build(privateKeyEntry.getPrivateKey()); builder = new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(SecurityModuleConstants.BC).build()); builder.setDirectSignature(true); } catch (OperatorCreationException e) { throw new RuntimeException(e.getMessage(), e); } }