use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project poi by apache.
the class PkiTestUtils method generateCertificate.
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;
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));
// .getEncoded()));
return new JcaX509CertificateConverter().getCertificate(certHolder);
}
use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project nifi by apache.
the class OcspCertificateValidator method getOcspStatus.
/**
* Gets the OCSP status for the specified subject and issuer certificates.
*
* @param ocspStatusKey status key
* @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;
}
use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project felix by apache.
the class DPSigner method calculateSignatureBlock.
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();
}
use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project atlas by alibaba.
the class LocalSignedJarBuilder method writeSignatureBlock.
/**
* Write the certificate file with a digital signature.
*/
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
certList.add(publicKey);
JcaCertStore certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm()).build(privateKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).setDirectSignature(true).build(sha1Signer, publicKey));
gen.addCertificates(certs);
CMSSignedData sigData = gen.generate(data, false);
ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
DEROutputStream dos = new DEROutputStream(mOutputJar);
dos.writeObject(asn1.readObject());
dos.flush();
dos.close();
asn1.close();
}
use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project ddf by codice.
the class OcspChecker method generateOcspRequest.
/**
* Creates an {@link OCSPReq} to send to the OCSP server for the given certificate.
*
* @param cert - the certificate to verify
* @return the created OCSP request
* @throws OcspCheckerException after posting an alert to the admin console, if any error occurs
*/
@VisibleForTesting
OCSPReq generateOcspRequest(Certificate cert) throws OcspCheckerException {
try {
X509CertificateHolder issuerCert = resolveIssuerCertificate(cert);
JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
CertificateID certId = new CertificateID(digestCalculator, issuerCert, cert.getSerialNumber().getValue());
OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder();
ocspReqGenerator.addRequest(certId);
return ocspReqGenerator.build();
} catch (OCSPException | OperatorCreationException e) {
throw new OcspCheckerException("Unable to create an OCSP request." + NOT_VERIFIED_MSG, e);
}
}
Aggregations