use of org.bouncycastle.operator.OperatorCreationException in project nifi by apache.
the class CertificateUtils method generateIssuedCertificate.
/**
* Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
*
* @param dn the distinguished name to use
* @param publicKey the public key to issue the certificate to
* @param extensions extensions extracted from the CSR
* @param issuer the issuer's certificate
* @param issuerKeyPair the issuer's keypair
* @param signingAlgorithm the signing algorithm to use
* @param days the number of days it should be valid for
* @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
* @throws CertificateException if there is an error issuing the certificate
*/
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException {
try {
ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
// Set certificate extensions
// (1) digitalSignature extension
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));
certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
// (2) extendedKeyUsage extension
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
// (3) subjectAlternativeName
if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
}
X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
} catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
throw new CertificateException(e);
}
}
use of org.bouncycastle.operator.OperatorCreationException 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.OperatorCreationException in project athenz by yahoo.
the class InstanceClientRefresh method generateCSR.
public static String generateCSR(String domainName, String serviceName, String instanceId, String dnsSuffix, PrivateKey key) {
final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz";
// now let's generate our dsnName field based on our principal's details
StringBuilder dnsName = new StringBuilder(128);
dnsName.append(serviceName);
dnsName.append('.');
dnsName.append(domainName.replace('.', '-'));
dnsName.append('.');
dnsName.append(dnsSuffix);
GeneralName[] sanArray = new GeneralName[2];
sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString()));
// next we include our instance id
StringBuilder dnsInstance = new StringBuilder(128);
dnsInstance.append(instanceId);
dnsInstance.append(".instanceid.athenz.");
dnsInstance.append(dnsSuffix);
sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString()));
String csr = null;
try {
csr = Crypto.generateX509CSR(key, dn, sanArray);
} catch (OperatorCreationException | IOException ex) {
System.err.println(ex.getMessage());
}
return csr;
}
use of org.bouncycastle.operator.OperatorCreationException in project athenz by yahoo.
the class InstanceClientRegister method generateCSR.
public static String generateCSR(String domainName, String serviceName, String instanceId, String dnsSuffix, PrivateKey key) {
final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz";
// now let's generate our dsnName field based on our principal's details
StringBuilder dnsName = new StringBuilder(128);
dnsName.append(serviceName);
dnsName.append('.');
dnsName.append(domainName.replace('.', '-'));
dnsName.append('.');
dnsName.append(dnsSuffix);
GeneralName[] sanArray = new GeneralName[2];
sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString()));
// next we include our instance id
StringBuilder dnsInstance = new StringBuilder(128);
dnsInstance.append(instanceId);
dnsInstance.append(".instanceid.athenz.");
dnsInstance.append(dnsSuffix);
sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString()));
String csr = null;
try {
csr = Crypto.generateX509CSR(key, dn, sanArray);
} catch (OperatorCreationException | IOException ex) {
System.err.println(ex.getMessage());
}
return csr;
}
use of org.bouncycastle.operator.OperatorCreationException in project Spark by igniterealtime.
the class MutualAuthenticationSettingsPanel method createCertificateSignRequest.
private void createCertificateSignRequest() {
idControll.setUpData(commonNameField.getText(), organizationUnitField.getText(), organizationField.getText(), countryField.getText(), cityField.getText());
try {
KeyPair keyPair = idControll.createKeyPair();
PKCS10CertificationRequest request = idControll.createCSR(keyPair);
PemHelper.saveToPemFile(keyPair, IdentityController.KEY_FILE);
PemHelper.saveToPemFile(request, IdentityController.CSR_FILE);
JOptionPane.showMessageDialog(null, Res.getString("dialog.certificate.request.has.been.created") + IdentityController.SECURITY_DIRECTORY.toString());
} catch (OperatorCreationException | NoSuchAlgorithmException | IOException | NoSuchProviderException e1) {
Log.error("Couldn't create Certificate Signing Request", e1);
}
}
Aggregations